diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..5f63ac6 Binary files /dev/null and b/.DS_Store differ diff --git a/My Mind/.DS_Store b/My Mind/.DS_Store new file mode 100644 index 0000000..25f6abd Binary files /dev/null and b/My Mind/.DS_Store differ diff --git a/My Mind/Cartfile.resolved b/My Mind/Cartfile.resolved new file mode 100644 index 0000000..9ef7909 --- /dev/null +++ b/My Mind/Cartfile.resolved @@ -0,0 +1 @@ +github "ortuman/SwiftForms" "1.8.2" diff --git a/My Mind/Carthage/Build/.SwiftForms.version b/My Mind/Carthage/Build/.SwiftForms.version new file mode 100644 index 0000000..6c6981e --- /dev/null +++ b/My Mind/Carthage/Build/.SwiftForms.version @@ -0,0 +1,18 @@ +{ + "Mac" : [ + + ], + "watchOS" : [ + + ], + "tvOS" : [ + + ], + "commitish" : "1.8.2", + "iOS" : [ + { + "name" : "SwiftForms", + "hash" : "7762f57c5a4174efcced3bed1ae5cee63a9d0be11881e95334c247391ea7d739" + } + ] +} \ No newline at end of file diff --git a/My Mind/Carthage/Build/iOS/28B8EE72-D40C-3E43-B398-AB1B96421070.bcsymbolmap b/My Mind/Carthage/Build/iOS/28B8EE72-D40C-3E43-B398-AB1B96421070.bcsymbolmap new file mode 100644 index 0000000..41109bb --- /dev/null +++ b/My Mind/Carthage/Build/iOS/28B8EE72-D40C-3E43-B398-AB1B96421070.bcsymbolmap @@ -0,0 +1,1552 @@ +BCSymbolMap Version: 2.0 +_$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvpfiTm +_$SSo16UILayoutPriorityaSQSCWa +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP09_bridgeToC1C01_C5CTypeQzyFTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP016_forceBridgeFromC1C_6resulty01_C5CTypeQz_xSgztFZTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP024_conditionallyBridgeFromC1C_6resultSb01_C5CTypeQz_xSgztFZTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP026_unconditionallyBridgeFromC1Cyx01_C5CTypeQzSgFZTW +_$SSo16UILayoutPriorityaSYSCSY8rawValuexSg03RawD0Qz_tcfCTW +_$SSo16UILayoutPriorityaSYSCSY8rawValue03RawD0QzvgTW +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCsACP03_todeF0s0eF0VSgyFTW +_$SSo28UITableViewCellAccessoryTypeVSQSCSQ2eeoiySbx_xtFZTW +_$SSo28UITableViewCellAccessoryTypeVSYSCSY8rawValuexSg03RawG0Qz_tcfCTW +_$SSo28UITableViewCellAccessoryTypeVSYSCSY8rawValue03RawG0QzvgTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP09_bridgeToD1C01_D5CTypeQzyFTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP016_forceBridgeFromD1C_6resulty01_D5CTypeQz_xSgztFZTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP024_conditionallyBridgeFromD1C_6resultSb01_D5CTypeQz_xSgztFZTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP026_unconditionallyBridgeFromD1Cyx01_D5CTypeQzSgFZTW +_$SSo15UIFontTextStyleaSYSCSY8rawValuexSg03RawE0Qz_tcfCTW +_$SSo15UIFontTextStyleaSYSCSY8rawValue03RawE0QzvgTW +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCsACP03_toefG0s0fG0VSgyFTW +_$SSo16UILayoutPriorityaSQSCSQ2eeoiySbx_xtFZTW +_$SSo16UILayoutPriorityaMa +_$SSo16UILayoutPriorityaSYSCWa +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWa +_$SSo8NSNumberCMa +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWa +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWa +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWI +_$SSo28UITableViewCellAccessoryTypeVSQSCWa +_$SSo28UITableViewCellAccessoryTypeVMa +___swift_memcpy8_8 +___swift_noop_void_return +_$SSo28UITableViewCellAccessoryTypeVwet +_$SSo28UITableViewCellAccessoryTypeVwst +_$SSo28UITableViewCellAccessoryTypeVwug +_$SSo28UITableViewCellAccessoryTypeVwup +_$SSo28UITableViewCellAccessoryTypeVwui +_$SSo28UITableViewCellAccessoryTypeVSYSCWa +_$SSo15UIFontTextStyleaSQSCWa +_$SSo16UILayoutPriorityaSHSCSH9hashValueSivgTW +_$SSo16UILayoutPriorityaSHSCSH4hash4intoys6HasherVz_tFTW +_$SSo15UIFontTextStyleaSQSCSQ2eeoiySbx_xtFZTW +_$SSo15UIFontTextStyleaMa +_$SSo15UIFontTextStyleaSYSCWa +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWa +_$SSo8NSStringCMa +_$SSo8NSNumberCMaTm +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWa +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWa +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWI +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWITm +_$SSo16UILayoutPriorityaSHSCWa +_$SSo16UILayoutPriorityaSHSCWI +_$SSo15UIFontTextStyleaSHSCWa +_$SSo15UIFontTextStyleaSHSCWI +_$SSo16UILayoutPriorityaSHSCWITm +_$SSo15UIFontTextStyleaSHSCSH9hashValueSivgTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP09_bridgeToD1C01_D5CTypeQzyFTWTm +_$SSo15UIFontTextStyleaSHSCSH4hash4intoys6HasherVz_tFTW +_$SSSSHsSH4hash4intoys6HasherVz_tFTW +_$SSSSQsSQ2eeoiySbx_xtFZTW +_$SSSSgWOe +_$SSS2eeoiySbSS_SStFZTf4xxd_n +__swift_dead_method_stub +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_token0 +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_token2 +_$S10SwiftForms13FormTitleCellC24defaultVisualConstraintsSaySSGyFTv_ +_$SSo16UILayoutPriorityaSQSCMc +_$SSo16UILayoutPriorityaSQSCWp +_$SSo16UILayoutPriorityaSQSCWG +_$SSo16UILayoutPriorityaSQSCWr +_$SSo16UILayoutPriorityaML +_$SSoMXM +_$SSo16UILayoutPriorityaMn +_$SSo16UILayoutPriorityaN +_$SSo16UILayoutPriorityaSYSCMc +_$SSo16UILayoutPriorityaSYSCWp +_$SSo16UILayoutPriorityaSYSCWG +_$SSo16UILayoutPriorityaSYSCWr +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCMc +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWp +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWG +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWr +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCMc +_$SSo8NSNumberCML +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWp +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWG +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWr +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCMc +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWp +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWG +_$SSo16UILayoutPriorityaABSYSCWL +_$SSo16UILayoutPriorityaABs35_HasCustomAnyHashableRepresentationSCWL +_$SSo28UITableViewCellAccessoryTypeVSQSCMc +_$SSo28UITableViewCellAccessoryTypeVSQSCWp +_$SSo28UITableViewCellAccessoryTypeVSQSCWG +_$SSo28UITableViewCellAccessoryTypeVSQSCWr +_$SSo28UITableViewCellAccessoryTypeVML +_$SSo28UITableViewCellAccessoryTypeVWV +_$SSo28UITableViewCellAccessoryTypeVMn +_$SSo28UITableViewCellAccessoryTypeVN +_$SSo28UITableViewCellAccessoryTypeVSYSCMc +_$SSo28UITableViewCellAccessoryTypeVSYSCWp +_$SSo28UITableViewCellAccessoryTypeVSYSCWG +_$SSo28UITableViewCellAccessoryTypeVSYSCWr +_$SSo15UIFontTextStyleaSQSCMc +_$SSo15UIFontTextStyleaSQSCWp +_$SSo15UIFontTextStyleaSQSCWG +_$SSo15UIFontTextStyleaSQSCWr +_$SSo15UIFontTextStyleaML +_$SSo15UIFontTextStyleaMn +_$SSo15UIFontTextStyleaN +_$SSo15UIFontTextStyleaSYSCMc +_$SSo15UIFontTextStyleaSYSCWp +_$SSo15UIFontTextStyleaSYSCWG +_$SSo15UIFontTextStyleaSYSCWr +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCMc +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWp +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWG +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWr +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCMc +_$SSo8NSStringCML +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWp +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWG +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWr +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCMc +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWp +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWG +_$SSo15UIFontTextStyleaABSYSCWL +_$SSo15UIFontTextStyleaABs35_HasCustomAnyHashableRepresentationSCWL +_$SSo16UILayoutPriorityaSHSCMc +_$SSo16UILayoutPriorityaSHSCWp +_$SSo16UILayoutPriorityaSHSCWG +_$SSo16UILayoutPriorityaABSQSCWL +_$SSo16UILayoutPriorityaSHSCWr +_$SSo15UIFontTextStyleaSHSCMc +_$SSo15UIFontTextStyleaSHSCWp +_$SSo15UIFontTextStyleaSHSCWG +_$SSo15UIFontTextStyleaABSQSCWL +_$SSo15UIFontTextStyleaSHSCWr +_symbolic $S10SwiftForms12FormSelectorP +_$S10SwiftForms12FormSelector_pMF +l_OBJC_LABEL_PROTOCOL_$__TtP10SwiftForms12FormSelector_ +l_OBJC_PROTOCOL_REFERENCE_$__TtP10SwiftForms12FormSelector_ +__swift_FORCE_LOAD_$_swiftUIKit_$_SwiftForms +__swift_FORCE_LOAD_$_swiftFoundation_$_SwiftForms +__swift_FORCE_LOAD_$_swiftDarwin_$_SwiftForms +__swift_FORCE_LOAD_$_swiftObjectiveC_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreFoundation_$_SwiftForms +__swift_FORCE_LOAD_$_swiftDispatch_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreGraphics_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreImage_$_SwiftForms +__swift_FORCE_LOAD_$_swiftMetal_$_SwiftForms +__swift_FORCE_LOAD_$_swiftQuartzCore_$_SwiftForms +_$SSo15UIFontTextStyleaABSHSCWL +_$SSo15UIFontTextStyleaABs20_SwiftNewtypeWrapperSCWL +_$SSo16UILayoutPriorityaABSHSCWL +_$SSo16UILayoutPriorityaABs20_SwiftNewtypeWrapperSCWL +_symbolic So16UILayoutPrioritya +_symbolic $Ss16RawRepresentableP +_symbolic Sf +_$SSo16UILayoutPriorityaSYSCMA +_symbolic $Ss21_ObjectiveCBridgeableP +_symbolic So8NSNumberC +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCMA +_symbolic So28UITableViewCellAccessoryTypeV +_symbolic Si +_$SSo28UITableViewCellAccessoryTypeVSYSCMA +_symbolic So15UIFontTextStylea +_symbolic SS +_$SSo15UIFontTextStyleaSYSCMA +_symbolic So8NSStringC +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCMA +___swift_reflection_version +_symbolic So7NSValueC +_$SSo8NSNumberCMF +_symbolic So8NSObjectC +_$SSo8NSStringCMF +_$SSo16UILayoutPriorityaMF +_$SSo15UIFontTextStyleaMF +l_OBJC_LABEL_PROTOCOL_$_NSObject +l_OBJC_PROTOCOL_REFERENCE_$_NSObject +Apple LLVM version 10.0.0 (clang-1000.11.45.1) +-emit-bc "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift" -supplementary-output-file-map -target arm64-apple-ios8.0 -Xllvm -aarch64-use-tbi -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk -I /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos -F /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos -g -import-underlying-module -module-cache-path /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/ModuleCache.noindex -swift-version 4.2 -O -serialize-debugging-options -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-generated-files.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-own-target-headers.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-all-non-framework-target-headers.hmap -Xcc -ivfsoverlay -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/all-product-headers.yaml -Xcc -iquote -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-project-headers.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos/include -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources/arm64 -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources -Xcc -ivfsoverlay -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/unextended-module-overlay.yaml -Xcc "-working-directory/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms" -module-name SwiftForms -num-threads 4 -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSelector.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormTitleCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSliderCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSectionDescriptor.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormDescriptor.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormBaseCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormLabelCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormTextViewCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormErrorType.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormViewController.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormButtonCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormStepperCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSelectorCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSwitchCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormCheckCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormValueCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormSegmentedControlCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormTextFieldCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormPickerCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormOptionsViewController.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormDateCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/arm64/FormRowDescriptor.bc -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift + +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms +Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1) +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift +== + +$Ss16_UnmanagedStringVss5UInt8VRszrlE12compareASCII2toSiAByADG_tF +$Ss16_UnmanagedStringVss5UInt8VRszrlE12compareASCII2toSiAByADG_tFTf4xx_n +$Ss11_StringGutsV19_unmanagedASCIIViews010_UnmanagedA0Vys5UInt8VGvg +$Ss11_StringGutsV19_unmanagedASCIIViews010_UnmanagedA0Vys5UInt8VGvgTf4x_n +$SSSSQsSQ2eeoiySbx_xtFZTW +$SSSSHsSH4hash4intoys6HasherVz_tFTW +hash +rawValue.get +FormSelector.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers +_bridgeToObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP09_bridgeToA1C01_A5CTypeQzyFTW +$SSo16UILayoutPriorityaSHSCWI +$SSo16UILayoutPriorityaABSQSCWl +$SSo16UILayoutPriorityaSQSCWa +$SSo15UIFontTextStyleaSHSCWa +$SSo16UILayoutPriorityaSHSCWa +$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWI +$SSo16UILayoutPriorityaABs35_HasCustomAnyHashableRepresentationSCWl +$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWa +$SSo16UILayoutPriorityaABSYSCWl +$SSo16UILayoutPriorityaSYSCWa +$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWa +$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWa +$SSo8NSNumberCMa +$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWa +$SSo15UIFontTextStyleaSYSCWa +$SSo15UIFontTextStyleaMa +$SSfSHsSH4hash4intoys6HasherVz_tFTW +$SSf4hash4intoys6HasherVz_tF +hashValue.get +$SSfSHsSH9hashValueSivgTW +$SSo15UIFontTextStyleaSQSCWa +$SSo28UITableViewCellAccessoryTypeVSYSCWa +$SSo28UITableViewCellAccessoryTypeVwui +$SSo28UITableViewCellAccessoryTypeVwup +$SSo28UITableViewCellAccessoryTypeVwug +$SSo28UITableViewCellAccessoryTypeVwst +$SSo28UITableViewCellAccessoryTypeVwet +__swift_noop_void_return +__swift_memcpy8_8 +$SSo28UITableViewCellAccessoryTypeVMa +$SSo28UITableViewCellAccessoryTypeVSQSCWa +$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWa +$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWa +$SSo16UILayoutPriorityaMa +$SSfSQsSQ2eeoiySbx_xtFZTW +_toCustomAnyHashable +$SSo15UIFontTextStyleaABs20_SwiftNewtypeWrapperSCWl +$SSo15UIFontTextStyleaABSHSCWl +init +_unconditionallyBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP026_unconditionallyBridgeFromA1Cyx01_A5CTypeQzSgFZTW +_conditionallyBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP024_conditionallyBridgeFromA1C_6resultSb01_A5CTypeQz_xSgztFZTW +_forceBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP016_forceBridgeFromA1C_6resulty01_A5CTypeQz_xSgztFZTW +$SSiSQsSQ2eeoiySbx_xtFZTW +$SSo16UILayoutPriorityaABs20_SwiftNewtypeWrapperSCWl +$SSo16UILayoutPriorityaABSHSCWl +$SSfs21_ObjectiveCBridgeable10FoundationsAAP026_unconditionallyBridgeFromA1Cyx01_A5CTypeQzSgFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP024_conditionallyBridgeFromA1C_6resultSb01_A5CTypeQz_xSgztFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP016_forceBridgeFromA1C_6resulty01_A5CTypeQz_xSgztFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP09_bridgeToA1C01_A5CTypeQzyFTW +$S10SwiftForms17FormRowDescriptorC5valueyXlSgvpfi +$S10SwiftForms17FormRowDescriptorC5titleSSSgvpfi +$S10SwiftForms17FormRowDescriptorC17DateConfigurationV13dateFormatterSo06NSDateI0CSgvpfi +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationV16didSelectClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationV18optionTitleClosureSSyXlcSgvpfi +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationV15controllerClassyXlXpSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV24visualConstraintsClosureSaySSGAA0c4BaseF0CcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV16didUpdateClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV17willUpdateClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV11placeholderSSSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV9cellClassyXlXpSgvpfi +$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvpfi +$S10SwiftForms12FormDateCellC15hiddenTextField33_C023FAD6768D46095D3739AAF2D78229LLSo06UITextH0Cvpfi +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvpfi +$S10SwiftForms17FormTextFieldCellC17customConstraints33_149870142910A653EE2CFFFC6D820B4ALLSayyXlGvpfi +$S10SwiftForms24FormSegmentedControlCellC17customConstraints33_DBE9D27F80989AD1EAE3BA68E841BE35LLSayyXlGvpfi +$S10SwiftForms13FormValueCellC17customConstraints33_82F16EA997B7B04DB1F3F41F679BB190LLSayyXlGSgvpfi +$S10SwiftForms18FormViewControllerC4formAA0C10DescriptorCvpfi +FormDescriptor.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors +$S10SwiftForms16FormTextViewCellC17customConstraints33_872CBDA890CBCF32517E3701A6021DB5LLSayyXlGSgvpfi +$S10SwiftForms12FormBaseCellC17customConstraints33_94960B1EEBF3E30EC85548629F87883BLLSaySo18NSLayoutConstraintCGvpfi +$S10SwiftForms12FormBaseCellC18formViewControllerAA0cgH0CSgXwvpfi +$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvpfi +$S10SwiftForms14FormDescriptorC8sectionsSayAA0c7SectionD0CGvpfi +$S10SwiftForms21FormSectionDescriptorC16footerViewHeight12CoreGraphics7CGFloatVvpfi +$S10SwiftForms21FormSectionDescriptorC16headerViewHeight12CoreGraphics7CGFloatVvpfi +$S10SwiftForms21FormSectionDescriptorC10footerViewSo6UIViewCSgvpfi +$S10SwiftForms21FormSectionDescriptorC10headerViewSo6UIViewCSgvpfi +$S10SwiftForms21FormSectionDescriptorC11footerTitleSSSgvpfi +$S10SwiftForms21FormSectionDescriptorC11headerTitleSSSgvpfi +$S10SwiftForms21FormSectionDescriptorC4rowsSayAA0c3RowE0CGvpfi +_$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvgTo +___swift_project_boxed_opaque_existential_0 +___swift_destroy_boxed_opaque_existential_0 +_$S10SwiftForms13FormTitleCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormTitleCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormTitleCellCfE +_$S10SwiftForms13FormTitleCellCfETo +_$SSD17dictionaryLiteralSDyxq_Gx_q_td_tcfCSS_So6UIViewCTg5Tf4gd_n +_$SSo7UILabelCML +_$SSo6UIViewCML +_$Ss23_ContiguousArrayStorageCySS_So6UIViewCtGML +_$SSS_So6UIViewCtML +_$Ss23_ContiguousArrayStorageCySSGML +_$S10SwiftFormsMXM +_$S10SwiftForms13FormTitleCellCML +_$S10SwiftForms13FormTitleCellCMf +_symbolic ____ 10SwiftForms13FormTitleCellC +_symbolic 10SwiftForms12FormBaseCellC +_symbolic So7UILabelC +_$S10SwiftForms13FormTitleCellCMF +_$Ss37_HashableTypedNativeDictionaryStorageCySSSo6UIViewCGML +_symbolic So6UIViewC +_$SSo7UILabelCMF +_objc_classes +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift +$S10SwiftForms13FormTitleCellCMa +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_So6UIViewCt_Tg5 +$SSp10initialize9repeating5countyx_SitFSu_Tgq5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_So6UIViewCt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_So6UIViewCt_Tg5 +$Ss37_HashableTypedNativeDictionaryStorageCySSSo6UIViewCGMa +$SSo6UIViewCMa +$SSa9_getCountSiyFSS_So6UIViewCt_Tg5 +deinit +FormTitleCell.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base +defaultVisualConstraints +_allocateUninitializedArray +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSS_Tg5 +$Ss23_ContiguousArrayStorageCySSGMa +constraintsViews +$Ss23_ContiguousArrayStorageCfDSS_So6UIViewCt_Tg5 +$SSS_So6UIViewCtMa +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSS_So6UIViewCt_Tg5 +$Ss23_ContiguousArrayStorageCySS_So6UIViewCtGMa +__swift_destroy_boxed_opaque_existential_0 +__swift_project_boxed_opaque_existential_0 +configure +$SSo7UILabelCMa +titleLabel.get +$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms14FormSliderCellC10sliderViewSo8UISliderCvgTo +_$SSSSgWOy +_$S10SwiftForms14FormSliderCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormSliderCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormSliderCellCfE +_$S10SwiftForms14FormSliderCellCfETo +_$SSa16_copyToNewBuffer8oldCountySi_tFSS_Tg5 +_$S10SwiftForms17FormRowDescriptorC5valueyXlSgvsTf4gn_n +_$S10SwiftForms14FormSliderCellC24defaultVisualConstraintsSaySSGyFTf4d_n +_$S10SwiftForms14FormSliderCellC12valueChangedyySo8UISliderCFTf4dn_n +_$SSo8UISliderCML +_$S10SwiftForms14FormSliderCellCML +_$S10SwiftForms14FormSliderCellCMf +_symbolic ____ 10SwiftForms14FormSliderCellC +_symbolic 10SwiftForms13FormTitleCellC +_symbolic So8UISliderC +_$S10SwiftForms14FormSliderCellCMF +_symbolic So9UIControlC +_$SSo8UISliderCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift +valueChanged +FormSliderCell.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells +rowDescriptor.get +value.set +$S10SwiftForms14FormSliderCellCMa +append +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFSS_Tg5 +$Ss12_ArrayBufferV5countSivsSS_Tg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFSS_Tg5 +$SSa9_getCountSiyFSS_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFSS_Tg5 +update +$SSo8UISliderCMa +sliderView.get +$S10SwiftForms14FormSliderCellC10sliderViewSo8UISliderCvgTo +_$S10SwiftForms21FormSectionDescriptorCML +_$S10SwiftForms21FormSectionDescriptorCMf +_symbolic ____ 10SwiftForms21FormSectionDescriptorC +_symbolic Say10SwiftForms17FormRowDescriptorCG +_symbolic SSSg +_symbolic So6UIViewCSg +_symbolic 12CoreGraphics7CGFloatV +_$S10SwiftForms21FormSectionDescriptorCMF +_symbolic So11UIResponderC +_$SSo6UIViewCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift +FormSectionDescriptor.swift +$S10SwiftForms21FormSectionDescriptorCMa +footerViewHeight.materialize +footerViewHeight.set +footerViewHeight.get +headerViewHeight.materialize +headerViewHeight.set +headerViewHeight.get +footerView.materialize +footerView.set +footerView.get +headerView.materialize +headerView.set +headerView.get +footerTitle.materialize +footerTitle.set +footerTitle.get +headerTitle.materialize +headerTitle.set +headerTitle.get +rows.materialize +rows.set +rows.get +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5 +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms21FormSectionDescriptorC_Tg5 +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5Tm +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_yXlTg5 +_$SSiSQsSQ2eeoiySbx_xtFZTW +_$SSD17dictionaryLiteralSDyxq_Gx_q_td_tcfCSS_yXlTg5Tf4gd_n +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5Tf4xnn_n +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5Tf4nxn_n +_$Ss24_VariantDictionaryBufferOyxq_GSHRzr0_lWOy +_$Ss24_VariantDictionaryBufferOyxq_GSHRzr0_lWOe +_$SSo10HeapObjectVMa +___swift_memcpy16_8 +_$SSo10HeapObjectVwet +_$SSo10HeapObjectVwst +_$SSo26InlineRefCountsPlaceholderaMa +_$S10SwiftForms14FormDescriptorCML +_$S10SwiftForms14FormDescriptorCMf +_symbolic ____ 10SwiftForms14FormDescriptorC +_symbolic Say10SwiftForms21FormSectionDescriptorCG +_$S10SwiftForms14FormDescriptorCMF +_$Ss37_HashableTypedNativeDictionaryStorageCySSyXlGML +_$SSo10HeapObjectVML +_$SSo10HeapObjectVWV +_$SSo10HeapObjectVMn +_$SSo10HeapObjectVN +_$SSo26InlineRefCountsPlaceholderaML +_$SSo26InlineRefCountsPlaceholderaMn +_$SSo26InlineRefCountsPlaceholderaN +_symbolic So10HeapObjectV +_symbolic s13OpaquePointerVSg +_symbolic So26InlineRefCountsPlaceholdera +_$SSo10HeapObjectVMF +_symbolic Su +_$SSo26InlineRefCountsPlaceholderaMF +_$SSo26InlineRefCountsPlaceholderaMB +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift +$SSo26InlineRefCountsPlaceholderaMa +$SSo10HeapObjectVwst +$SSo10HeapObjectVwet +__swift_memcpy16_8 +$SSo10HeapObjectVMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5Tf4nxn_n +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5Tf4xnn_n +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_yXlt_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_yXlt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_yXlt_Tg5 +$Ss37_HashableTypedNativeDictionaryStorageCySSyXlGMa +$SSa9_getCountSiyFSS_yXlt_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_yXlTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFSS_Tg5 +$Ss24_CocoaDictionaryIteratorC4nextyXl_yXltSgyF +$Ss24_UnmanagedAnyObjectArrayVyyXlSicig +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_yXlTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_yXlTg5Tf4nnd_n +$Ss24_CocoaDictionaryIteratorCyABs13_NSDictionary_pcfc +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5 +validateForm +next +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTW10SwiftForms21FormSectionDescriptorC_Tg5 +subscript.get +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa9formIndex5afterySiz_tF10SwiftForms17FormRowDescriptorC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa9formIndex5afterySiz_tF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms17FormRowDescriptorC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyF10SwiftForms17FormRowDescriptorC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa8endIndexSivg10SwiftForms17FormRowDescriptorC_Tg5 +$SSa9_getCountSiyF10SwiftForms17FormRowDescriptorC_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms21FormSectionDescriptorC_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa8endIndexSivg10SwiftForms21FormSectionDescriptorC_Tg5 +makeIterator +$SSayxGs10CollectionsSl10startIndex0C0QzvgTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa10startIndexSivg10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa9_getCountSiyF10SwiftForms21FormSectionDescriptorC_Tg5 +formValues +subscript.set +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5 +__derived_enum_equals +$S10SwiftForms14FormDescriptorCMa +sections.materialize +sections.set +sections.get +title.materialize +title.set +title.get +_$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvmytfU_ +_$S10SwiftForms12FormBaseCellC18formViewControllerAA0cgH0CSgXwvmytfU_ +_$S10SwiftForms12FormBaseCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms12FormBaseCellC5coderACSgSo7NSCoderC_tcfcTo +_$Ss17_dictionaryUpCastySDyq0_q1_GSDyxq_Gs8HashableRzsADR0_r2_lFSS_So6UIViewCSSypTg5 +_$S10SwiftForms12FormBaseCellC17updateConstraintsyyFTo +_$S10SwiftForms12FormBaseCellCfETo +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFSo18NSLayoutConstraintC_Tg5 +_$SSa16_copyToNewBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySo18NSLayoutConstraintCG_Tg5 +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_ypTg5 +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_ypTg5 +_$Ss12_ArrayBufferV18_typeCheckSlowPathyySiFSo18NSLayoutConstraintC_Tg5 +_$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvsTf4gn_n +_$S10SwiftForms12FormBaseCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms12FormBaseCellCSaySSGIeggo_SgWOy +_$S10SwiftForms12FormBaseCellCSaySSGIeggo_SgWOe +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5Tf4xnn_n +_$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5Tf4xnn_n +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5Tf4nnndn_n +_$Ss32DictionaryIteratorRepresentationOySSSo6UIViewCGWOe +_$SypWOb +_$SypSgWOh +_$SypWOc +___swift_assign_boxed_opaque_existential_0 +_$SypSgWOc +_$Ss23_ContiguousArrayStorageCySo15UIBarButtonItemCGML +_$SSo15UIBarButtonItemCML +_$S10SwiftForms12FormBaseCellC17customConstraints33_94960B1EEBF3E30EC85548629F87883BLLSaySo18NSLayoutConstraintCGvpWvd +_$SSo18NSLayoutConstraintCML +_$S10SwiftForms12FormBaseCellCML +_$S10SwiftForms12FormBaseCellCMf +_symbolic ____ 10SwiftForms12FormBaseCellC +_symbolic So15UITableViewCellC +_symbolic 10SwiftForms17FormRowDescriptorCSg +_symbolic 10SwiftForms18FormViewControllerCSgXw +_symbolic SaySo18NSLayoutConstraintCG +_$S10SwiftForms12FormBaseCellCMF +_$Ss23_ContiguousArrayStorageCySo18NSLayoutConstraintCGML +_$Ss37_HashableTypedNativeDictionaryStorageCySSypGML +_symbolic So18NSLayoutConstraintC +_$SSo18NSLayoutConstraintCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift +$SypSgWOc +__swift_assign_boxed_opaque_existential_0 +$SypWOc +$SypSgWOh +$SypWOb +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV8endIndexSivgSo18NSLayoutConstraintC_Tg5 +$SSp12deinitialize5countSvSi_tFSo18NSLayoutConstraintC_Tg5 +$SSp8distance2toSiSpyxG_tFSo18NSLayoutConstraintC_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFSo18NSLayoutConstraintC_Tg5 +$SSo18NSLayoutConstraintCMa +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV5countSivgSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5Tf4xnn_n +$SSp10initialize4from5countySPyxG_SitFSo18NSLayoutConstraintC_Tg5 +$SSp8advanced2bySpyxGSi_tFSo18NSLayoutConstraintC_Tg5 +$SSlsE20_failEarlyRangeCheck_6boundsy5IndexQz_SnyADGtFSnySiG_Tgq5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5Tf4xnn_n +FormBaseCell.swift +$S10SwiftForms12FormBaseCellCMa +rowDescriptor.set +rowDescriptor.didset +$Ss12_ArrayBufferV18_typeCheckSlowPathyySiFSo18NSLayoutConstraintC_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_ypTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFyp_Tg5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_ypTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_ypTg5Tf4nnd_n +$Ss37_HashableTypedNativeDictionaryStorageCySSypGMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_ypTg5 +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySo18NSLayoutConstraintCG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV8capacitySivgSo18NSLayoutConstraintC_Tg5 +$Ss23_ContiguousArrayStorageCySo18NSLayoutConstraintCGMa +$SSa16_copyToNewBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5 +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFSo18NSLayoutConstraintC_Tg5 +updateConstraints +_dictionaryUpCast +$Ss13_UnsafeBitMapV11sizeInWords07forSizeE4BitsS2i_tFZ +$Ss23_NativeDictionaryBufferV12assertingGetyx3key_q_5valuets01_aB5IndexVyxq_GFSS_So6UIViewCTg5 +$SSD5countSivgSS_So6UIViewCTg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTWSo18NSLayoutConstraintC_Tg5 +$SSa9formIndex5afterySiz_tFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWSS_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_Tg5 +removeAll +$Ss12_ArrayBufferV5countSivsSo18NSLayoutConstraintC_Tg5 +$SSa9_getCountSiyFSo18NSLayoutConstraintC_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWSo18NSLayoutConstraintC_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSo18NSLayoutConstraintC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWSo18NSLayoutConstraintC_Tg5 +$SSa8endIndexSivgSo18NSLayoutConstraintC_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_Tg5 +customConstraints.get +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWSS_Tg5 +$SSa8endIndexSivgSS_Tg5 +> +count.get +handleDoneAction +formViewController +formRowCanBecomeFirstResponder +formRowCellHeight +inputAccesoryView +$SSo15UIBarButtonItemCMa +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSo15UIBarButtonItemC_Tg5 +$Ss23_ContiguousArrayStorageCySo15UIBarButtonItemCGMa +firstResponderElement +formViewController.materialize +formViewController.set +formViewController.get +rowDescriptor.materialize +_$S10SwiftForms13FormLabelCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormLabelCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormLabelCellCML +_$S10SwiftForms13FormLabelCellCMf +_symbolic ____ 10SwiftForms13FormLabelCellC +_symbolic 10SwiftForms13FormValueCellC +_$S10SwiftForms13FormLabelCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift +FormLabelCell.swift +$S10SwiftForms13FormLabelCellCMa +_$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms16FormTextViewCellC9textFieldSo06UITextE0CvgTo +_$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms16FormTextViewCellC04textE9DidChangeyySo06UITextE0CFTo +_$S10SwiftForms16FormTextViewCellC5style15reuseIdentifierACSo07UITableeF5StyleV_SSSgtcfcTo +_$S10SwiftForms16FormTextViewCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms16FormTextViewCellCfE +_$S10SwiftForms16FormTextViewCellCfETo +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_So6UIViewCTg5 +_$Ss24_VariantDictionaryBufferO12nativeDelete_11idealBucket6offsetys07_NativebC0Vyxq_G_S2itFSS_So6UIViewCTg5 +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5Tf4xnn_n +_$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5Tf4xn_n +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5Tf4nxn_n +_$S10SwiftForms16FormTextViewCellC5style15reuseIdentifierACSo07UITableeF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms16FormTextViewCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo10UITextViewCML +l_OBJC_LABEL_PROTOCOL_$_UITextViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UITextViewDelegate +_$S10SwiftForms16FormTextViewCellC17customConstraints33_872CBDA890CBCF32517E3701A6021DB5LLSayyXlGSgvpWvd +_$S10SwiftForms16FormTextViewCellCML +_$S10SwiftForms16FormTextViewCellCMf +_symbolic ____ 10SwiftForms16FormTextViewCellC +_symbolic So10UITextViewC +_symbolic SayyXlGSg +_$S10SwiftForms16FormTextViewCellCMF +_symbolic So12UIScrollViewC +_$SSo10UITextViewCMF +l_OBJC_LABEL_PROTOCOL_$_UIScrollViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UIScrollViewDelegate +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift +FormTextViewCell.swift +$S10SwiftForms16FormTextViewCellCMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5Tf4nxn_n +$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5Tf4xn_n +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5Tf4xnn_n +$Ss24_VariantDictionaryBufferO12nativeDelete_11idealBucket6offsetys07_NativebC0Vyxq_G_S2itFSS_So6UIViewCTg5 +$SSp12deinitialize5countSvSi_tFSo6UIViewC_Tg5 +$SSp12deinitialize5countSvSi_tFSS_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_So6UIViewCTg5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_So6UIViewCTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_So6UIViewCTg5Tf4nnd_n +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFSo6UIViewC_Tg5 +textViewDidChange +$SSD11removeValue6forKeyq_Sgx_tFSS_So6UIViewCTg5 +$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5 +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5 +$SSo10UITextViewCMa +textField.get +$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms13FormErrorTypeOSQAASQ2eeoiySbx_xtFZTW +_$S10SwiftForms13FormErrorTypeOSHAASH9hashValueSivgTW +_$S10SwiftForms13FormErrorTypeOSHAASH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP7_domainSSvgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP5_codeSivgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP9_userInfoyXlSgvgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP19_getEmbeddedNSErroryXlSgyFTW +_$SSiSHsSH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms13FormErrorTypeOSHAAWI +___swift_memcpy1_1 +_$S10SwiftForms13FormErrorTypeOwet +_$S10SwiftForms13FormErrorTypeOwst +_$S10SwiftForms13FormErrorTypeOwxs +_$S10SwiftForms13FormErrorTypeOwxg +_$S10SwiftForms13FormErrorTypeOwug +_$S10SwiftForms13FormErrorTypeOwup +_$S10SwiftForms13FormErrorTypeOwui +_$S10SwiftForms13FormErrorTypeOSQAAWp +_$S10SwiftForms13FormErrorTypeOSQAAWG +_$S10SwiftForms13FormErrorTypeOSQAAWr +_$S10SwiftForms13FormErrorTypeOSHAAWp +_$S10SwiftForms13FormErrorTypeOSHAAWG +_$S10SwiftForms13FormErrorTypeOACSQAAWL +_$S10SwiftForms13FormErrorTypeOSHAAWr +_$S10SwiftForms13FormErrorTypeOs0D0AAWp +_$S10SwiftForms13FormErrorTypeOs0D0AAWG +_$S10SwiftForms13FormErrorTypeOs0D0AAWr +_$S10SwiftForms13FormErrorTypeOWV +_$S10SwiftForms13FormErrorTypeOMf +_symbolic ____ 10SwiftForms13FormErrorTypeO +_$S10SwiftForms13FormErrorTypeOMF +_$S10SwiftForms13FormErrorTypeOACs0D0AAWL +_$S10SwiftForms13FormErrorTypeOmML +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift +$S10SwiftForms13FormErrorTypeOMa +$S10SwiftForms13FormErrorTypeOwui +$S10SwiftForms13FormErrorTypeOwup +$S10SwiftForms13FormErrorTypeOwug +$S10SwiftForms13FormErrorTypeOwxg +$S10SwiftForms13FormErrorTypeOwxs +$S10SwiftForms13FormErrorTypeOwst +$S10SwiftForms13FormErrorTypeOwet +__swift_memcpy1_1 +$S10SwiftForms13FormErrorTypeOs0D0AAWa +$S10SwiftForms13FormErrorTypeOSHAAWI +$S10SwiftForms13FormErrorTypeOACSQAAWl +$S10SwiftForms13FormErrorTypeOSQAAWa +$S10SwiftForms13FormErrorTypeOSHAAWa +$SSiSHsSH4hash4intoys6HasherVz_tFTW +_getEmbeddedNSError +_userInfo.get +$S10SwiftForms13FormErrorTypeOACs0D0AAWl +_code.get +_domain.get +$S10SwiftForms13FormErrorTypeOmMa +FormErrorType.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms +combine +_hashValue +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_func0 +_$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvpZfiyyXEfU_ +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_func2 +_$S10SwiftForms18FormViewControllerCACycfcTo +_$S10SwiftForms18FormViewControllerC5styleACSo07UITableD5StyleV_tcfcTo +_$S10SwiftForms18FormViewControllerC7nibName6bundleACSSSg_So8NSBundleCSgtcfcTo +_$S10SwiftForms18FormViewControllerC5coderACSo7NSCoderC_tcfcTo +_$S10SwiftForms18FormViewControllerC11viewDidLoadyyFTo +_$S10SwiftForms18FormViewControllerC16numberOfSections2inSiSo07UITableD0C_tFTo +_$S10SwiftForms18FormViewControllerC05tableD0_21numberOfRowsInSectionSiSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_12cellForRowAtSo07UITableD4CellCSo0kD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerC05tableD0_23titleForHeaderInSectionSSSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_23titleForFooterInSectionSSSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_22viewForHeaderInSectionSo6UIViewCSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_22viewForFooterInSectionSo6UIViewCSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForFooterInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFToTm +_$S10SwiftForms18FormViewControllerC05tableD0_14heightForRowAt12CoreGraphics7CGFloatVSo07UITableD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerC05tableD0_14didSelectRowAtySo07UITableD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerCfETo +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtF10SwiftForms17FormRowDescriptorC0L4TypeO_AF0K8BaseCellCmTg5 +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tF10SwiftForms17FormRowDescriptorC0P4TypeO_AG0O8BaseCellCmTg5 +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tF10SwiftForms17FormRowDescriptorC0M4TypeO_AG0L8BaseCellCmTg5 +_$SSi6offset_10SwiftForms17FormRowDescriptorC7elementtSgWOe +_$SSi6offset_10SwiftForms17FormRowDescriptorC7elementtSgWOy +_$SSD17dictionaryLiteralSDyxq_Gx_q_td_tcfC10SwiftForms17FormRowDescriptorC0F4TypeO_AC0E8BaseCellCmTg5Tf4gd_n +_$S10Foundation9IndexPathV7Storage33_99E5384770E52278DCADDB8A2FD5C86ELLOWOe +_$Ss32DictionaryIteratorRepresentationOySSyXlGWOe +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTf4dnn_n +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForFooterInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTf4dnn_n +_$S10SwiftForms17FormRowDescriptorCIegg_SgWOe +_$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGMa +_$SSi6offset_10SwiftForms21FormSectionDescriptorC7elementtSgWOe +_$SSi6offset_10SwiftForms21FormSectionDescriptorC7elementtSgWOy +_$S10SwiftForms18FormViewControllerC18defaultCellClasses33_A98A5792941355E0FC6070FE05AD0013LLSDyAA0C13RowDescriptorC0O4TypeOAA0c4BaseG0CmGvpZ +_$S10SwiftForms18FormViewControllerCML +_$S10SwiftForms18FormViewControllerCMf +_symbolic ____ 10SwiftForms18FormViewControllerC +_symbolic So21UITableViewControllerC +_symbolic 10SwiftForms14FormDescriptorC +_$S10SwiftForms18FormViewControllerCMF +_$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGML +_$S10SwiftForms12FormBaseCellCmML +_$S10SwiftForms17FormRowDescriptorC0D4TypeOAESHAAWL +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift +$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGMa +$S10SwiftForms17FormRowDescriptorC0D4TypeOAESHAAWl +$S10SwiftForms12FormBaseCellCmMa +tableView +FormViewController.swift +form.get +defaultCellClassForRowType +$S10SwiftForms18FormViewControllerC18defaultCellClasses33_A98A5792941355E0FC6070FE05AD0013LLSDyAA0C13RowDescriptorC0O4TypeOAA0c4BaseG0CmGvau +$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvau +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms17FormRowDescriptorC0oE0O_AF0N8BaseCellCmt_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms17FormRowDescriptorC0lE0O_AE0K8BaseCellCmt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms17FormRowDescriptorC0nG0O_AE0M8BaseCellCmt_Tg5 +$SSa9_getCountSiyF10SwiftForms17FormRowDescriptorC0F4TypeO_AB0E8BaseCellCmt_Tg5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tF10SwiftForms17FormRowDescriptorC0M4TypeO_AG0L8BaseCellCmTg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tF10SwiftForms17FormRowDescriptorC0P4TypeO_AG0O8BaseCellCmTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlF10SwiftForms12FormBaseCellCm_Tg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlF10SwiftForms17FormRowDescriptorC0H4TypeO_Tg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfC10SwiftForms17FormRowDescriptorC0M4TypeO_AH0L8BaseCellCmTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfC10SwiftForms17FormRowDescriptorC0M4TypeO_AH0L8BaseCellCmTg5Tf4nnd_n +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtF10SwiftForms17FormRowDescriptorC0L4TypeO_AF0K8BaseCellCmTg5 +$S10SwiftForms18FormViewControllerCMa +formRowDescriptorAtIndexPath +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms17FormRowDescriptorC_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms17FormRowDescriptorC_Tg5 +formBaseCellClassFromRowDescriptor +$Ss18DictionaryIteratorV11_nativeNextx3key_q_5valuetSgyFSS_yXlTg5 +$Ss23_NativeDictionaryBufferV12assertingGetyx3key_q_5valuets01_aB5IndexVyxq_GFSS_yXlTg5 +numberOfSections +setValue +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSay10SwiftForms21FormSectionDescriptorCG_Tg5 +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSay10SwiftForms17FormRowDescriptorCG_Tg5 +valueForTag +viewDidLoad +form.materialize +form.set +globalinit_33_A98A5792941355E0FC6070FE05AD0013_func2 +$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvpZfiyyXEfU_ +globalinit_33_A98A5792941355E0FC6070FE05AD0013_func0 +_$S10SwiftForms14FormButtonCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormButtonCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormButtonCellCML +_$S10SwiftForms14FormButtonCellCMf +_symbolic ____ 10SwiftForms14FormButtonCellC +_$S10SwiftForms14FormButtonCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift +FormButtonCell.swift +$S10SwiftForms14FormButtonCellCMa +_$S10SwiftForms15FormStepperCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms15FormStepperCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms15FormStepperCellCfE +_$S10SwiftForms15FormStepperCellCfETo +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySSG_Tg5 +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5Tf4nnndn_n +_$S10SwiftForms15FormStepperCellC12valueChangedyySo8UISwitchCFTf4dn_n +_$S10SwiftForms15FormStepperCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$SSo9UIStepperCML +_$S10SwiftForms15FormStepperCellCML +_$S10SwiftForms15FormStepperCellCMf +_symbolic ____ 10SwiftForms15FormStepperCellC +_symbolic So9UIStepperC +_$S10SwiftForms15FormStepperCellCMF +_$SSo9UIStepperCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift +FormStepperCell.swift +$S10SwiftForms15FormStepperCellCMa +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWSS_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSS_Tg5 +$SSp8distance2toSiSpyxG_tFSS_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWSS_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgSS_Tg5 +$SSp10initialize4from5countySPyxG_SitFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWSS_Tg5 +$Ss12_ArrayBufferV8endIndexSivgSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWSS_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFSS_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWSS_Tg5 +$Ss12_ArrayBufferV5countSivgSS_Tg5 +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySSG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWSS_Tg5 +$Ss12_ArrayBufferV8capacitySivgSS_Tg5 +$SSa16_copyToNewBuffer8oldCountySi_tFSS_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5 +$SSds23CustomStringConvertiblessAAP11descriptionSSvgTW +$SSd11descriptionSSvg +$Ss16_float64ToString_5debugSSSd_SbtF +$SSo9UIStepperCMa +countLabel.get +stepperView.get +_$SyXlSSIeggo_SgWOy +_$SyXlSSIeggo_SgWOe +_$S10SwiftForms16FormSelectorCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms16FormSelectorCellC5coderACSgSo7NSCoderC_tcfcTo +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFyXl_Tg5 +_$SSi6offset_yXl7elementtSgWOy +_$SSi6offset_yXl7elementtSgWOe +_$SSayyXlGML +_$SSo16UIViewControllerCML +_$S10SwiftForms16FormSelectorCellCML +_$S10SwiftForms16FormSelectorCellCMf +_symbolic ____ 10SwiftForms16FormSelectorCellC +_$S10SwiftForms16FormSelectorCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift +$S10SwiftForms16FormSelectorCellCMa +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFyXl_Tg5 +FormSelectorCell.swift +$SSo16UIViewControllerCMa +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSayyXlG_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWyXl_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFyXl_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTWyXl_Tg5 +$SSa9formIndex5afterySiz_tFyXl_Tg5 ++= +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFyXl_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFyXl_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWyXl_Tg5 +$SSa8endIndexSivgyXl_Tg5 +$SSa9_getCountSiyFyXl_Tg5 +$SSayyXlGMa +_$S10SwiftForms14FormSwitchCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormSwitchCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormSwitchCellCfE +_$S10SwiftForms14FormSwitchCellCfETo +_$S10SwiftForms14FormSwitchCellC12valueChangedyySo8UISwitchCFTf4dn_n +_$S10SwiftForms14FormSwitchCellCML +_$S10SwiftForms14FormSwitchCellCMf +_symbolic ____ 10SwiftForms14FormSwitchCellC +_symbolic So8UISwitchC +_$S10SwiftForms14FormSwitchCellCMF +_$SSo8UISwitchCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift +FormSwitchCell.swift +$S10SwiftForms14FormSwitchCellCMa +switchView.get +_$S10SwiftForms13FormCheckCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormCheckCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormCheckCellCML +_$S10SwiftForms13FormCheckCellCMf +_symbolic ____ 10SwiftForms13FormCheckCellC +_$S10SwiftForms13FormCheckCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift +$S10SwiftForms13FormCheckCellCMa +FormCheckCell.swift +check +_$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms13FormValueCellC10valueLabelSo7UILabelCvgTo +_$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms13FormValueCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormValueCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormValueCellCfE +_$S10SwiftForms13FormValueCellCfETo +_$Ss27_toStringReadOnlyStreamableySSxs010TextOutputE0RzlFSS_Tg5 +_$Ss26_toStringReadOnlyPrintableySSxs06CustomB11ConvertibleRzlFSi_Tg5 +_$SSS19stringInterpolationS2Sd_tcfCTf4nd_n +_$S10SwiftForms13FormValueCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms13FormValueCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms13FormValueCellC17customConstraints33_82F16EA997B7B04DB1F3F41F679BB190LLSayyXlGSgvpWvd +_$S10SwiftForms13FormValueCellCML +_$S10SwiftForms13FormValueCellCMf +_symbolic ____ 10SwiftForms13FormValueCellC +_$S10SwiftForms13FormValueCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift +FormValueCell.swift +$S10SwiftForms13FormValueCellCMa +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_Tgq5 +$SSa9_getCountSiyFSS_Tgq5 +$Ss26_toStringReadOnlyPrintableySSxs06CustomB11ConvertibleRzlFSi_Tg5 +$SSis23CustomStringConvertiblessAAP11descriptionSSvgTW +$Ss14_int64ToString_5radix9uppercaseSSs5Int64V_AESbtF +$Ss27_toStringReadOnlyStreamableySSxs010TextOutputE0RzlFSS_Tg5 +$SSSs20TextOutputStreamablessAAP5write2toyqd__z_ts0aB6StreamRd__lFTWSS_Tg5 +$SSS5write2toyxz_ts16TextOutputStreamRzlFSS_Tg5 +$SSSs16TextOutputStreamssAAP5writeyySSFTW +valueLabel.get +$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms24FormSegmentedControlCellC09segmentedE0So011UISegmentedE0CvgTo +_$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms24FormSegmentedControlCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTo +_$S10SwiftForms24FormSegmentedControlCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms24FormSegmentedControlCellCfE +_$S10SwiftForms24FormSegmentedControlCellCfETo +_$S10SwiftForms24FormSegmentedControlCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms24FormSegmentedControlCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo18UISegmentedControlCML +_$S10SwiftForms24FormSegmentedControlCellC17customConstraints33_DBE9D27F80989AD1EAE3BA68E841BE35LLSayyXlGvpWvd +_$S10SwiftForms24FormSegmentedControlCellCML +_$S10SwiftForms24FormSegmentedControlCellCMf +_symbolic ____ 10SwiftForms24FormSegmentedControlCellC +_symbolic So18UISegmentedControlC +_symbolic SayyXlG +_$S10SwiftForms24FormSegmentedControlCellCMF +_$SSo18UISegmentedControlCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift +FormSegmentedControlCell.swift +$S10SwiftForms24FormSegmentedControlCellCMa +$SSa29_hoistableIsNativeTypeCheckedSbyFyXl_Tg5 +isEmpty.get +$SSayxGs10CollectionsSl10startIndex0C0QzvgTWyXl_Tg5 +$SSa10startIndexSivgyXl_Tg5 +updateSegmentedControl +=== +$SSo18UISegmentedControlCMa +segmentedControl.get +$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms17FormTextFieldCellC04textE0So06UITextE0CvgTo +_$S10SwiftForms17FormTextFieldCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTo +_$S10SwiftForms17FormTextFieldCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms17FormTextFieldCellCfE +_$S10SwiftForms17FormTextFieldCellCfETo +_$S10SwiftForms17FormTextFieldCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms17FormTextFieldCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo11UITextFieldCML +_$S10SwiftForms17FormTextFieldCellC17customConstraints33_149870142910A653EE2CFFFC6D820B4ALLSayyXlGvpWvd +_$S10SwiftForms17FormTextFieldCellCML +_$S10SwiftForms17FormTextFieldCellCMf +_symbolic ____ 10SwiftForms17FormTextFieldCellC +_symbolic So11UITextFieldC +_$S10SwiftForms17FormTextFieldCellCMF +_$SSo11UITextFieldCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift +FormTextFieldCell.swift +$S10SwiftForms17FormTextFieldCellCMa +editingChanged +$SSo11UITextFieldCMa +$S10SwiftForms17FormTextFieldCellC04textE0So06UITextE0CvgTo +_$S10SwiftForms14FormPickerCellC10pickerView_11titleForRow12forComponentSSSgSo08UIPickerG0C_S2itFTo +_$S10SwiftForms14FormPickerCellC10pickerView_12didSelectRow11inComponentySo08UIPickerG0C_S2itFTo +_$S10SwiftForms14FormPickerCellC18numberOfComponents2inSiSo12UIPickerViewC_tFTo +_$S10SwiftForms14FormPickerCellC10pickerView_23numberOfRowsInComponentSiSo08UIPickerG0C_SitFTo +_$S10SwiftForms14FormPickerCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormPickerCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormPickerCellCfE +_$S10SwiftForms14FormPickerCellCfETo +_$S10SwiftForms14FormPickerCellC10pickerView_11titleForRow12forComponentSSSgSo08UIPickerG0C_S2itFTf4dndn_n +_$S10SwiftForms14FormPickerCellC10pickerView_12didSelectRow11inComponentySo08UIPickerG0C_S2itFTf4dndn_n +_$S10SwiftForms14FormPickerCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms14FormPickerCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms14FormPickerCellC6picker33_509F42A1F3552FA9D46F9A9EE75C8D9BLLSo12UIPickerViewCvpWvd +_$S10SwiftForms14FormPickerCellC15hiddenTextField33_509F42A1F3552FA9D46F9A9EE75C8D9BLLSo06UITextH0CvpWvd +l_OBJC_LABEL_PROTOCOL_$_UIPickerViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UIPickerViewDelegate +l_OBJC_LABEL_PROTOCOL_$_UIPickerViewDataSource +l_OBJC_PROTOCOL_REFERENCE_$_UIPickerViewDataSource +_$S10SwiftForms14FormPickerCellCML +_$S10SwiftForms14FormPickerCellCMf +_symbolic ____ 10SwiftForms14FormPickerCellC +_symbolic So12UIPickerViewC +_$S10SwiftForms14FormPickerCellCMF +_$SSo12UIPickerViewCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift +FormPickerCell.swift +$S10SwiftForms14FormPickerCellCMa +pickerView +numberOfComponents +enumerated +_$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvgTo +_$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvsTo +_$S10SwiftForms29FormOptionsSelectorControllerCACycfcTo +_$S10SwiftForms29FormOptionsSelectorControllerC5coderACSo7NSCoderC_tcfcTo +_$S10SwiftForms29FormOptionsSelectorControllerC11viewDidLoadyyFTo +_$S10SwiftForms29FormOptionsSelectorControllerC16numberOfSections2inSiSo11UITableViewC_tFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_21numberOfRowsInSectionSiSo07UITableH0C_SitFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableH0C_SitFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_12cellForRowAtSo07UITableH4CellCSo0mH0C_10Foundation9IndexPathVtFTo +_$SSa6remove2atxSi_tFyXl_Tg5 +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_14didSelectRowAtySo07UITableH0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms29FormOptionsSelectorControllerC5styleACSo16UITableViewStyleV_tcfcTo +_$S10SwiftForms29FormOptionsSelectorControllerCfETo +_$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFyXl_Tg5 +_$SSa16_copyToNewBuffer8oldCountySi_tFyXl_Tg5 +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VyyXlG_Tg5 +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_21numberOfRowsInSectionSiSo07UITableH0C_SitFTf4ddn_n +_$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5Tf4xnn_n +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5Tf4nnndn_n +_$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_yAMXEfU_Tf4xx_n +_$Ss23_ContiguousArrayStorageCyyXlGML +_$S10SwiftForms29FormOptionsSelectorControllerCML +_$S10SwiftForms29FormOptionsSelectorControllerCMf +_symbolic ____ 10SwiftForms29FormOptionsSelectorControllerC +_symbolic 10SwiftForms12FormBaseCellCSg +_$S10SwiftForms29FormOptionsSelectorControllerCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift +$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_yAMXEfU_Tf4xx_n +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWyXl_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWyXl_Tg5 +$Ss12_ArrayBufferV8endIndexSivgyXl_Tg5 +$SSp12deinitialize5countSvSi_tFyXl_Tg5 +$SSp8distance2toSiSpyxG_tFyXl_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWyXl_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWyXl_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFyXl_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWyXl_Tg5 +$Ss12_ArrayBufferV5countSivgyXl_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5Tf4xnn_n +$SSp10initialize4from5countySPyxG_SitFyXl_Tg5 +$SSp8advanced2bySpyxGSi_tFyXl_Tg5 +FormOptionsViewController.swift +formCell.get +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VyyXlG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWyXl_Tg5 +$Ss12_ArrayBufferV8capacitySivgyXl_Tg5 +$Ss23_ContiguousArrayStorageCyyXlGMa +$SSa16_copyToNewBuffer8oldCountySi_tFyXl_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFyXl_Tg5 +$S10SwiftForms29FormOptionsSelectorControllerCMa +$Ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFyt_Tgq5 +$SSRys5UInt8VGIgy_ACytIegyr_TR +$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_ +$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_yAMXEfU_ +$Ss12_ArrayBufferV5countSivsyXl_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFyXl_Tg5 +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFyXl_Tg5 +index +$SSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKFSayyXlG_Tg5 +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZyXl_Tg5 +$SyXlSbs5Error_pIggdzo_yXlSbsAA_pIegndzo_TR +$S10SwiftForms29FormOptionsSelectorControllerC9tableView_14didSelectRowAtySo07UITableH0C_10Foundation9IndexPathVtFSbyXlXEfU_ +$S10SwiftForms29FormOptionsSelectorControllerC9tableView_12cellForRowAtSo07UITableH4CellCSo0mH0C_10Foundation9IndexPathVtFSbyXlXEfU_ +formCell.materialize +formCell.set +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvsTo +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvgTo +_$S10SwiftForms12FormDateCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms12FormDateCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms12FormDateCellCfE +_$S10SwiftForms12FormDateCellCfETo +_$S10SwiftForms12FormDateCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms12FormDateCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms12FormDateCellC15hiddenTextField33_C023FAD6768D46095D3739AAF2D78229LLSo06UITextH0CvpWvd +_$S10SwiftForms12FormDateCellC10datePicker33_C023FAD6768D46095D3739AAF2D78229LLSo06UIDateG0CvpWvd +_$S10SwiftForms12FormDateCellC07defaultD9Formatter33_C023FAD6768D46095D3739AAF2D78229LLSo06NSDateG0CvpWvd +_$S10SwiftForms12FormDateCellCML +_$S10SwiftForms12FormDateCellCMf +_symbolic ____ 10SwiftForms12FormDateCellC +_symbolic So12UIDatePickerC +_symbolic So15NSDateFormatterC +_$S10SwiftForms12FormDateCellCMF +_$SSo12UIDatePickerCMF +_symbolic So11NSFormatterC +_$SSo15NSDateFormatterCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift +FormDateCell.swift +$S10SwiftForms12FormDateCellCMa +getDateFormatter +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAASQ2eeoiySbx_xtFZTW +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAASH9hashValueSivgTW +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAASH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms17FormRowDescriptorC5valueyXlSgvmytfU_ +_$SSayyXlGWOr +_$S10SwiftForms17FormRowDescriptorC3tag4type5titleACSS_AC0D4TypeOSStcfcTf4xnxn_n +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWI +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwet +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwst +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwxs +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwxg +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwug +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwup +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwui +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwca +_$SSSWOh +___swift_memcpy88_8 +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwta +___swift_copy_outline_existential_box_pointer8 +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwca +___swift_memcpy33_8 +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwca +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwst +___swift_memcpy25_8 +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwca +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwca +___swift_memcpy192_8 +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxs +_$SSayyXlGWOs +_$S10SwiftForms17FormRowDescriptorCIegg_SgWOy +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWp +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWG +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWr +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWp +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWG +_$S10SwiftForms17FormRowDescriptorC0D4TypeOAESQAAWL +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWr +_$S10SwiftForms17FormRowDescriptorCML +_$S10SwiftForms17FormRowDescriptorCMf +_$S10SwiftForms17FormRowDescriptorC0D4TypeOWV +_$S10SwiftForms17FormRowDescriptorC0D4TypeOMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC0D4TypeO +_$S10SwiftForms17FormRowDescriptorC0D4TypeOMF +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC17CellConfigurationV +_symbolic yXlXpSg +_symbolic SDySSyXlG +_symbolic Sb +_symbolic y____cSg 10SwiftForms17FormRowDescriptorC +_symbolic SaySSG10SwiftForms12FormBaseCellCcSg +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC22SelectionConfigurationV +_symbolic SSyXlcSg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC19ButtonConfigurationV +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC20StepperConfigurationV +_symbolic Sd +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC17DateConfigurationV +_symbolic So15NSDateFormatterCSg +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC0D13ConfigurationV +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMF +_symbolic ____ 10SwiftForms17FormRowDescriptorC +_symbolic yXlSg +_$S10SwiftForms17FormRowDescriptorCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMa +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxg +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxs +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwst +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwet +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwta +__swift_memcpy192_8 +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwca +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMa +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwst +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwet +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwta +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwca +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMa +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwst +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwet +__swift_memcpy25_8 +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMa +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwst +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwet +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwta +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwca +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMa +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwst +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwet +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwta +__swift_memcpy33_8 +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwca +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMa +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwst +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwet +__swift_copy_outline_existential_box_pointer8 +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwta +__swift_memcpy88_8 +$SSSWOh +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwca +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC0D4TypeOMa +$S10SwiftForms17FormRowDescriptorC0D4TypeOwui +$S10SwiftForms17FormRowDescriptorC0D4TypeOwup +$S10SwiftForms17FormRowDescriptorC0D4TypeOwug +$S10SwiftForms17FormRowDescriptorC0D4TypeOwxg +$S10SwiftForms17FormRowDescriptorC0D4TypeOwxs +$S10SwiftForms17FormRowDescriptorC0D4TypeOwst +$S10SwiftForms17FormRowDescriptorC0D4TypeOwet +$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWI +$S10SwiftForms17FormRowDescriptorC0D4TypeOAESQAAWl +$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWa +$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWa +FormRowDescriptor.swift +$S10SwiftForms17FormRowDescriptorCMa +$SSayyXlGWOr +value.didset +value.willset +configuration.materialize +configuration.set +configuration.get +value.materialize +value.get +type.get +tag.get +userInfo.materialize +userInfo.set +userInfo.get +date.materialize +date.set +date.get +stepper.materialize +stepper.set +stepper.get +button.materialize +button.set +button.get +selection.materialize +selection.set +selection.get +cell.materialize +cell.set +cell.get +dateFormatter.materialize +dateFormatter.set +dateFormatter.get +continuous.materialize +continuous.set +continuous.get +steps.materialize +steps.set +steps.get +minimumValue.materialize +minimumValue.set +minimumValue.get +maximumValue.materialize +maximumValue.set +maximumValue.get +didSelectClosure.materialize +didSelectClosure.set +didSelectClosure.get +allowsMultipleSelection.materialize +allowsMultipleSelection.set +allowsMultipleSelection.get +optionTitleClosure.materialize +optionTitleClosure.set +optionTitleClosure.get +options.materialize +options.set +options.get +controllerClass.materialize +controllerClass.set +controllerClass.get +visualConstraintsClosure.materialize +visualConstraintsClosure.set +visualConstraintsClosure.get +didUpdateClosure.materialize +didUpdateClosure.set +didUpdateClosure.get +willUpdateClosure.materialize +willUpdateClosure.set +willUpdateClosure.get +required.materialize +required.set +required.get +showsInputToolbar.materialize +showsInputToolbar.set +showsInputToolbar.get +placeholder.materialize +placeholder.set +placeholder.get +appearance.materialize +appearance.set +appearance.get +cellClass.materialize +cellClass.set +cellClass.get +Apple LLVM version 10.0.0 (clang-1000.11.45.5) +/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources/SwiftForms_vers.c +__ZL15__ARCLite__loadv +__ZL58__arclite_NSMutableDictionary__setObject_forKeyedSubscriptP19NSMutableDictionaryP13objc_selectorP11objc_objectS4_ +__ZL22add_image_hook_swiftV1PK11mach_headerl +__ZL42__arclite_NSUndoManagerProxy_isKindOfClassP11objc_objectP13objc_selectorP10objc_class +__ZL30__arclite_NSManagedObject_initP11objc_objectP13objc_selector +__ZL41__arclite_NSManagedObject_allocWithEntityP11objc_objectP13objc_selectorS0_ +__ZL36__arclite_NSManagedObject_allocBatchP11objc_objectP13objc_selectorPS0_S0_j +__ZL37__arclite_NSKKMS_fastIndexForKnownKeyP11objc_objectP13objc_selectorS0_ +__ZL28__arclite_NSKKMS_indexForKeyP11objc_objectP13objc_selectorS0_ +__ZL29__arclite_NSKKsD_objectForKeyP11objc_objectP13objc_selectorS0_ +__ZL35__arclite_NSKKsD_removeObjectForKeyP11objc_objectP13objc_selectorS0_ +__ZL33__arclite_NSKKsD_setObject_forKeyP11objc_objectP13objc_selectorS0_S0_ +__ZL41__arclite_NSKKsD_addEntriesFromDictionaryP11objc_objectP13objc_selectorP12NSDictionary +__ZL28__arclite_objc_readClassPairP10objc_classPK15objc_image_info +__ZL32__arclite_objc_allocateClassPairP10objc_classPKcm +__ZL32__arclite_object_getIndexedIvarsP11objc_object +__ZL23__arclite_objc_getClassPKc +__ZL27__arclite_objc_getMetaClassPKc +__ZL31__arclite_objc_getRequiredClassPKc +__ZL26__arclite_objc_lookUpClassPKc +__ZL26__arclite_objc_getProtocolPKc +__ZL23__arclite_class_getNameP10objc_class +__ZL26__arclite_protocol_getNameP8Protocol +__ZL37__arclite_objc_copyClassNamesForImagePKcPj +__ZL17transcribeMethodsP10objc_classP15glue_class_ro_t +__ZL19transcribeProtocolsP10objc_classP15glue_class_ro_t +__ZL20transcribePropertiesP10objc_classP15glue_class_ro_t +__ZL14initialize_impP11objc_objectP13objc_selector +__ZL18allocateMaybeSwiftP18glue_swift_class_tm +__ZL22copySwiftV1MangledNamePKcb +__ZL13demangledNamePKcb +__ZL16scanMangledFieldRPKcS0_S1_Ri +__ZL30arclite_uninitialized_functionv +__ZL12cxxConstructP11objc_object +__ZL20fixStringForCoreDataP11objc_object +_OBJC_METACLASS_$___ARCLite__ +__ZL24OBJC_CLASS_$___ARCLite__ +__ZL31OBJC_METACLASS_RO_$___ARCLite__ +__non_lazy_classes +__ZL27OBJC_CLASS_RO_$___ARCLite__ +__ZL11_class_name +__ZL32OBJC_$_CLASS_METHODS___ARCLite__ +__ZL17_load_method_name +__ZL17_load_method_type +l_OBJC_PROTOCOL_$___ARCLiteKeyedSubscripting__ +l_OBJC_LABEL_PROTOCOL_$___ARCLiteKeyedSubscripting__ +l_OBJC_PROTOCOL_REFERENCE_$___ARCLiteKeyedSubscripting__ +__ZL30NSUndoManagerProxy_targetClass +__ZL29original_NSManagedObject_init +__ZL40original_NSManagedObject_allocWithEntity +__ZL35original_NSManagedObject_allocBatch +__ZL25NSMutableDictionary_class +__ZL22NSConstantString_class +__ZL14NSString_class +__ZL36original_NSKKMS_fastIndexForKnownKey +__ZL27original_NSKKMS_indexForKey +__ZL28original_NSKKsD_objectForKey +__ZL34original_NSKKsD_removeObjectForKey +__ZL32original_NSKKsD_setObject_forKey +__ZL40original_NSKKsD_addEntriesFromDictionary +__ZZL22add_image_hook_swiftV1PK11mach_headerlE7patches +__ZGVZL22add_image_hook_swiftV1PK11mach_headerlE7patches +__ZL31original_objc_allocateClassPair +__ZL31original_object_getIndexedIvars +__ZL22original_objc_getClass +__ZL26original_objc_getMetaClass +__ZL30original_objc_getRequiredClass +__ZL25original_objc_lookUpClass +__ZL25original_objc_getProtocol +__ZL22original_class_getName +__ZL25original_protocol_getName +__ZL36original_objc_copyClassNamesForImage +__ZL12demangleLock +__ZL9Demangled +/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c++ -arch arm64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=c++11 -Wno-trigraphs -fno-exceptions -fno-rtti -fno-sanitize=vptr -mpascal-strings -Os -Wno-missing-field-initializers -Wmissing-prototypes -Wno-implicit-atomic-properties -Wno-objc-interface-ivars -Wno-arc-repeated-use-of-weak -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-empty-body -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-constant-conversion -Wno-int-conversion -Wno-bool-conversion -Wno-enum-conversion -Wno-float-conversion -Wno-non-literal-null-conversion -Wno-objc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -Wno-c++11-extensions -D NDEBUG=1 -D OBJC_OLD_DISPATCH_PROTOTYPES=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -Winvalid-offsetof -miphoneos-version-min=4.3 -g -fno-threadsafe-statics -Wno-sign-conversion -Wno-infinite-recursion -Wno-move -Wno-comma -Wno-block-capture-autoreleasing -Wno-strict-prototypes -Wno-range-loop-analysis -Wno-semicolon-before-method-body -fembed-bitcode=all -iquote /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-generated-files.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-own-target-headers.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-all-target-headers.hmap -iquote /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-project-headers.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/Symbols/BuiltProducts/include -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/DerivedSources/arm64 -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/DerivedSources -F/Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/Symbols/BuiltProducts -iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk/System/Library/PrivateFrameworks -Wall -Wextra -Wno-gcc-compat -Wno-error=incomplete-umbrella -Wno-error=invalid-ios-deployment-target -Wno-error=incomplete-umbrella -Wno-error=invalid-ios-deployment-target -MMD -MT dependencies -MF /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/arm64/arclite.d --serialize-diagnostics /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/arm64/arclite.dia -c /Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70/source/arclite.mm -o /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/arm64/arclite.o -mlinker-version=409.12 +/Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70/source/arclite.mm +/Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70 +fixStringForCoreData +cxxConstruct +arclite_uninitialized_function +scanMangledField +/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk/usr/include/_ctype.h +__isctype +demangledName +copySwiftV1DemangledName +copySwiftV1MangledName +allocateMaybeSwift +word_align +isSwift +initialize_imp +transcribeProperties +property_list_nth +transcribeProtocols +transcribeMethods +data +method_list_nth +__arclite_objc_copyClassNamesForImage +__arclite_protocol_getName +__arclite_class_getName +__arclite_objc_getProtocol +__arclite_objc_lookUpClass +__arclite_objc_getRequiredClass +__arclite_objc_getMetaClass +__arclite_objc_getClass +__arclite_object_getIndexedIvars +__arclite_objc_allocateClassPair +metaclass +__arclite_objc_readClassPair +transcribeIvars +ivar_list_nth +max +alignment +ro +fastFlags +__arclite_NSKKsD_addEntriesFromDictionary +__arclite_NSKKsD_setObject_forKey +__arclite_NSKKsD_removeObjectForKey +__arclite_NSKKsD_objectForKey +__arclite_NSKKMS_indexForKey +__arclite_NSKKMS_fastIndexForKnownKey +__arclite_NSManagedObject_allocBatch +__arclite_NSManagedObject_allocWithEntity +__arclite_NSManagedObject_init +__arclite_NSUndoManagerProxy_isKindOfClass +add_image_hook_swiftV1 +patch_lazy_pointers +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +__arclite_NSMutableDictionary__setObject_forKeyedSubscript +__ARCLite__load +install_swiftV1 +replaceMethod +install_dict_nil_value +addOrReplaceMethod +keyedGetter diff --git a/My Mind/Carthage/Build/iOS/92E5AB11-5B5A-33E7-8588-365F2FE39CFD.bcsymbolmap b/My Mind/Carthage/Build/iOS/92E5AB11-5B5A-33E7-8588-365F2FE39CFD.bcsymbolmap new file mode 100644 index 0000000..f4e5ef4 --- /dev/null +++ b/My Mind/Carthage/Build/iOS/92E5AB11-5B5A-33E7-8588-365F2FE39CFD.bcsymbolmap @@ -0,0 +1,1640 @@ +BCSymbolMap Version: 2.0 +_$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvpfiTm +_$SSo16UILayoutPriorityaSQSCWa +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP09_bridgeToC1C01_C5CTypeQzyFTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP016_forceBridgeFromC1C_6resulty01_C5CTypeQz_xSgztFZTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP024_conditionallyBridgeFromC1C_6resultSb01_C5CTypeQz_xSgztFZTW +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCsACP026_unconditionallyBridgeFromC1Cyx01_C5CTypeQzSgFZTW +_$SSo16UILayoutPriorityaSYSCSY8rawValuexSg03RawD0Qz_tcfCTW +_$SSo16UILayoutPriorityaSYSCSY8rawValue03RawD0QzvgTW +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCsACP03_todeF0s0eF0VSgyFTW +_$SSo28UITableViewCellAccessoryTypeVSQSCSQ2eeoiySbx_xtFZTW +_$SSo28UITableViewCellAccessoryTypeVSYSCSY8rawValuexSg03RawG0Qz_tcfCTW +_$SSo28UITableViewCellAccessoryTypeVSYSCSY8rawValue03RawG0QzvgTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP09_bridgeToD1C01_D5CTypeQzyFTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP016_forceBridgeFromD1C_6resulty01_D5CTypeQz_xSgztFZTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP024_conditionallyBridgeFromD1C_6resultSb01_D5CTypeQz_xSgztFZTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP026_unconditionallyBridgeFromD1Cyx01_D5CTypeQzSgFZTW +_$SSo15UIFontTextStyleaSYSCSY8rawValuexSg03RawE0Qz_tcfCTW +_$SSo15UIFontTextStyleaSYSCSY8rawValue03RawE0QzvgTW +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCsACP03_toefG0s0fG0VSgyFTW +_$SSo16UILayoutPriorityaSQSCSQ2eeoiySbx_xtFZTW +_$SSo16UILayoutPriorityaMa +_$SSo16UILayoutPriorityaSYSCWa +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWa +_$SSo8NSNumberCMa +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWa +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWa +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWI +_$SSo28UITableViewCellAccessoryTypeVSQSCWa +_$SSo28UITableViewCellAccessoryTypeVMa +___swift_memcpy4_4 +___swift_noop_void_return +_$SSo28UITableViewCellAccessoryTypeVwet +_$SSo28UITableViewCellAccessoryTypeVwst +_$SSo28UITableViewCellAccessoryTypeVwug +_$SSo28UITableViewCellAccessoryTypeVwup +_$SSo28UITableViewCellAccessoryTypeVwui +_$SSo28UITableViewCellAccessoryTypeVSYSCWa +_$SSo15UIFontTextStyleaSQSCWa +_$SSo16UILayoutPriorityaSHSCSH9hashValueSivgTW +_$SSo16UILayoutPriorityaSHSCSH4hash4intoys6HasherVz_tFTW +_$SSo15UIFontTextStyleaSQSCSQ2eeoiySbx_xtFZTW +_$SSo15UIFontTextStyleaMa +_$SSo15UIFontTextStyleaSYSCWa +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWa +_$SSo8NSStringCMa +_$SSo8NSNumberCMaTm +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWa +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWa +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWI +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWITm +_$SSo16UILayoutPriorityaSHSCWa +_$SSo16UILayoutPriorityaSHSCWI +_$SSo15UIFontTextStyleaSHSCWa +_$SSo15UIFontTextStyleaSHSCWI +_$SSo16UILayoutPriorityaSHSCWITm +_$SSo15UIFontTextStyleaSHSCSH9hashValueSivgTW +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCsACP09_bridgeToD1C01_D5CTypeQzyFTWTm +_$SSo15UIFontTextStyleaSHSCSH4hash4intoys6HasherVz_tFTW +_$SSSSHsSH4hash4intoys6HasherVz_tFTW +_$Ss13_StringObjectV8_VariantOWOe +_$SSSSQsSQ2eeoiySbx_xtFZTW +_$SSSSgWOe +_$Ss11_StringGutsV7compare_2toSiAB_ABtFZTf4xxd_n +_$Ss11_StringGutsV7isEqual_2toSbAB_ABtFZTf4xxd_n +_$Ss13_StringObjectV8_VariantOWOy +__swift_dead_method_stub +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_token0 +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_token2 +_$SSo16UILayoutPriorityaSQSCMc +_$SSo16UILayoutPriorityaSQSCWp +_$SSo16UILayoutPriorityaSQSCWG +_$SSo16UILayoutPriorityaSQSCWr +_$SSo16UILayoutPriorityaML +_$SSoMXM +_$SSo16UILayoutPriorityaMn +_$SSo16UILayoutPriorityaN +_$SSo16UILayoutPriorityaSYSCMc +_$SSo16UILayoutPriorityaSYSCWp +_$SSo16UILayoutPriorityaSYSCWG +_$SSo16UILayoutPriorityaSYSCWr +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCMc +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWp +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWG +_$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWr +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCMc +_$SSo8NSNumberCML +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWp +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWG +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWr +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCMc +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWp +_$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWG +_$SSo16UILayoutPriorityaABSYSCWL +_$SSo16UILayoutPriorityaABs35_HasCustomAnyHashableRepresentationSCWL +_$SSo28UITableViewCellAccessoryTypeVSQSCMc +_$SSo28UITableViewCellAccessoryTypeVSQSCWp +_$SSo28UITableViewCellAccessoryTypeVSQSCWG +_$SSo28UITableViewCellAccessoryTypeVSQSCWr +_$SSo28UITableViewCellAccessoryTypeVML +_$SSo28UITableViewCellAccessoryTypeVWV +_$SSo28UITableViewCellAccessoryTypeVMn +_$SSo28UITableViewCellAccessoryTypeVN +_$SSo28UITableViewCellAccessoryTypeVSYSCMc +_$SSo28UITableViewCellAccessoryTypeVSYSCWp +_$SSo28UITableViewCellAccessoryTypeVSYSCWG +_$SSo28UITableViewCellAccessoryTypeVSYSCWr +_$SSo15UIFontTextStyleaSQSCMc +_$SSo15UIFontTextStyleaSQSCWp +_$SSo15UIFontTextStyleaSQSCWG +_$SSo15UIFontTextStyleaSQSCWr +_$SSo15UIFontTextStyleaML +_$SSo15UIFontTextStyleaMn +_$SSo15UIFontTextStyleaN +_$SSo15UIFontTextStyleaSYSCMc +_$SSo15UIFontTextStyleaSYSCWp +_$SSo15UIFontTextStyleaSYSCWG +_$SSo15UIFontTextStyleaSYSCWr +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCMc +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWp +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWG +_$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWr +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCMc +_$SSo8NSStringCML +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWp +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWG +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWr +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCMc +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWp +_$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWG +_$SSo15UIFontTextStyleaABSYSCWL +_$SSo15UIFontTextStyleaABs35_HasCustomAnyHashableRepresentationSCWL +_$SSo16UILayoutPriorityaSHSCMc +_$SSo16UILayoutPriorityaSHSCWp +_$SSo16UILayoutPriorityaSHSCWG +_$SSo16UILayoutPriorityaABSQSCWL +_$SSo16UILayoutPriorityaSHSCWr +_$SSo15UIFontTextStyleaSHSCMc +_$SSo15UIFontTextStyleaSHSCWp +_$SSo15UIFontTextStyleaSHSCWG +_$SSo15UIFontTextStyleaABSQSCWL +_$SSo15UIFontTextStyleaSHSCWr +_symbolic $S10SwiftForms12FormSelectorP +_$S10SwiftForms12FormSelector_pMF +l_OBJC_LABEL_PROTOCOL_$__TtP10SwiftForms12FormSelector_ +l_OBJC_PROTOCOL_REFERENCE_$__TtP10SwiftForms12FormSelector_ +__swift_FORCE_LOAD_$_swiftUIKit_$_SwiftForms +__swift_FORCE_LOAD_$_swiftFoundation_$_SwiftForms +__swift_FORCE_LOAD_$_swiftDarwin_$_SwiftForms +__swift_FORCE_LOAD_$_swiftObjectiveC_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreFoundation_$_SwiftForms +__swift_FORCE_LOAD_$_swiftDispatch_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreGraphics_$_SwiftForms +__swift_FORCE_LOAD_$_swiftCoreImage_$_SwiftForms +__swift_FORCE_LOAD_$_swiftMetal_$_SwiftForms +__swift_FORCE_LOAD_$_swiftQuartzCore_$_SwiftForms +_$SSo15UIFontTextStyleaABSHSCWL +_$SSo15UIFontTextStyleaABs20_SwiftNewtypeWrapperSCWL +_$SSo16UILayoutPriorityaABSHSCWL +_$SSo16UILayoutPriorityaABs20_SwiftNewtypeWrapperSCWL +_symbolic So16UILayoutPrioritya +_symbolic $Ss16RawRepresentableP +_symbolic Sf +_$SSo16UILayoutPriorityaSYSCMA +_symbolic $Ss21_ObjectiveCBridgeableP +_symbolic So8NSNumberC +_$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCMA +_symbolic So28UITableViewCellAccessoryTypeV +_symbolic Si +_$SSo28UITableViewCellAccessoryTypeVSYSCMA +_symbolic So15UIFontTextStylea +_symbolic SS +_$SSo15UIFontTextStyleaSYSCMA +_symbolic So8NSStringC +_$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCMA +___swift_reflection_version +_symbolic So7NSValueC +_$SSo8NSNumberCMF +_symbolic So8NSObjectC +_$SSo8NSStringCMF +_$SSo16UILayoutPriorityaMF +_$SSo15UIFontTextStyleaMF +l_OBJC_LABEL_PROTOCOL_$_NSObject +l_OBJC_PROTOCOL_REFERENCE_$_NSObject +Apple LLVM version 10.0.0 (clang-1000.11.45.1) +-emit-bc "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift" "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift" -supplementary-output-file-map -target armv7-apple-ios8.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk -I /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos -F /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos -g -import-underlying-module -module-cache-path /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/ModuleCache.noindex -swift-version 4.2 -O -serialize-debugging-options -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-generated-files.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-own-target-headers.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-all-non-framework-target-headers.hmap -Xcc -ivfsoverlay -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/all-product-headers.yaml -Xcc -iquote -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/SwiftForms-project-headers.hmap -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/BuildProductsPath/Release-iphoneos/include -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources/armv7 -Xcc -I/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources -Xcc -ivfsoverlay -Xcc /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/unextended-module-overlay.yaml -Xcc "-working-directory/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms" -module-name SwiftForms -num-threads 4 -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSelector.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormTitleCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSliderCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSectionDescriptor.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormDescriptor.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormBaseCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormLabelCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormTextViewCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormErrorType.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormViewController.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormButtonCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormStepperCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSelectorCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSwitchCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormCheckCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormValueCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormSegmentedControlCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormTextFieldCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormPickerCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormOptionsViewController.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormDateCell.bc -o /Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/Objects-normal/armv7/FormRowDescriptor.bc -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift + +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms +Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1) +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift +$Ss11_StringGutsV7isEqual_2toSbAB_ABtFZTf4xxd_n + +$Ss11_StringGutsV7compare_2toSiAB_ABtFZ +$Ss11_StringGutsV7compare_2toSiAB_ABtFZTf4xxd_n +$Ss16_UnmanagedStringVss5UInt8VRszrlE12compareASCII2toSiAByADG_tF +$Ss16_UnmanagedStringVss5UInt8VRszrlE12compareASCII2toSiAByADG_tFTf4xx_n +$Ss11_StringGutsV19_unmanagedASCIIViews010_UnmanagedA0Vys5UInt8VGvg +$Ss11_StringGutsV19_unmanagedASCIIViews010_UnmanagedA0Vys5UInt8VGvgTf4x_n +$SSSSQsSQ2eeoiySbx_xtFZTW +$Ss11_StringGutsV7isEqual_2toSbAB_ABtFZ +$SSSSHsSH4hash4intoys6HasherVz_tFTW +hash +rawValue.get +FormSelector.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers +_bridgeToObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP09_bridgeToA1C01_A5CTypeQzyFTW +$SSo16UILayoutPriorityaSHSCWI +$SSo16UILayoutPriorityaABSQSCWl +$SSo16UILayoutPriorityaSQSCWa +$SSo15UIFontTextStyleaSHSCWa +$SSo16UILayoutPriorityaSHSCWa +$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWI +$SSo16UILayoutPriorityaABs35_HasCustomAnyHashableRepresentationSCWl +$SSo16UILayoutPriorityas35_HasCustomAnyHashableRepresentationSCWa +$SSo16UILayoutPriorityaABSYSCWl +$SSo16UILayoutPriorityaSYSCWa +$SSo15UIFontTextStyleas20_SwiftNewtypeWrapperSCWa +$SSo15UIFontTextStyleas21_ObjectiveCBridgeableSCWa +$SSo8NSNumberCMa +$SSo15UIFontTextStyleas35_HasCustomAnyHashableRepresentationSCWa +$SSo15UIFontTextStyleaSYSCWa +$SSo15UIFontTextStyleaMa +== +$SSfSHsSH4hash4intoys6HasherVz_tFTW +$SSf4hash4intoys6HasherVz_tF +hashValue.get +$SSfSHsSH9hashValueSivgTW +$SSo15UIFontTextStyleaSQSCWa +$SSo28UITableViewCellAccessoryTypeVSYSCWa +$SSo28UITableViewCellAccessoryTypeVwui +$SSo28UITableViewCellAccessoryTypeVwup +$SSo28UITableViewCellAccessoryTypeVwug +$SSo28UITableViewCellAccessoryTypeVwst +$SSo28UITableViewCellAccessoryTypeVwet +__swift_noop_void_return +__swift_memcpy4_4 +$SSo28UITableViewCellAccessoryTypeVMa +$SSo28UITableViewCellAccessoryTypeVSQSCWa +$SSo16UILayoutPriorityas20_SwiftNewtypeWrapperSCWa +$SSo16UILayoutPriorityas21_ObjectiveCBridgeableSCWa +$SSo16UILayoutPriorityaMa +$SSfSQsSQ2eeoiySbx_xtFZTW +_toCustomAnyHashable +$SSo15UIFontTextStyleaABs20_SwiftNewtypeWrapperSCWl +$SSo15UIFontTextStyleaABSHSCWl +init +_unconditionallyBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP026_unconditionallyBridgeFromA1Cyx01_A5CTypeQzSgFZTW +_conditionallyBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP024_conditionallyBridgeFromA1C_6resultSb01_A5CTypeQz_xSgztFZTW +_forceBridgeFromObjectiveC +$SSSs21_ObjectiveCBridgeable10FoundationsAAP016_forceBridgeFromA1C_6resulty01_A5CTypeQz_xSgztFZTW +$SSiSQsSQ2eeoiySbx_xtFZTW +$SSo16UILayoutPriorityaABs20_SwiftNewtypeWrapperSCWl +$SSo16UILayoutPriorityaABSHSCWl +$SSfs21_ObjectiveCBridgeable10FoundationsAAP026_unconditionallyBridgeFromA1Cyx01_A5CTypeQzSgFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP024_conditionallyBridgeFromA1C_6resultSb01_A5CTypeQz_xSgztFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP016_forceBridgeFromA1C_6resulty01_A5CTypeQz_xSgztFZTW +$SSfs21_ObjectiveCBridgeable10FoundationsAAP09_bridgeToA1C01_A5CTypeQzyFTW +$S10SwiftForms17FormRowDescriptorC5valueyXlSgvpfi +$S10SwiftForms17FormRowDescriptorC5titleSSSgvpfi +$S10SwiftForms17FormRowDescriptorC17DateConfigurationV13dateFormatterSo06NSDateI0CSgvpfi +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationV16didSelectClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationV18optionTitleClosureSSyXlcSgvpfi +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationV15controllerClassyXlXpSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV24visualConstraintsClosureSaySSGAA0c4BaseF0CcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV16didUpdateClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV17willUpdateClosureyACcSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV11placeholderSSSgvpfi +$S10SwiftForms17FormRowDescriptorC17CellConfigurationV9cellClassyXlXpSgvpfi +$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvpfi +$S10SwiftForms12FormDateCellC15hiddenTextField33_C023FAD6768D46095D3739AAF2D78229LLSo06UITextH0Cvpfi +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvpfi +$S10SwiftForms17FormTextFieldCellC17customConstraints33_149870142910A653EE2CFFFC6D820B4ALLSayyXlGvpfi +$S10SwiftForms24FormSegmentedControlCellC17customConstraints33_DBE9D27F80989AD1EAE3BA68E841BE35LLSayyXlGvpfi +$S10SwiftForms13FormValueCellC17customConstraints33_82F16EA997B7B04DB1F3F41F679BB190LLSayyXlGSgvpfi +$S10SwiftForms18FormViewControllerC4formAA0C10DescriptorCvpfi +FormDescriptor.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors +$S10SwiftForms16FormTextViewCellC17customConstraints33_872CBDA890CBCF32517E3701A6021DB5LLSayyXlGSgvpfi +$S10SwiftForms12FormBaseCellC17customConstraints33_94960B1EEBF3E30EC85548629F87883BLLSaySo18NSLayoutConstraintCGvpfi +$S10SwiftForms12FormBaseCellC18formViewControllerAA0cgH0CSgXwvpfi +$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvpfi +$S10SwiftForms14FormDescriptorC8sectionsSayAA0c7SectionD0CGvpfi +$S10SwiftForms21FormSectionDescriptorC16footerViewHeight12CoreGraphics7CGFloatVvpfi +$S10SwiftForms21FormSectionDescriptorC16headerViewHeight12CoreGraphics7CGFloatVvpfi +$S10SwiftForms21FormSectionDescriptorC10footerViewSo6UIViewCSgvpfi +$S10SwiftForms21FormSectionDescriptorC10headerViewSo6UIViewCSgvpfi +$S10SwiftForms21FormSectionDescriptorC11footerTitleSSSgvpfi +$S10SwiftForms21FormSectionDescriptorC11headerTitleSSSgvpfi +$S10SwiftForms21FormSectionDescriptorC4rowsSayAA0c3RowE0CGvpfi +_$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvgTo +___swift_project_boxed_opaque_existential_0 +___swift_destroy_boxed_opaque_existential_0 +_$S10SwiftForms13FormTitleCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormTitleCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormTitleCellCfE +_$S10SwiftForms13FormTitleCellCfETo +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_So6UIViewCTg5Tf4nd_n +_$SSo7UILabelCML +_$SSo6UIViewCML +_$Ss23_ContiguousArrayStorageCySS_So6UIViewCtGML +_$SSS_So6UIViewCtML +_$Ss23_ContiguousArrayStorageCySSGML +_$S10SwiftFormsMXM +_$S10SwiftForms13FormTitleCellCML +_$S10SwiftForms13FormTitleCellCMf +_symbolic ____ 10SwiftForms13FormTitleCellC +_symbolic 10SwiftForms12FormBaseCellC +_symbolic So7UILabelC +_$S10SwiftForms13FormTitleCellCMF +_$Ss37_HashableTypedNativeDictionaryStorageCySSSo6UIViewCGML +_symbolic So6UIViewC +_$SSo7UILabelCMF +_objc_classes +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift +$S10SwiftForms13FormTitleCellCMa +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_So6UIViewCTg5Tf4nd_n +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_So6UIViewCt_Tg5 +$SSp10initialize9repeating5countyx_SitFSu_Tgq5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_So6UIViewCt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_So6UIViewCt_Tg5 +$Ss37_HashableTypedNativeDictionaryStorageCySSSo6UIViewCGMa +$SSo6UIViewCMa +$SSa9_getCountSiyFSS_So6UIViewCt_Tg5 +deinit +FormTitleCell.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base +defaultVisualConstraints +_allocateUninitializedArray +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSS_Tg5 +$Ss23_ContiguousArrayStorageCySSGMa +constraintsViews +$Ss23_ContiguousArrayStorageCfDSS_So6UIViewCt_Tg5 +$SSS_So6UIViewCtMa +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_So6UIViewCTg5 +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSS_So6UIViewCt_Tg5 +$Ss23_ContiguousArrayStorageCySS_So6UIViewCtGMa +__swift_destroy_boxed_opaque_existential_0 +__swift_project_boxed_opaque_existential_0 +configure +$SSo7UILabelCMa +titleLabel.get +$S10SwiftForms13FormTitleCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms14FormSliderCellC10sliderViewSo8UISliderCvgTo +_$SSSSgWOy +_$S10SwiftForms14FormSliderCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormSliderCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormSliderCellCfE +_$S10SwiftForms14FormSliderCellCfETo +_$SSa16_copyToNewBuffer8oldCountySi_tFSS_Tg5 +_$S10SwiftForms17FormRowDescriptorC5valueyXlSgvsTf4gn_n +_$S10SwiftForms14FormSliderCellC24defaultVisualConstraintsSaySSGyFTf4d_n +_$S10SwiftForms14FormSliderCellC12valueChangedyySo8UISliderCFTf4dn_n +_$SSo8UISliderCML +_$S10SwiftForms14FormSliderCellCML +_$S10SwiftForms14FormSliderCellCMf +_symbolic ____ 10SwiftForms14FormSliderCellC +_symbolic 10SwiftForms13FormTitleCellC +_symbolic So8UISliderC +_$S10SwiftForms14FormSliderCellCMF +_symbolic So9UIControlC +_$SSo8UISliderCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift +valueChanged +FormSliderCell.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells +rowDescriptor.get +value.set +$S10SwiftForms14FormSliderCellCMa +append +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFSS_Tg5 +$Ss12_ArrayBufferV5countSivsSS_Tg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFSS_Tg5 +$SSa9_getCountSiyFSS_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFSS_Tg5 +update +$SSo8UISliderCMa +sliderView.get +$S10SwiftForms14FormSliderCellC10sliderViewSo8UISliderCvgTo +_$S10SwiftForms21FormSectionDescriptorCML +_$S10SwiftForms21FormSectionDescriptorCMf +_symbolic ____ 10SwiftForms21FormSectionDescriptorC +_symbolic Say10SwiftForms17FormRowDescriptorCG +_symbolic SSSg +_symbolic So6UIViewCSg +_symbolic 12CoreGraphics7CGFloatV +_$S10SwiftForms21FormSectionDescriptorCMF +_symbolic So11UIResponderC +_$SSo6UIViewCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift +FormSectionDescriptor.swift +$S10SwiftForms21FormSectionDescriptorCMa +footerViewHeight.materialize +footerViewHeight.set +footerViewHeight.get +headerViewHeight.materialize +headerViewHeight.set +headerViewHeight.get +footerView.materialize +footerView.set +footerView.get +headerView.materialize +headerView.set +headerView.get +footerTitle.materialize +footerTitle.set +footerTitle.get +headerTitle.materialize +headerTitle.set +headerTitle.get +rows.materialize +rows.set +rows.get +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5 +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms21FormSectionDescriptorC_Tg5 +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5Tm +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_yXlTg5 +_$SSiSQsSQ2eeoiySbx_xtFZTW +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_yXlTg5Tf4nd_n +_$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_yXlTg5Tf4nnd_n +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5Tf4xnn_n +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5Tf4nxn_n +_$Ss24_VariantDictionaryBufferOyxq_GSHRzr0_lWOy +_$Ss24_VariantDictionaryBufferOyxq_GSHRzr0_lWOe +_$SSo10HeapObjectVMa +___swift_memcpy8_4 +_$SSo10HeapObjectVwet +_$SSo10HeapObjectVwst +_$SSo26InlineRefCountsPlaceholderaMa +_$S10SwiftForms14FormDescriptorCML +_$S10SwiftForms14FormDescriptorCMf +_symbolic ____ 10SwiftForms14FormDescriptorC +_symbolic Say10SwiftForms21FormSectionDescriptorCG +_$S10SwiftForms14FormDescriptorCMF +_$Ss37_HashableTypedNativeDictionaryStorageCySSyXlGML +_$SSo10HeapObjectVML +_$SSo10HeapObjectVWV +_$SSo10HeapObjectVMn +_$SSo10HeapObjectVN +_$SSo26InlineRefCountsPlaceholderaML +_$SSo26InlineRefCountsPlaceholderaMn +_$SSo26InlineRefCountsPlaceholderaN +_symbolic So10HeapObjectV +_symbolic s13OpaquePointerVSg +_symbolic So26InlineRefCountsPlaceholdera +_$SSo10HeapObjectVMF +_symbolic Su +_$SSo26InlineRefCountsPlaceholderaMF +_$SSo26InlineRefCountsPlaceholderaMB +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift +$SSo26InlineRefCountsPlaceholderaMa +$SSo10HeapObjectVwst +$SSo10HeapObjectVwet +__swift_memcpy8_4 +$SSo10HeapObjectVMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5Tf4nxn_n +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5Tf4xnn_n +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_yXlTg5Tf4nnd_n +$Ss13_UnsafeBitMapV11sizeInWords07forSizeE4BitsS2i_tFZ +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_yXlTg5Tf4nd_n +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_yXlt_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_yXlt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_yXlt_Tg5 +$Ss37_HashableTypedNativeDictionaryStorageCySSyXlGMa +$SSa9_getCountSiyFSS_yXlt_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_yXlTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFSS_Tg5 +$Ss24_CocoaDictionaryIteratorC4nextyXl_yXltSgyF +$Ss24_UnmanagedAnyObjectArrayVyyXlSicig +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_yXlTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_yXlTg5 +$Ss24_CocoaDictionaryIteratorCyABs13_NSDictionary_pcfc +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiF10SwiftForms17FormRowDescriptorC_Tg5 +validateForm +next +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTW10SwiftForms21FormSectionDescriptorC_Tg5 +subscript.get +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa9formIndex5afterySiz_tF10SwiftForms17FormRowDescriptorC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa9formIndex5afterySiz_tF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms17FormRowDescriptorC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyF10SwiftForms17FormRowDescriptorC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTW10SwiftForms17FormRowDescriptorC_Tg5 +$SSa8endIndexSivg10SwiftForms17FormRowDescriptorC_Tg5 +$SSa9_getCountSiyF10SwiftForms17FormRowDescriptorC_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms21FormSectionDescriptorC_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyF10SwiftForms21FormSectionDescriptorC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa8endIndexSivg10SwiftForms21FormSectionDescriptorC_Tg5 +makeIterator +$SSayxGs10CollectionsSl10startIndex0C0QzvgTW10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa10startIndexSivg10SwiftForms21FormSectionDescriptorC_Tg5 +$SSa9_getCountSiyF10SwiftForms21FormSectionDescriptorC_Tg5 +formValues +subscript.set +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_yXlTg5 +__derived_enum_equals +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZSS_yXlTg5 +$S10SwiftForms14FormDescriptorCMa +sections.materialize +sections.set +sections.get +title.materialize +title.set +title.get +_$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvmytfU_ +_$S10SwiftForms12FormBaseCellC18formViewControllerAA0cgH0CSgXwvmytfU_ +_$S10SwiftForms12FormBaseCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms12FormBaseCellC5coderACSgSo7NSCoderC_tcfcTo +_$Ss17_dictionaryUpCastySDyq0_q1_GSDyxq_Gs8HashableRzsADR0_r2_lFSS_So6UIViewCSSypTg5 +_$S10SwiftForms12FormBaseCellC17updateConstraintsyyFTo +_$S10SwiftForms12FormBaseCellCfETo +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFSo18NSLayoutConstraintC_Tg5 +_$SSa16_copyToNewBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySo18NSLayoutConstraintCG_Tg5 +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_ypTg5 +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_ypTg5 +_$Ss12_ArrayBufferV18_typeCheckSlowPathyySiFSo18NSLayoutConstraintC_Tg5 +_$S10SwiftForms12FormBaseCellC13rowDescriptorAA0c3RowG0CSgvsTf4gn_n +_$S10SwiftForms12FormBaseCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms12FormBaseCellCSaySSGIeggo_SgWOy +_$S10SwiftForms12FormBaseCellCSaySSGIeggo_SgWOe +_$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_ypTg5Tf4nnd_n +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5Tf4xnn_n +_$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5Tf4xnn_n +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5Tf4nnndn_n +_$Ss32DictionaryIteratorRepresentationOySSSo6UIViewCGWOe +_$SypWOb +_$SypSgWOh +_$SypWOc +___swift_assign_boxed_opaque_existential_0 +_$SypSgWOc +_$Ss23_ContiguousArrayStorageCySo15UIBarButtonItemCGML +_$SSo15UIBarButtonItemCML +_$S10SwiftForms12FormBaseCellC17customConstraints33_94960B1EEBF3E30EC85548629F87883BLLSaySo18NSLayoutConstraintCGvpWvd +_$SSo18NSLayoutConstraintCML +_$S10SwiftForms12FormBaseCellCML +_$S10SwiftForms12FormBaseCellCMf +_symbolic ____ 10SwiftForms12FormBaseCellC +_symbolic So15UITableViewCellC +_symbolic 10SwiftForms17FormRowDescriptorCSg +_symbolic 10SwiftForms18FormViewControllerCSgXw +_symbolic SaySo18NSLayoutConstraintCG +_$S10SwiftForms12FormBaseCellCMF +_$Ss23_ContiguousArrayStorageCySo18NSLayoutConstraintCGML +_$Ss37_HashableTypedNativeDictionaryStorageCySSypGML +_symbolic So18NSLayoutConstraintC +_$SSo18NSLayoutConstraintCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift +$SypSgWOc +__swift_assign_boxed_opaque_existential_0 +$SypWOc +$SypSgWOh +$SypWOb +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV8endIndexSivgSo18NSLayoutConstraintC_Tg5 +$SSp12deinitialize5countSvSi_tFSo18NSLayoutConstraintC_Tg5 +$SSp8distance2toSiSpyxG_tFSo18NSLayoutConstraintC_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFSo18NSLayoutConstraintC_Tg5 +$SSo18NSLayoutConstraintCMa +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV5countSivgSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSo18NSLayoutConstraintC_Tg5Tf4xnn_n +$SSp10initialize4from5countySPyxG_SitFSo18NSLayoutConstraintC_Tg5 +$SSp8advanced2bySpyxGSi_tFSo18NSLayoutConstraintC_Tg5 +$SSlsE20_failEarlyRangeCheck_6boundsy5IndexQz_SnyADGtFSnySiG_Tgq5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5Tf4xnn_n +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_ypTg5Tf4nnd_n +FormBaseCell.swift +$S10SwiftForms12FormBaseCellCMa +rowDescriptor.set +rowDescriptor.didset +$Ss12_ArrayBufferV18_typeCheckSlowPathyySiFSo18NSLayoutConstraintC_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_ypTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFyp_Tg5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_ypTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_ypTg5 +$Ss37_HashableTypedNativeDictionaryStorageCySSypGMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_ypTg5 +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySo18NSLayoutConstraintCG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWSo18NSLayoutConstraintC_Tg5 +$Ss12_ArrayBufferV8capacitySivgSo18NSLayoutConstraintC_Tg5 +$Ss23_ContiguousArrayStorageCySo18NSLayoutConstraintCGMa +$SSa16_copyToNewBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySo18NSLayoutConstraintCG_s07_IgnoreK0VyANGTg5 +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFSo18NSLayoutConstraintC_Tg5 +updateConstraints +_dictionaryUpCast +$Ss23_NativeDictionaryBufferV12assertingGetyx3key_q_5valuets01_aB5IndexVyxq_GFSS_So6UIViewCTg5 +$SSD5countSivgSS_So6UIViewCTg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFSo18NSLayoutConstraintC_Tg5 +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTWSo18NSLayoutConstraintC_Tg5 +$SSa9formIndex5afterySiz_tFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWSS_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_Tg5 +removeAll +$Ss12_ArrayBufferV5countSivsSo18NSLayoutConstraintC_Tg5 +$SSa9_getCountSiyFSo18NSLayoutConstraintC_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWSo18NSLayoutConstraintC_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSo18NSLayoutConstraintC_Tg5 +$SSa29_hoistableIsNativeTypeCheckedSbyFSo18NSLayoutConstraintC_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWSo18NSLayoutConstraintC_Tg5 +$SSa8endIndexSivgSo18NSLayoutConstraintC_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFSS_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFSS_Tg5 +customConstraints.get +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWSS_Tg5 +$SSa8endIndexSivgSS_Tg5 +> +count.get +handleDoneAction +formViewController +formRowCanBecomeFirstResponder +formRowCellHeight +inputAccesoryView +$SSo15UIBarButtonItemCMa +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZSo15UIBarButtonItemC_Tg5 +$Ss23_ContiguousArrayStorageCySo15UIBarButtonItemCGMa +firstResponderElement +formViewController.materialize +formViewController.set +formViewController.get +rowDescriptor.materialize +_$S10SwiftForms13FormLabelCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormLabelCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormLabelCellCML +_$S10SwiftForms13FormLabelCellCMf +_symbolic ____ 10SwiftForms13FormLabelCellC +_symbolic 10SwiftForms13FormValueCellC +_$S10SwiftForms13FormLabelCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift +FormLabelCell.swift +$S10SwiftForms13FormLabelCellCMa +_$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms16FormTextViewCellC9textFieldSo06UITextE0CvgTo +_$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms16FormTextViewCellC04textE9DidChangeyySo06UITextE0CFTo +_$S10SwiftForms16FormTextViewCellC5style15reuseIdentifierACSo07UITableeF5StyleV_SSSgtcfcTo +_$S10SwiftForms16FormTextViewCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms16FormTextViewCellCfE +_$S10SwiftForms16FormTextViewCellCfETo +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_So6UIViewCTg5 +_$Ss24_VariantDictionaryBufferO12nativeDelete_11idealBucket6offsetys07_NativebC0Vyxq_G_S2itFSS_So6UIViewCTg5 +_$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_So6UIViewCTg5Tf4nnd_n +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5Tf4xnn_n +_$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5Tf4xn_n +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5Tf4nxn_n +_$S10SwiftForms16FormTextViewCellC5style15reuseIdentifierACSo07UITableeF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms16FormTextViewCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo10UITextViewCML +l_OBJC_LABEL_PROTOCOL_$_UITextViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UITextViewDelegate +_$S10SwiftForms16FormTextViewCellC17customConstraints33_872CBDA890CBCF32517E3701A6021DB5LLSayyXlGSgvpWvd +_$S10SwiftForms16FormTextViewCellCML +_$S10SwiftForms16FormTextViewCellCMf +_symbolic ____ 10SwiftForms16FormTextViewCellC +_symbolic So10UITextViewC +_symbolic SayyXlGSg +_$S10SwiftForms16FormTextViewCellCMF +_symbolic So12UIScrollViewC +_$SSo10UITextViewCMF +l_OBJC_LABEL_PROTOCOL_$_UIScrollViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UIScrollViewDelegate +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift +FormTextViewCell.swift +$S10SwiftForms16FormTextViewCellCMa +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5Tf4nxn_n +$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5Tf4xn_n +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5Tf4xnn_n +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_So6UIViewCTg5Tf4nnd_n +$Ss24_VariantDictionaryBufferO12nativeDelete_11idealBucket6offsetys07_NativebC0Vyxq_G_S2itFSS_So6UIViewCTg5 +$SSp12deinitialize5countSvSi_tFSo6UIViewC_Tg5 +$SSp12deinitialize5countSvSi_tFSS_Tg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tFSS_So6UIViewCTg5 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tFSS_So6UIViewCTg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfCSS_So6UIViewCTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlFSo6UIViewC_Tg5 +textViewDidChange +$SSD11removeValue6forKeyq_Sgx_tFSS_So6UIViewCTg5 +$Ss24_VariantDictionaryBufferO18nativeRemoveObject6forKeyq_Sgx_tFSS_So6UIViewCTg5 +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtFSS_So6UIViewCTg5 +$SSo10UITextViewCMa +textField.get +$S10SwiftForms16FormTextViewCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms13FormErrorTypeOSQAASQ2eeoiySbx_xtFZTW +_$S10SwiftForms13FormErrorTypeOSHAASH9hashValueSivgTW +_$S10SwiftForms13FormErrorTypeOSHAASH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP7_domainSSvgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP5_codeSivgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP9_userInfoyXlSgvgTW +_$S10SwiftForms13FormErrorTypeOs0D0AAsADP19_getEmbeddedNSErroryXlSgyFTW +_$SSiSHsSH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms13FormErrorTypeOSHAAWI +___swift_memcpy1_1 +_$S10SwiftForms13FormErrorTypeOwet +_$S10SwiftForms13FormErrorTypeOwst +_$S10SwiftForms13FormErrorTypeOwxs +_$S10SwiftForms13FormErrorTypeOwxg +_$S10SwiftForms13FormErrorTypeOwug +_$S10SwiftForms13FormErrorTypeOwup +_$S10SwiftForms13FormErrorTypeOwui +_$S10SwiftForms13FormErrorTypeOSQAAWp +_$S10SwiftForms13FormErrorTypeOSQAAWG +_$S10SwiftForms13FormErrorTypeOSQAAWr +_$S10SwiftForms13FormErrorTypeOSHAAWp +_$S10SwiftForms13FormErrorTypeOSHAAWG +_$S10SwiftForms13FormErrorTypeOACSQAAWL +_$S10SwiftForms13FormErrorTypeOSHAAWr +_$S10SwiftForms13FormErrorTypeOs0D0AAWp +_$S10SwiftForms13FormErrorTypeOs0D0AAWG +_$S10SwiftForms13FormErrorTypeOs0D0AAWr +_$S10SwiftForms13FormErrorTypeOWV +_$S10SwiftForms13FormErrorTypeOMf +_symbolic ____ 10SwiftForms13FormErrorTypeO +_$S10SwiftForms13FormErrorTypeOMF +_$S10SwiftForms13FormErrorTypeOACs0D0AAWL +_$S10SwiftForms13FormErrorTypeOmML +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift +$S10SwiftForms13FormErrorTypeOMa +$S10SwiftForms13FormErrorTypeOwui +$S10SwiftForms13FormErrorTypeOwup +$S10SwiftForms13FormErrorTypeOwug +$S10SwiftForms13FormErrorTypeOwxg +$S10SwiftForms13FormErrorTypeOwxs +$S10SwiftForms13FormErrorTypeOwst +$S10SwiftForms13FormErrorTypeOwet +__swift_memcpy1_1 +$S10SwiftForms13FormErrorTypeOs0D0AAWa +$S10SwiftForms13FormErrorTypeOSHAAWI +$S10SwiftForms13FormErrorTypeOACSQAAWl +$S10SwiftForms13FormErrorTypeOSQAAWa +$S10SwiftForms13FormErrorTypeOSHAAWa +$SSiSHsSH4hash4intoys6HasherVz_tFTW +_getEmbeddedNSError +_userInfo.get +$S10SwiftForms13FormErrorTypeOACs0D0AAWl +_code.get +_domain.get +$S10SwiftForms13FormErrorTypeOmMa +FormErrorType.swift +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms +combine +_hashValue +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_func0 +_$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvpZfiyyXEfU_ +_globalinit_33_A98A5792941355E0FC6070FE05AD0013_func2 +_$S10SwiftForms18FormViewControllerCACycfcTo +_$S10SwiftForms18FormViewControllerC5styleACSo07UITableD5StyleV_tcfcTo +_$S10SwiftForms18FormViewControllerC7nibName6bundleACSSSg_So8NSBundleCSgtcfcTo +_$S10SwiftForms18FormViewControllerC5coderACSo7NSCoderC_tcfcTo +_$S10SwiftForms18FormViewControllerC11viewDidLoadyyFTo +_$S10SwiftForms18FormViewControllerC16numberOfSections2inSiSo07UITableD0C_tFTo +_$S10SwiftForms18FormViewControllerC05tableD0_21numberOfRowsInSectionSiSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_12cellForRowAtSo07UITableD4CellCSo0kD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerC05tableD0_23titleForHeaderInSectionSSSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_23titleForFooterInSectionSSSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_22viewForHeaderInSectionSo6UIViewCSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_22viewForFooterInSectionSo6UIViewCSgSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForFooterInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTo +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFToTm +_$S10SwiftForms18FormViewControllerC05tableD0_14heightForRowAt12CoreGraphics7CGFloatVSo07UITableD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerC05tableD0_14didSelectRowAtySo07UITableD0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms18FormViewControllerCfETo +_$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtF10SwiftForms17FormRowDescriptorC0L4TypeO_AF0K8BaseCellCmTg5 +_$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tF10SwiftForms17FormRowDescriptorC0P4TypeO_AG0O8BaseCellCmTg5 +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tF10SwiftForms17FormRowDescriptorC0M4TypeO_AG0L8BaseCellCmTg5 +_$SSi6offset_10SwiftForms17FormRowDescriptorC7elementtSgWOe +_$SSi6offset_10SwiftForms17FormRowDescriptorC7elementtSgWOy +_$S10Foundation9IndexPathV7Storage33_99E5384770E52278DCADDB8A2FD5C86ELLOWOe +_$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfC10SwiftForms17FormRowDescriptorC0M4TypeO_AH0L8BaseCellCmTg5Tf4nnd_n +_$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZ10SwiftForms17FormRowDescriptorC0J4TypeO_AG0I8BaseCellCmTg5Tf4nd_n +_$Ss32DictionaryIteratorRepresentationOySSyXlGWOe +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTf4dnn_n +_$S10SwiftForms18FormViewControllerC05tableD0_24heightForFooterInSection12CoreGraphics7CGFloatVSo07UITableD0C_SitFTf4dnn_n +_$S10SwiftForms17FormRowDescriptorCIegg_SgWOe +_$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGMa +_$SSi6offset_10SwiftForms21FormSectionDescriptorC7elementtSgWOe +_$SSi6offset_10SwiftForms21FormSectionDescriptorC7elementtSgWOy +_$S10SwiftForms18FormViewControllerC18defaultCellClasses33_A98A5792941355E0FC6070FE05AD0013LLSDyAA0C13RowDescriptorC0O4TypeOAA0c4BaseG0CmGvpZ +_$S10SwiftForms18FormViewControllerCML +_$S10SwiftForms18FormViewControllerCMf +_symbolic ____ 10SwiftForms18FormViewControllerC +_symbolic So21UITableViewControllerC +_symbolic 10SwiftForms14FormDescriptorC +_$S10SwiftForms18FormViewControllerCMF +_$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGML +_$S10SwiftForms12FormBaseCellCmML +_$S10SwiftForms17FormRowDescriptorC0D4TypeOAESHAAWL +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift +$Ss37_HashableTypedNativeDictionaryStorageCy10SwiftForms17FormRowDescriptorC0I4TypeOAC0H8BaseCellCmGMa +$S10SwiftForms17FormRowDescriptorC0D4TypeOAESHAAWl +$S10SwiftForms12FormBaseCellCmMa +tableView +FormViewController.swift +form.get +defaultCellClassForRowType +$S10SwiftForms18FormViewControllerC18defaultCellClasses33_A98A5792941355E0FC6070FE05AD0013LLSDyAA0C13RowDescriptorC0O4TypeOAA0c4BaseG0CmGvau +$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvau +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZ10SwiftForms17FormRowDescriptorC0J4TypeO_AG0I8BaseCellCmTg5Tf4nd_n +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF10SwiftForms17FormRowDescriptorC0oE0O_AF0N8BaseCellCmt_Tg5 +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms17FormRowDescriptorC0lE0O_AE0K8BaseCellCmt_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms17FormRowDescriptorC0nG0O_AE0M8BaseCellCmt_Tg5 +$SSa9_getCountSiyF10SwiftForms17FormRowDescriptorC0F4TypeO_AB0E8BaseCellCmt_Tg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfC10SwiftForms17FormRowDescriptorC0M4TypeO_AH0L8BaseCellCmTg5Tf4nnd_n +$Ss23_NativeDictionaryBufferVss8HashableRzrlE12unsafeAddNew3key5valueyx_q_tF10SwiftForms17FormRowDescriptorC0M4TypeO_AG0L8BaseCellCmTg5 +$Ss24_VariantDictionaryBufferO018ensureUniqueNativeC015withBucketCountSb11reallocated_Sb15capacityChangedtSi_tF10SwiftForms17FormRowDescriptorC0P4TypeO_AG0O8BaseCellCmTg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlF10SwiftForms12FormBaseCellCm_Tg5 +$Ss26_forceBridgeFromObjectiveCyxyXl_xmtlF10SwiftForms17FormRowDescriptorC0H4TypeO_Tg5 +$Ss23_NativeDictionaryBufferV17_exactBucketCount7storageAByxq_GSi_s04_RawaB7StorageCtcfC10SwiftForms17FormRowDescriptorC0M4TypeO_AH0L8BaseCellCmTg5 +$Ss24_VariantDictionaryBufferO17nativeUpdateValue_6forKeyq_Sgq__xtF10SwiftForms17FormRowDescriptorC0L4TypeO_AF0K8BaseCellCmTg5 +$S10SwiftForms18FormViewControllerCMa +formRowDescriptorAtIndexPath +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF10SwiftForms17FormRowDescriptorC_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF10SwiftForms17FormRowDescriptorC_Tg5 +formBaseCellClassFromRowDescriptor +$Ss18DictionaryIteratorV11_nativeNextx3key_q_5valuetSgyFSS_yXlTg5 +$Ss23_NativeDictionaryBufferV12assertingGetyx3key_q_5valuets01_aB5IndexVyxq_GFSS_yXlTg5 +numberOfSections +setValue +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSay10SwiftForms21FormSectionDescriptorCG_Tg5 +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSay10SwiftForms17FormRowDescriptorCG_Tg5 +valueForTag +viewDidLoad +form.materialize +form.set +globalinit_33_A98A5792941355E0FC6070FE05AD0013_func2 +$Ss23_NativeDictionaryBufferVss8HashableRzrlE9fromArrayyAByxq_GSayx_q_tGFZ10SwiftForms17FormRowDescriptorC0J4TypeO_AG0I8BaseCellCmTg5 +$S10SwiftForms18FormViewControllerC6__once33_A98A5792941355E0FC6070FE05AD0013LLytvpZfiyyXEfU_ +globalinit_33_A98A5792941355E0FC6070FE05AD0013_func0 +_$S10SwiftForms14FormButtonCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormButtonCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormButtonCellCML +_$S10SwiftForms14FormButtonCellCMf +_symbolic ____ 10SwiftForms14FormButtonCellC +_$S10SwiftForms14FormButtonCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift +FormButtonCell.swift +$S10SwiftForms14FormButtonCellCMa +_$S10SwiftForms15FormStepperCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms15FormStepperCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms15FormStepperCellCfE +_$S10SwiftForms15FormStepperCellCfETo +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySSG_Tg5 +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5Tf4nnndn_n +_$S10SwiftForms15FormStepperCellC12valueChangedyySo8UISwitchCFTf4dn_n +_$S10SwiftForms15FormStepperCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$SSo9UIStepperCML +_$S10SwiftForms15FormStepperCellCML +_$S10SwiftForms15FormStepperCellCMf +_symbolic ____ 10SwiftForms15FormStepperCellC +_symbolic So9UIStepperC +_$S10SwiftForms15FormStepperCellCMF +_$SSo9UIStepperCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift +FormStepperCell.swift +$S10SwiftForms15FormStepperCellCMa +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWSS_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFSS_Tg5 +$SSp8distance2toSiSpyxG_tFSS_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWSS_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgSS_Tg5 +$SSp10initialize4from5countySPyxG_SitFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWSS_Tg5 +$Ss12_ArrayBufferV8endIndexSivgSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWSS_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFSS_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFSS_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWSS_Tg5 +$Ss12_ArrayBufferV5countSivgSS_Tg5 +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VySSG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWSS_Tg5 +$Ss12_ArrayBufferV8capacitySivgSS_Tg5 +$SSa16_copyToNewBuffer8oldCountySi_tFSS_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VySSG_s07_IgnoreK0VySSGTg5 +$SSds23CustomStringConvertiblessAAP11descriptionSSvgTW +$SSo9UIStepperCMa +countLabel.get +stepperView.get +_$SyXlSSIeggo_SgWOy +_$SyXlSSIeggo_SgWOe +_$S10SwiftForms16FormSelectorCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms16FormSelectorCellC5coderACSgSo7NSCoderC_tcfcTo +_$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFyXl_Tg5 +_$SSi6offset_yXl7elementtSgWOy +_$SSi6offset_yXl7elementtSgWOe +_$SSayyXlGML +_$SSo16UIViewControllerCML +_$S10SwiftForms16FormSelectorCellCML +_$S10SwiftForms16FormSelectorCellCMf +_symbolic ____ 10SwiftForms16FormSelectorCellC +_$S10SwiftForms16FormSelectorCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift +$S10SwiftForms16FormSelectorCellCMa +$Ss12_ArrayBufferV19_getElementSlowPathyyXlSiFyXl_Tg5 +FormSelectorCell.swift +$SSo16UIViewControllerCMa +$Ss16IndexingIteratorVyxGs0B8ProtocolsSt4next7ElementQzSgyFTWSayyXlG_Tg5 +$SSayxGs10CollectionsSly7ElementQz5IndexQzcigTWyXl_Tg5 +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFyXl_Tg5 +$SSayxGs10CollectionsSl9formIndex5aftery0C0Qzz_tFTWyXl_Tg5 +$SSa9formIndex5afterySiz_tFyXl_Tg5 ++= +$SSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtFyXl_Tg5 +$Ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtFyXl_Tg5 +$SSayxGs10CollectionsSl8endIndex0C0QzvgTWyXl_Tg5 +$SSa8endIndexSivgyXl_Tg5 +$SSa9_getCountSiyFyXl_Tg5 +$SSayyXlGMa +_$S10SwiftForms14FormSwitchCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormSwitchCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormSwitchCellCfE +_$S10SwiftForms14FormSwitchCellCfETo +_$S10SwiftForms14FormSwitchCellC12valueChangedyySo8UISwitchCFTf4dn_n +_$S10SwiftForms14FormSwitchCellCML +_$S10SwiftForms14FormSwitchCellCMf +_symbolic ____ 10SwiftForms14FormSwitchCellC +_symbolic So8UISwitchC +_$S10SwiftForms14FormSwitchCellCMF +_$SSo8UISwitchCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift +FormSwitchCell.swift +$S10SwiftForms14FormSwitchCellCMa +switchView.get +_$S10SwiftForms13FormCheckCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormCheckCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormCheckCellCML +_$S10SwiftForms13FormCheckCellCMf +_symbolic ____ 10SwiftForms13FormCheckCellC +_$S10SwiftForms13FormCheckCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift +$S10SwiftForms13FormCheckCellCMa +FormCheckCell.swift +check +_$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms13FormValueCellC10valueLabelSo7UILabelCvgTo +_$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms13FormValueCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms13FormValueCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms13FormValueCellCfE +_$S10SwiftForms13FormValueCellCfETo +_$Ss27_toStringReadOnlyStreamableySSxs010TextOutputE0RzlFSS_Tg5 +_$Ss26_toStringReadOnlyPrintableySSxs06CustomB11ConvertibleRzlFSi_Tg5 +_$SSS19stringInterpolationS2Sd_tcfCTf4nd_n +_$S10SwiftForms13FormValueCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms13FormValueCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms13FormValueCellC17customConstraints33_82F16EA997B7B04DB1F3F41F679BB190LLSayyXlGSgvpWvd +_$S10SwiftForms13FormValueCellCML +_$S10SwiftForms13FormValueCellCMf +_symbolic ____ 10SwiftForms13FormValueCellC +_$S10SwiftForms13FormValueCellCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift +FormValueCell.swift +$S10SwiftForms13FormValueCellCMa +$SSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtFSS_Tgq5 +$SSa9_getCountSiyFSS_Tgq5 +$Ss26_toStringReadOnlyPrintableySSxs06CustomB11ConvertibleRzlFSi_Tg5 +$SSis23CustomStringConvertiblessAAP11descriptionSSvgTW +$SSzsE11descriptionSSvgSi_Tgq5 +$Ss14_int64ToString_5radix9uppercaseSSs5Int64V_AESbtF +$Ss27_toStringReadOnlyStreamableySSxs010TextOutputE0RzlFSS_Tg5 +$SSSs20TextOutputStreamablessAAP5write2toyqd__z_ts0aB6StreamRd__lFTWSS_Tg5 +$SSS5write2toyxz_ts16TextOutputStreamRzlFSS_Tg5 +$SSSs16TextOutputStreamssAAP5writeyySSFTW +valueLabel.get +$S10SwiftForms13FormValueCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms24FormSegmentedControlCellC09segmentedE0So011UISegmentedE0CvgTo +_$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgToTm +_$S10SwiftForms24FormSegmentedControlCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTo +_$S10SwiftForms24FormSegmentedControlCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms24FormSegmentedControlCellCfE +_$S10SwiftForms24FormSegmentedControlCellCfETo +_$S10SwiftForms24FormSegmentedControlCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms24FormSegmentedControlCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo18UISegmentedControlCML +_$S10SwiftForms24FormSegmentedControlCellC17customConstraints33_DBE9D27F80989AD1EAE3BA68E841BE35LLSayyXlGvpWvd +_$S10SwiftForms24FormSegmentedControlCellCML +_$S10SwiftForms24FormSegmentedControlCellCMf +_symbolic ____ 10SwiftForms24FormSegmentedControlCellC +_symbolic So18UISegmentedControlC +_symbolic SayyXlG +_$S10SwiftForms24FormSegmentedControlCellCMF +_$SSo18UISegmentedControlCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift +FormSegmentedControlCell.swift +$S10SwiftForms24FormSegmentedControlCellCMa +$SSa29_hoistableIsNativeTypeCheckedSbyFyXl_Tg5 +isEmpty.get +$SSayxGs10CollectionsSl10startIndex0C0QzvgTWyXl_Tg5 +$SSa10startIndexSivgyXl_Tg5 +updateSegmentedControl +=== +$SSo18UISegmentedControlCMa +segmentedControl.get +$S10SwiftForms24FormSegmentedControlCellC10titleLabelSo7UILabelCvgTo +_$S10SwiftForms17FormTextFieldCellC04textE0So06UITextE0CvgTo +_$S10SwiftForms17FormTextFieldCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTo +_$S10SwiftForms17FormTextFieldCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms17FormTextFieldCellCfE +_$S10SwiftForms17FormTextFieldCellCfETo +_$S10SwiftForms17FormTextFieldCellC5style15reuseIdentifierACSo011UITableViewF5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms17FormTextFieldCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$SSo11UITextFieldCML +_$S10SwiftForms17FormTextFieldCellC17customConstraints33_149870142910A653EE2CFFFC6D820B4ALLSayyXlGvpWvd +_$S10SwiftForms17FormTextFieldCellCML +_$S10SwiftForms17FormTextFieldCellCMf +_symbolic ____ 10SwiftForms17FormTextFieldCellC +_symbolic So11UITextFieldC +_$S10SwiftForms17FormTextFieldCellCMF +_$SSo11UITextFieldCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift +FormTextFieldCell.swift +$S10SwiftForms17FormTextFieldCellCMa +editingChanged +$SSo11UITextFieldCMa +$S10SwiftForms17FormTextFieldCellC04textE0So06UITextE0CvgTo +_$S10SwiftForms14FormPickerCellC10pickerView_11titleForRow12forComponentSSSgSo08UIPickerG0C_S2itFTo +_$S10SwiftForms14FormPickerCellC10pickerView_12didSelectRow11inComponentySo08UIPickerG0C_S2itFTo +_$S10SwiftForms14FormPickerCellC18numberOfComponents2inSiSo12UIPickerViewC_tFTo +_$S10SwiftForms14FormPickerCellC10pickerView_23numberOfRowsInComponentSiSo08UIPickerG0C_SitFTo +_$S10SwiftForms14FormPickerCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms14FormPickerCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms14FormPickerCellCfE +_$S10SwiftForms14FormPickerCellCfETo +_$S10SwiftForms14FormPickerCellC10pickerView_11titleForRow12forComponentSSSgSo08UIPickerG0C_S2itFTf4dndn_n +_$S10SwiftForms14FormPickerCellC10pickerView_12didSelectRow11inComponentySo08UIPickerG0C_S2itFTf4dndn_n +_$S10SwiftForms14FormPickerCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms14FormPickerCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms14FormPickerCellC6picker33_509F42A1F3552FA9D46F9A9EE75C8D9BLLSo12UIPickerViewCvpWvd +_$S10SwiftForms14FormPickerCellC15hiddenTextField33_509F42A1F3552FA9D46F9A9EE75C8D9BLLSo06UITextH0CvpWvd +l_OBJC_LABEL_PROTOCOL_$_UIPickerViewDelegate +l_OBJC_PROTOCOL_REFERENCE_$_UIPickerViewDelegate +l_OBJC_LABEL_PROTOCOL_$_UIPickerViewDataSource +l_OBJC_PROTOCOL_REFERENCE_$_UIPickerViewDataSource +_$S10SwiftForms14FormPickerCellCML +_$S10SwiftForms14FormPickerCellCMf +_symbolic ____ 10SwiftForms14FormPickerCellC +_symbolic So12UIPickerViewC +_$S10SwiftForms14FormPickerCellCMF +_$SSo12UIPickerViewCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift +FormPickerCell.swift +$S10SwiftForms14FormPickerCellCMa +pickerView +numberOfComponents +enumerated +_$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvgTo +_$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvsTo +_$S10SwiftForms29FormOptionsSelectorControllerCACycfcTo +_$S10SwiftForms29FormOptionsSelectorControllerC5coderACSo7NSCoderC_tcfcTo +_$S10SwiftForms29FormOptionsSelectorControllerC11viewDidLoadyyFTo +_$S10SwiftForms29FormOptionsSelectorControllerC16numberOfSections2inSiSo11UITableViewC_tFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_21numberOfRowsInSectionSiSo07UITableH0C_SitFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_24heightForHeaderInSection12CoreGraphics7CGFloatVSo07UITableH0C_SitFTo +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_12cellForRowAtSo07UITableH4CellCSo0mH0C_10Foundation9IndexPathVtFTo +_$SSa6remove2atxSi_tFyXl_Tg5 +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_14didSelectRowAtySo07UITableH0C_10Foundation9IndexPathVtFTo +_$S10SwiftForms29FormOptionsSelectorControllerC5styleACSo16UITableViewStyleV_tcfcTo +_$S10SwiftForms29FormOptionsSelectorControllerCfETo +_$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFyXl_Tg5 +_$SSa16_copyToNewBuffer8oldCountySi_tFyXl_Tg5 +_$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VyyXlG_Tg5 +_$S10SwiftForms29FormOptionsSelectorControllerC9tableView_21numberOfRowsInSectionSiSo07UITableH0C_SitFTf4ddn_n +_$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5Tf4xnn_n +_$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5Tf4nnndn_n +_$Ss23_ContiguousArrayStorageCyyXlGML +_$S10SwiftForms29FormOptionsSelectorControllerCML +_$S10SwiftForms29FormOptionsSelectorControllerCMf +_symbolic ____ 10SwiftForms29FormOptionsSelectorControllerC +_symbolic 10SwiftForms12FormBaseCellCSg +_$S10SwiftForms29FormOptionsSelectorControllerCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5Tf4nnndn_n +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP13_copyContents8subRange12initializingSpy7ElementQzGSnySiG_AKtFTWyXl_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8endIndexSivgTWyXl_Tg5 +$Ss12_ArrayBufferV8endIndexSivgyXl_Tg5 +$SSp12deinitialize5countSvSi_tFyXl_Tg5 +$SSp8distance2toSiSpyxG_tFyXl_Tg5 +$SSp14moveInitialize4from5countySpyxG_SitFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP19firstElementAddressSpy0E0QzGvgTWyXl_Tg5 +$Ss12_ArrayBufferV19firstElementAddressSpyxGvgyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0Vy7ElementQzGSgSi_tFTWyXl_Tg5 +$Ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tFyXl_Tg5 +$Ss12_ArrayBufferV20isUniquelyReferencedSbyFyXl_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP5countSivgTWyXl_Tg5 +$Ss12_ArrayBufferV5countSivgyXl_Tg5 +$Ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtFyXl_Tg5Tf4xnn_n +$SSp10initialize4from5countySPyxG_SitFyXl_Tg5 +$SSp8advanced2bySpyxGSi_tFyXl_Tg5 +FormOptionsViewController.swift +formCell.get +$Ss20_ArrayBufferProtocolPsE025_forceCreateUniqueMutableB0011countForNewB003minJ8Capacitys011_ContiguousaB0Vy7ElementQzGSi_SitFs01_aB0VyyXlG_Tg5 +$Ss12_ArrayBufferVyxGs01_aB8ProtocolssADP8capacitySivgTWyXl_Tg5 +$Ss12_ArrayBufferV8capacitySivgyXl_Tg5 +$Ss23_ContiguousArrayStorageCyyXlGMa +$SSa16_copyToNewBuffer8oldCountySi_tFyXl_Tg5 +$Ss20_ArrayBufferProtocolPsE22_arrayOutOfPlaceUpdateyys011_ContiguousaB0Vy7ElementQzGz_S2iqd__ts16_PointerFunctionRd__AFQyd__AGRSlFs01_aB0VyyXlG_s07_IgnoreK0VyyXlGTg5 +$SSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tFyXl_Tg5 +$S10SwiftForms29FormOptionsSelectorControllerCMa +$Ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFyt_Tgq5 +$SSRys5UInt8VGIgy_ACytIegyr_TR +$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_ +$Ss25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utFySRys5UInt8VGXEfU0_yAMXEfU_ +$Ss12_ArrayBufferV5countSivsyXl_Tg5 +$SSa034_makeUniqueAndReserveCapacityIfNotB0yyFyXl_Tg5 +$SSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xtFyXl_Tg5 +index +$SSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKFSayyXlG_Tg5 +$SSa13_adoptStorage_5countSayxG_SpyxGts016_ContiguousArrayB0CyxGn_SitFZyXl_Tg5 +$SyXlSbs5Error_pIggdzo_yXlSbsAA_pIegndzo_TR +$S10SwiftForms29FormOptionsSelectorControllerC9tableView_14didSelectRowAtySo07UITableH0C_10Foundation9IndexPathVtFSbyXlXEfU_ +$S10SwiftForms29FormOptionsSelectorControllerC9tableView_12cellForRowAtSo07UITableH4CellCSo0mH0C_10Foundation9IndexPathVtFSbyXlXEfU_ +formCell.materialize +formCell.set +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvsTo +$S10SwiftForms29FormOptionsSelectorControllerC8formCellAA0c4BaseH0CSgvgTo +_$S10SwiftForms12FormDateCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTo +_$S10SwiftForms12FormDateCellC5coderACSgSo7NSCoderC_tcfcTo +_$S10SwiftForms12FormDateCellCfE +_$S10SwiftForms12FormDateCellCfETo +_$S10SwiftForms12FormDateCellC5style15reuseIdentifierACSo011UITableViewE5StyleV_SSSgtcfcTf4ngn_n +_$S10SwiftForms12FormDateCellC5coderACSgSo7NSCoderC_tcfcTf4gn_n +_$S10SwiftForms12FormDateCellC15hiddenTextField33_C023FAD6768D46095D3739AAF2D78229LLSo06UITextH0CvpWvd +_$S10SwiftForms12FormDateCellC10datePicker33_C023FAD6768D46095D3739AAF2D78229LLSo06UIDateG0CvpWvd +_$S10SwiftForms12FormDateCellC07defaultD9Formatter33_C023FAD6768D46095D3739AAF2D78229LLSo06NSDateG0CvpWvd +_$S10SwiftForms12FormDateCellCML +_$S10SwiftForms12FormDateCellCMf +_symbolic ____ 10SwiftForms12FormDateCellC +_symbolic So12UIDatePickerC +_symbolic So15NSDateFormatterC +_$S10SwiftForms12FormDateCellCMF +_$SSo12UIDatePickerCMF +_symbolic So11NSFormatterC +_$SSo15NSDateFormatterCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift +FormDateCell.swift +$S10SwiftForms12FormDateCellCMa +getDateFormatter +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAASQ2eeoiySbx_xtFZTW +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAASH9hashValueSivgTW +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAASH4hash4intoys6HasherVz_tFTW +_$S10SwiftForms17FormRowDescriptorC5valueyXlSgvmytfU_ +_$SSayyXlGWOr +_$SSayyXlGWOs +_$S10SwiftForms17FormRowDescriptorC3tag4type5titleACSS_AC0D4TypeOSStcfcTf4gXngXn_n +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWI +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwet +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwst +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwxs +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwxg +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwug +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwup +_$S10SwiftForms17FormRowDescriptorC0D4TypeOwui +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwca +_$SSSWOh +___swift_memcpy48_4 +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwta +___swift_copy_outline_existential_box_pointer4 +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwca +___swift_memcpy17_4 +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwca +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwst +___swift_memcpy25_8 +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwca +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxx +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwcp +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwca +___swift_memcpy116_8 +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwta +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwet +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwst +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorCIegg_SgWOy +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwCP +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwCP +___swift_copy_outline_existential_box_pointer8 +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxs +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWp +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWG +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWr +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWp +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWG +_$S10SwiftForms17FormRowDescriptorC0D4TypeOAESQAAWL +_$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWr +_$S10SwiftForms17FormRowDescriptorCML +_$S10SwiftForms17FormRowDescriptorCMf +_$S10SwiftForms17FormRowDescriptorC0D4TypeOWV +_$S10SwiftForms17FormRowDescriptorC0D4TypeOMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC0D4TypeO +_$S10SwiftForms17FormRowDescriptorC0D4TypeOMF +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC17CellConfigurationV +_symbolic yXlXpSg +_symbolic SDySSyXlG +_symbolic Sb +_symbolic y____cSg 10SwiftForms17FormRowDescriptorC +_symbolic SaySSG10SwiftForms12FormBaseCellCcSg +_$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC22SelectionConfigurationV +_symbolic SSyXlcSg +_$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC19ButtonConfigurationV +_$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC20StepperConfigurationV +_symbolic Sd +_$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC17DateConfigurationV +_symbolic So15NSDateFormatterCSg +_$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMF +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVWV +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMf +_symbolic ____ 10SwiftForms17FormRowDescriptorC0D13ConfigurationV +_$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMF +_symbolic ____ 10SwiftForms17FormRowDescriptorC +_symbolic yXlSg +_$S10SwiftForms17FormRowDescriptorCMF +/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVMa +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxg +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxs +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwst +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwet +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwta +__swift_memcpy116_8 +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwca +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC0D13ConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVMa +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwst +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwet +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwta +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwca +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC17DateConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVMa +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwst +$S10SwiftForms17FormRowDescriptorC20StepperConfigurationVwet +__swift_memcpy25_8 +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVMa +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwst +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwet +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwta +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwca +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC19ButtonConfigurationVwCP +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVMa +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwst +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwet +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwta +__swift_memcpy17_4 +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwca +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC22SelectionConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVMa +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxg +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxs +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwst +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwet +__swift_copy_outline_existential_box_pointer4 +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwta +__swift_memcpy48_4 +$SSSWOh +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwca +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwcp +$S10SwiftForms17FormRowDescriptorC17CellConfigurationVwxx +$S10SwiftForms17FormRowDescriptorC0D4TypeOMa +$S10SwiftForms17FormRowDescriptorC0D4TypeOwui +$S10SwiftForms17FormRowDescriptorC0D4TypeOwup +$S10SwiftForms17FormRowDescriptorC0D4TypeOwug +$S10SwiftForms17FormRowDescriptorC0D4TypeOwxg +$S10SwiftForms17FormRowDescriptorC0D4TypeOwxs +$S10SwiftForms17FormRowDescriptorC0D4TypeOwst +$S10SwiftForms17FormRowDescriptorC0D4TypeOwet +$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWI +$S10SwiftForms17FormRowDescriptorC0D4TypeOAESQAAWl +$S10SwiftForms17FormRowDescriptorC0D4TypeOSQAAWa +$S10SwiftForms17FormRowDescriptorC0D4TypeOSHAAWa +FormRowDescriptor.swift +$S10SwiftForms17FormRowDescriptorCMa +$SSayyXlGWOs +$SSayyXlGWOr +value.didset +value.willset +configuration.materialize +configuration.set +configuration.get +value.materialize +value.get +type.get +tag.get +userInfo.materialize +userInfo.set +userInfo.get +date.materialize +date.set +date.get +stepper.materialize +stepper.set +stepper.get +button.materialize +button.set +button.get +selection.materialize +selection.set +selection.get +cell.materialize +cell.set +cell.get +dateFormatter.materialize +dateFormatter.set +dateFormatter.get +continuous.materialize +continuous.set +continuous.get +steps.materialize +steps.set +steps.get +minimumValue.materialize +minimumValue.set +minimumValue.get +maximumValue.materialize +maximumValue.set +maximumValue.get +didSelectClosure.materialize +didSelectClosure.set +didSelectClosure.get +allowsMultipleSelection.materialize +allowsMultipleSelection.set +allowsMultipleSelection.get +optionTitleClosure.materialize +optionTitleClosure.set +optionTitleClosure.get +options.materialize +options.set +options.get +controllerClass.materialize +controllerClass.set +controllerClass.get +visualConstraintsClosure.materialize +visualConstraintsClosure.set +visualConstraintsClosure.get +didUpdateClosure.materialize +didUpdateClosure.set +didUpdateClosure.get +willUpdateClosure.materialize +willUpdateClosure.set +willUpdateClosure.get +required.materialize +required.set +required.get +showsInputToolbar.materialize +showsInputToolbar.set +showsInputToolbar.get +placeholder.materialize +placeholder.set +placeholder.get +appearance.materialize +appearance.set +appearance.get +cellClass.materialize +cellClass.set +cellClass.get +Apple LLVM version 10.0.0 (clang-1000.11.45.5) +/Users/alexanderdavis/Library/Caches/org.carthage.CarthageKit/DerivedData/10.1_10B61/SwiftForms/1.8.2/Build/Intermediates.noindex/ArchiveIntermediates/SwiftForms/IntermediateBuildFilesPath/SwiftFormsApplication.build/Release-iphoneos/SwiftForms.build/DerivedSources/SwiftForms_vers.c +__ZL15__ARCLite__loadv +__ZL30add_image_hook_autoreleasepoolPK11mach_headerl +__ZL34__arclite_objc_autoreleasePoolPushv +__ZL33__arclite_objc_autoreleasePoolPopPv +__ZL19patch_lazy_pointersPK11mach_headerP7patch_tm +__ZL42__arclite_NSArray_objectAtIndexedSubscriptP7NSArrayP13objc_selectorj +__ZL53__arclite_NSMutableArray_setObject_atIndexedSubscriptP14NSMutableArrayP13objc_selectorP11objc_objectj +__ZL46__arclite_NSDictionary_objectForKeyedSubscriptP12NSDictionaryP13objc_selectorP11objc_object +__ZL47__arclite_NSOrderedSet_objectAtIndexedSubscriptP12NSOrderedSetP13objc_selectorj +__ZL58__arclite_NSMutableOrderedSet_setObject_atIndexedSubscriptP19NSMutableOrderedSetP13objc_selectorP11objc_objectj +__ZL58__arclite_NSMutableDictionary__setObject_forKeyedSubscriptP19NSMutableDictionaryP13objc_selectorP11objc_objectS4_ +__ZL18add_image_hook_ARCPK11mach_headerl +__ZL36__arclite_object_setInstanceVariableP11objc_objectPKcPv +__ZL24__arclite_object_setIvarP11objc_objectP9objc_ivarS0_ +__ZL21__arclite_object_copyP11objc_objectm +__ZL21__arclite_objc_retainP11objc_object +__ZL26__arclite_objc_retainBlockP11objc_object +__ZL22__arclite_objc_releaseP11objc_object +__ZL26__arclite_objc_autoreleaseP11objc_object +__ZL32__arclite_objc_retainAutoreleaseP11objc_object +__ZL37__arclite_objc_autoreleaseReturnValueP11objc_object +__ZL43__arclite_objc_retainAutoreleaseReturnValueP11objc_object +__ZL44__arclite_objc_retainAutoreleasedReturnValueP11objc_object +__ZL26__arclite_objc_storeStrongPP11objc_objectS0_ +__ZL22add_image_hook_swiftV1PK11mach_headerl +__ZL42__arclite_NSUndoManagerProxy_isKindOfClassP11objc_objectP13objc_selectorP10objc_class +__ZL30__arclite_NSManagedObject_initP11objc_objectP13objc_selector +__ZL41__arclite_NSManagedObject_allocWithEntityP11objc_objectP13objc_selectorS0_ +__ZL36__arclite_NSManagedObject_allocBatchP11objc_objectP13objc_selectorPS0_S0_j +__ZL37__arclite_NSKKMS_fastIndexForKnownKeyP11objc_objectP13objc_selectorS0_ +__ZL28__arclite_NSKKMS_indexForKeyP11objc_objectP13objc_selectorS0_ +__ZL29__arclite_NSKKsD_objectForKeyP11objc_objectP13objc_selectorS0_ +__ZL35__arclite_NSKKsD_removeObjectForKeyP11objc_objectP13objc_selectorS0_ +__ZL33__arclite_NSKKsD_setObject_forKeyP11objc_objectP13objc_selectorS0_S0_ +__ZL41__arclite_NSKKsD_addEntriesFromDictionaryP11objc_objectP13objc_selectorP12NSDictionary +__ZL28__arclite_objc_readClassPairP10objc_classPK15objc_image_info +__ZL32__arclite_objc_allocateClassPairP10objc_classPKcm +__ZL32__arclite_object_getIndexedIvarsP11objc_object +__ZL23__arclite_objc_getClassPKc +__ZL27__arclite_objc_getMetaClassPKc +__ZL31__arclite_objc_getRequiredClassPKc +__ZL26__arclite_objc_lookUpClassPKc +__ZL26__arclite_objc_getProtocolPKc +__ZL23__arclite_class_getNameP10objc_class +__ZL26__arclite_protocol_getNameP8Protocol +__ZL37__arclite_objc_copyClassNamesForImagePKcPj +__ZL17transcribeMethodsP10objc_classP15glue_class_ro_t +__ZL19transcribeProtocolsP10objc_classP15glue_class_ro_t +__ZL20transcribePropertiesP10objc_classP15glue_class_ro_t +__ZL14initialize_impP11objc_objectP13objc_selector +__ZL18allocateMaybeSwiftP18glue_swift_class_tm +__ZL22copySwiftV1MangledNamePKcb +__ZL13demangledNamePKcb +__ZL16scanMangledFieldRPKcS0_S1_Ri +__ZL30arclite_uninitialized_functionv +__ZL12cxxConstructP11objc_object +__ZL20fixStringForCoreDataP11objc_object +_OBJC_METACLASS_$___ARCLite__ +__ZL24OBJC_CLASS_$___ARCLite__ +__ZL31OBJC_METACLASS_RO_$___ARCLite__ +__non_lazy_classes +__ZL27OBJC_CLASS_RO_$___ARCLite__ +__ZL11_class_name +__ZL32OBJC_$_CLASS_METHODS___ARCLite__ +__ZL17_load_method_name +__ZL17_load_method_type +__ZL23NSAutoreleasePool_class +__ZZL30add_image_hook_autoreleasepoolPK11mach_headerlE7patches +__ZGVZL30add_image_hook_autoreleasepoolPK11mach_headerlE7patches +l_OBJC_PROTOCOL_$___ARCLiteIndexedSubscripting__ +l_OBJC_LABEL_PROTOCOL_$___ARCLiteIndexedSubscripting__ +l_OBJC_PROTOCOL_REFERENCE_$___ARCLiteIndexedSubscripting__ +l_OBJC_PROTOCOL_$___ARCLiteKeyedSubscripting__ +l_OBJC_LABEL_PROTOCOL_$___ARCLiteKeyedSubscripting__ +l_OBJC_PROTOCOL_REFERENCE_$___ARCLiteKeyedSubscripting__ +__ZZL18add_image_hook_ARCPK11mach_headerlE7patches +__ZGVZL18add_image_hook_ARCPK11mach_headerlE7patches +__ZL30NSUndoManagerProxy_targetClass +__ZL29original_NSManagedObject_init +__ZL40original_NSManagedObject_allocWithEntity +__ZL35original_NSManagedObject_allocBatch +__ZL25NSMutableDictionary_class +__ZL22NSConstantString_class +__ZL14NSString_class +__ZL36original_NSKKMS_fastIndexForKnownKey +__ZL27original_NSKKMS_indexForKey +__ZL28original_NSKKsD_objectForKey +__ZL34original_NSKKsD_removeObjectForKey +__ZL32original_NSKKsD_setObject_forKey +__ZL40original_NSKKsD_addEntriesFromDictionary +__ZZL22add_image_hook_swiftV1PK11mach_headerlE7patches +__ZGVZL22add_image_hook_swiftV1PK11mach_headerlE7patches +__ZL31original_objc_allocateClassPair +__ZL31original_object_getIndexedIvars +__ZL22original_objc_getClass +__ZL26original_objc_getMetaClass +__ZL30original_objc_getRequiredClass +__ZL25original_objc_lookUpClass +__ZL25original_objc_getProtocol +__ZL22original_class_getName +__ZL25original_protocol_getName +__ZL36original_objc_copyClassNamesForImage +__ZL12demangleLock +__ZL9Demangled +/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c++ -arch armv7 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=c++11 -Wno-trigraphs -fno-exceptions -fno-rtti -fno-sanitize=vptr -mpascal-strings -Os -Wno-missing-field-initializers -Wmissing-prototypes -Wno-implicit-atomic-properties -Wno-objc-interface-ivars -Wno-arc-repeated-use-of-weak -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-empty-body -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-constant-conversion -Wno-int-conversion -Wno-bool-conversion -Wno-enum-conversion -Wno-float-conversion -Wno-non-literal-null-conversion -Wno-objc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -Wno-c++11-extensions -D NDEBUG=1 -D OBJC_OLD_DISPATCH_PROTOTYPES=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -Winvalid-offsetof -miphoneos-version-min=4.3 -g -fno-threadsafe-statics -Wno-sign-conversion -Wno-infinite-recursion -Wno-move -Wno-comma -Wno-block-capture-autoreleasing -Wno-strict-prototypes -Wno-range-loop-analysis -Wno-semicolon-before-method-body -fembed-bitcode=all -iquote /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-generated-files.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-own-target-headers.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-all-target-headers.hmap -iquote /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/arclite_iphoneos-project-headers.hmap -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/Symbols/BuiltProducts/include -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/DerivedSources/armv7 -I /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/DerivedSources -F/Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/Symbols/BuiltProducts -iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk/System/Library/PrivateFrameworks -Wall -Wextra -Wno-gcc-compat -Wno-error=incomplete-umbrella -Wno-error=invalid-ios-deployment-target -Wno-error=incomplete-umbrella -Wno-error=invalid-ios-deployment-target -MMD -MT dependencies -MF /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/armv7/arclite.d --serialize-diagnostics /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/armv7/arclite.dia -c /Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70/source/arclite.mm -o /Library/Caches/com.apple.xbs/Binaries/arclite_iOS/install/TempContent/Objects/arclite.build/arclite_iOS.build/Objects-normal/armv7/arclite.o -mlinker-version=409.12 -march=armv7a +/Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70/source/arclite.mm +/Library/Caches/com.apple.xbs/Sources/arclite_iOS/arclite-70 +fixStringForCoreData +cxxConstruct +arclite_uninitialized_function +scanMangledField +/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.Internal.sdk/usr/include/_ctype.h +__isctype +demangledName +copySwiftV1DemangledName +copySwiftV1MangledName +allocateMaybeSwift +word_align +isSwift +initialize_imp +transcribeProperties +property_list_nth +transcribeProtocols +transcribeMethods +data +method_list_nth +__arclite_objc_copyClassNamesForImage +__arclite_protocol_getName +__arclite_class_getName +__arclite_objc_getProtocol +__arclite_objc_lookUpClass +__arclite_objc_getRequiredClass +__arclite_objc_getMetaClass +__arclite_objc_getClass +__arclite_object_getIndexedIvars +__arclite_objc_allocateClassPair +metaclass +__arclite_objc_readClassPair +transcribeIvars +ivar_list_nth +max +alignment +ro +fastFlags +__arclite_NSKKsD_addEntriesFromDictionary +__arclite_NSKKsD_setObject_forKey +__arclite_NSKKsD_removeObjectForKey +__arclite_NSKKsD_objectForKey +__arclite_NSKKMS_indexForKey +__arclite_NSKKMS_fastIndexForKnownKey +__arclite_NSManagedObject_allocBatch +__arclite_NSManagedObject_allocWithEntity +__arclite_NSManagedObject_init +__arclite_NSUndoManagerProxy_isKindOfClass +add_image_hook_swiftV1 +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +__arclite_objc_storeStrong +__arclite_objc_release +__arclite_objc_retain +__arclite_objc_retainAutoreleasedReturnValue +__arclite_objc_retainAutoreleaseReturnValue +__arclite_objc_autoreleaseReturnValue +__arclite_objc_retainAutorelease +__arclite_objc_autorelease +__arclite_objc_retainBlock +__arclite_object_copy +fixupCopiedReferences +_class_getInstanceStart +alignedInstanceStart +__arclite_class_usesAutomaticRetainRelease +classOrSuperClassesUseARR +__arclite_object_setIvar +isScannedOffset +_ivar_getClass +__arclite_object_setInstanceVariable +add_image_hook_ARC +patch_t +patch_t +patch_t +patch_t +patch_t +patch_t +__arclite_NSMutableDictionary__setObject_forKeyedSubscript +__arclite_NSMutableOrderedSet_setObject_atIndexedSubscript +__arclite_NSOrderedSet_objectAtIndexedSubscript +__arclite_NSDictionary_objectForKeyedSubscript +__arclite_NSMutableArray_setObject_atIndexedSubscript +__arclite_NSArray_objectAtIndexedSubscript +patch_lazy_pointers +__arclite_objc_autoreleasePoolPop +__arclite_objc_autoreleasePoolPush +add_image_hook_autoreleasepool +patch_t +patch_t +__ARCLite__load +install_swiftV1 +replaceMethod +install_ARC +install_dict_nil_value +addOrReplaceMethod +keyedGetter +install_subscripting +addMethod +indexedGetter +install_autoreleasepool diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Info.plist b/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Info.plist new file mode 100644 index 0000000..7720ade --- /dev/null +++ b/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Info.plist @@ -0,0 +1,20 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleIdentifier + com.apple.xcode.dsym.com.ortulabs.SwiftForms + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + dSYM + CFBundleSignature + ???? + CFBundleShortVersionString + 1.8.2 + CFBundleVersion + 1 + + diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Resources/DWARF/SwiftForms b/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Resources/DWARF/SwiftForms new file mode 100644 index 0000000..7c660f3 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework.dSYM/Contents/Resources/DWARF/SwiftForms differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms-Swift.h b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms-Swift.h new file mode 100644 index 0000000..d5c7eaa --- /dev/null +++ b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms-Swift.h @@ -0,0 +1,366 @@ +// Generated by Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgcc-compat" + +#if !defined(__has_include) +# define __has_include(x) 0 +#endif +#if !defined(__has_attribute) +# define __has_attribute(x) 0 +#endif +#if !defined(__has_feature) +# define __has_feature(x) 0 +#endif +#if !defined(__has_warning) +# define __has_warning(x) 0 +#endif + +#if __has_include() +# include +#endif + +#pragma clang diagnostic ignored "-Wauto-import" +#include +#include +#include +#include + +#if !defined(SWIFT_TYPEDEFS) +# define SWIFT_TYPEDEFS 1 +# if __has_include() +# include +# elif !defined(__cplusplus) +typedef uint_least16_t char16_t; +typedef uint_least32_t char32_t; +# endif +typedef float swift_float2 __attribute__((__ext_vector_type__(2))); +typedef float swift_float3 __attribute__((__ext_vector_type__(3))); +typedef float swift_float4 __attribute__((__ext_vector_type__(4))); +typedef double swift_double2 __attribute__((__ext_vector_type__(2))); +typedef double swift_double3 __attribute__((__ext_vector_type__(3))); +typedef double swift_double4 __attribute__((__ext_vector_type__(4))); +typedef int swift_int2 __attribute__((__ext_vector_type__(2))); +typedef int swift_int3 __attribute__((__ext_vector_type__(3))); +typedef int swift_int4 __attribute__((__ext_vector_type__(4))); +typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); +typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); +typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); +#endif + +#if !defined(SWIFT_PASTE) +# define SWIFT_PASTE_HELPER(x, y) x##y +# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) +#endif +#if !defined(SWIFT_METATYPE) +# define SWIFT_METATYPE(X) Class +#endif +#if !defined(SWIFT_CLASS_PROPERTY) +# if __has_feature(objc_class_property) +# define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ +# else +# define SWIFT_CLASS_PROPERTY(...) +# endif +#endif + +#if __has_attribute(objc_runtime_name) +# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) +#else +# define SWIFT_RUNTIME_NAME(X) +#endif +#if __has_attribute(swift_name) +# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) +#else +# define SWIFT_COMPILE_NAME(X) +#endif +#if __has_attribute(objc_method_family) +# define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) +#else +# define SWIFT_METHOD_FAMILY(X) +#endif +#if __has_attribute(noescape) +# define SWIFT_NOESCAPE __attribute__((noescape)) +#else +# define SWIFT_NOESCAPE +#endif +#if __has_attribute(warn_unused_result) +# define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +# define SWIFT_WARN_UNUSED_RESULT +#endif +#if __has_attribute(noreturn) +# define SWIFT_NORETURN __attribute__((noreturn)) +#else +# define SWIFT_NORETURN +#endif +#if !defined(SWIFT_CLASS_EXTRA) +# define SWIFT_CLASS_EXTRA +#endif +#if !defined(SWIFT_PROTOCOL_EXTRA) +# define SWIFT_PROTOCOL_EXTRA +#endif +#if !defined(SWIFT_ENUM_EXTRA) +# define SWIFT_ENUM_EXTRA +#endif +#if !defined(SWIFT_CLASS) +# if __has_attribute(objc_subclassing_restricted) +# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA +# define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# else +# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# endif +#endif + +#if !defined(SWIFT_PROTOCOL) +# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA +# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA +#endif + +#if !defined(SWIFT_EXTENSION) +# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) +#endif + +#if !defined(OBJC_DESIGNATED_INITIALIZER) +# if __has_attribute(objc_designated_initializer) +# define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) +# else +# define OBJC_DESIGNATED_INITIALIZER +# endif +#endif +#if !defined(SWIFT_ENUM_ATTR) +# if defined(__has_attribute) && __has_attribute(enum_extensibility) +# define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility))) +# else +# define SWIFT_ENUM_ATTR(_extensibility) +# endif +#endif +#if !defined(SWIFT_ENUM) +# define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type +# if __has_feature(generalized_swift_name) +# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type +# else +# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility) +# endif +#endif +#if !defined(SWIFT_UNAVAILABLE) +# define SWIFT_UNAVAILABLE __attribute__((unavailable)) +#endif +#if !defined(SWIFT_UNAVAILABLE_MSG) +# define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) +#endif +#if !defined(SWIFT_AVAILABILITY) +# define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) +#endif +#if !defined(SWIFT_DEPRECATED) +# define SWIFT_DEPRECATED __attribute__((deprecated)) +#endif +#if !defined(SWIFT_DEPRECATED_MSG) +# define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) +#endif +#if __has_feature(attribute_diagnose_if_objc) +# define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) +#else +# define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) +#endif +#if __has_feature(modules) +@import CoreGraphics; +@import Foundation; +@import ObjectiveC; +@import UIKit; +#endif + +#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" +#pragma clang diagnostic ignored "-Wduplicate-method-arg" +#if __has_warning("-Wpragma-clang-attribute") +# pragma clang diagnostic ignored "-Wpragma-clang-attribute" +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" +#pragma clang diagnostic ignored "-Wnullability" + +#if __has_attribute(external_source_symbol) +# pragma push_macro("any") +# undef any +# pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="SwiftForms",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol)) +# pragma pop_macro("any") +#endif + +@class NSCoder; + +SWIFT_CLASS("_TtC10SwiftForms12FormBaseCell") +@interface FormBaseCell : UITableViewCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +- (void)updateConstraints; +@end + +@class UILabel; + +SWIFT_CLASS("_TtC10SwiftForms13FormTitleCell") +@interface FormTitleCell : FormBaseCell +@property (nonatomic, readonly, strong) UILabel * _Nonnull titleLabel; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms14FormButtonCell") +@interface FormButtonCell : FormTitleCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms13FormCheckCell") +@interface FormCheckCell : FormTitleCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms13FormValueCell") +@interface FormValueCell : FormBaseCell +@property (nonatomic, readonly, strong) UILabel * _Nonnull titleLabel; +@property (nonatomic, readonly, strong) UILabel * _Nonnull valueLabel; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms12FormDateCell") +@interface FormDateCell : FormValueCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms13FormLabelCell") +@interface FormLabelCell : FormValueCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_PROTOCOL("_TtP10SwiftForms12FormSelector_") +@protocol FormSelector +@property (nonatomic, strong) FormBaseCell * _Nullable formCell; +@end + +@class NSBundle; +@class UITableView; + +SWIFT_CLASS("_TtC10SwiftForms29FormOptionsSelectorController") +@interface FormOptionsSelectorController : UITableViewController +@property (nonatomic, strong) FormBaseCell * _Nullable formCell; +- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil SWIFT_UNAVAILABLE; +- (void)viewDidLoad; +- (NSInteger)numberOfSectionsInTableView:(UITableView * _Nonnull)tableView SWIFT_WARN_UNUSED_RESULT; +- (NSInteger)tableView:(UITableView * _Nonnull)tableView numberOfRowsInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (CGFloat)tableView:(UITableView * _Nonnull)tableView heightForHeaderInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (UITableViewCell * _Nonnull)tableView:(UITableView * _Nonnull)tableView cellForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath SWIFT_WARN_UNUSED_RESULT; +- (void)tableView:(UITableView * _Nonnull)tableView didSelectRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath; +- (nonnull instancetype)initWithStyle:(UITableViewStyle)style SWIFT_UNAVAILABLE; +@end + +@class UIPickerView; + +SWIFT_CLASS("_TtC10SwiftForms14FormPickerCell") +@interface FormPickerCell : FormValueCell +- (NSString * _Nullable)pickerView:(UIPickerView * _Nonnull)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component SWIFT_WARN_UNUSED_RESULT; +- (void)pickerView:(UIPickerView * _Nonnull)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component; +- (NSInteger)numberOfComponentsInPickerView:(UIPickerView * _Nonnull)pickerView SWIFT_WARN_UNUSED_RESULT; +- (NSInteger)pickerView:(UIPickerView * _Nonnull)pickerView numberOfRowsInComponent:(NSInteger)component SWIFT_WARN_UNUSED_RESULT; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + +@class UISegmentedControl; + +SWIFT_CLASS_NAMED("FormSegmentedControlCell") +@interface FormSegmentedControlCell : FormBaseCell +@property (nonatomic, readonly, strong) UILabel * _Nonnull titleLabel; +@property (nonatomic, readonly, strong) UISegmentedControl * _Nonnull segmentedControl; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + + +SWIFT_CLASS("_TtC10SwiftForms16FormSelectorCell") +@interface FormSelectorCell : FormValueCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + +@class UISlider; + +SWIFT_CLASS("_TtC10SwiftForms14FormSliderCell") +@interface FormSliderCell : FormTitleCell +@property (nonatomic, readonly, strong) UISlider * _Nonnull sliderView; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms15FormStepperCell") +@interface FormStepperCell : FormTitleCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + +SWIFT_CLASS("_TtC10SwiftForms14FormSwitchCell") +@interface FormSwitchCell : FormTitleCell +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + +@class UITextField; + +SWIFT_CLASS("_TtC10SwiftForms17FormTextFieldCell") +@interface FormTextFieldCell : FormBaseCell +@property (nonatomic, readonly, strong) UITextField * _Nonnull textField; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + +@class UITextView; + +SWIFT_CLASS("_TtC10SwiftForms16FormTextViewCell") +@interface FormTextViewCell : FormBaseCell +@property (nonatomic, readonly, strong) UILabel * _Nonnull titleLabel; +@property (nonatomic, readonly, strong) UITextView * _Nonnull textField; +- (void)textViewDidChange:(UITextView * _Nonnull)textView; +- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Null_unspecified)reuseIdentifier OBJC_DESIGNATED_INITIALIZER; +- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +@end + + + +@class UIView; + +SWIFT_CLASS("_TtC10SwiftForms18FormViewController") +@interface FormViewController : UITableViewController +- (nonnull instancetype)init; +- (nonnull instancetype)initWithStyle:(UITableViewStyle)style OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; +- (void)viewDidLoad; +- (NSInteger)numberOfSectionsInTableView:(UITableView * _Nonnull)tableView SWIFT_WARN_UNUSED_RESULT; +- (NSInteger)tableView:(UITableView * _Nonnull)tableView numberOfRowsInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (UITableViewCell * _Nonnull)tableView:(UITableView * _Nonnull)tableView cellForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath SWIFT_WARN_UNUSED_RESULT; +- (NSString * _Nullable)tableView:(UITableView * _Nonnull)tableView titleForHeaderInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (NSString * _Nullable)tableView:(UITableView * _Nonnull)tableView titleForFooterInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (UIView * _Nullable)tableView:(UITableView * _Nonnull)tableView viewForHeaderInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (UIView * _Nullable)tableView:(UITableView * _Nonnull)tableView viewForFooterInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (CGFloat)tableView:(UITableView * _Nonnull)tableView heightForHeaderInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (CGFloat)tableView:(UITableView * _Nonnull)tableView heightForFooterInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; +- (CGFloat)tableView:(UITableView * _Nonnull)tableView heightForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath SWIFT_WARN_UNUSED_RESULT; +- (void)tableView:(UITableView * _Nonnull)tableView didSelectRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath; +@end + +#if __has_attribute(external_source_symbol) +# pragma clang attribute pop +#endif +#pragma clang diagnostic pop diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms.h b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms.h new file mode 100644 index 0000000..b14d579 --- /dev/null +++ b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Headers/SwiftForms.h @@ -0,0 +1,19 @@ +// +// SwiftForms.h +// SwiftForms +// +// Created by Miguel Angel Ortuno Ortuno on 14/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +#import + +//! Project version number for SwiftForms. +FOUNDATION_EXPORT double SwiftFormsVersionNumber; + +//! Project version string for SwiftForms. +FOUNDATION_EXPORT const unsigned char SwiftFormsVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Info.plist b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Info.plist new file mode 100644 index 0000000..0009386 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Info.plist differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftdoc b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftdoc new file mode 100644 index 0000000..be917ae Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftdoc differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftmodule b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftmodule new file mode 100644 index 0000000..cae9c6b Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm.swiftmodule differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftdoc b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftdoc new file mode 100644 index 0000000..fc3685a Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftdoc differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftmodule b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftmodule new file mode 100644 index 0000000..9727718 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/arm64.swiftmodule differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftdoc b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftdoc new file mode 100644 index 0000000..ece9778 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftdoc differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftmodule b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftmodule new file mode 100644 index 0000000..a77a4d5 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/i386.swiftmodule differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftdoc b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftdoc new file mode 100644 index 0000000..3066de9 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftdoc differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftmodule b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftmodule new file mode 100644 index 0000000..2a53b6a Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/SwiftForms.swiftmodule/x86_64.swiftmodule differ diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/module.modulemap b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/module.modulemap new file mode 100644 index 0000000..c6acb38 --- /dev/null +++ b/My Mind/Carthage/Build/iOS/SwiftForms.framework/Modules/module.modulemap @@ -0,0 +1,11 @@ +framework module SwiftForms { + umbrella header "SwiftForms.h" + + export * + module * { export * } +} + +module SwiftForms.Swift { + header "SwiftForms-Swift.h" + requires objc +} diff --git a/My Mind/Carthage/Build/iOS/SwiftForms.framework/SwiftForms b/My Mind/Carthage/Build/iOS/SwiftForms.framework/SwiftForms new file mode 100755 index 0000000..28b5600 Binary files /dev/null and b/My Mind/Carthage/Build/iOS/SwiftForms.framework/SwiftForms differ diff --git a/My Mind/Carthage/Checkouts/SwiftForms/.gitignore b/My Mind/Carthage/Checkouts/SwiftForms/.gitignore new file mode 100644 index 0000000..7469951 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/.gitignore @@ -0,0 +1,60 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Pods # +######## +Pods/ + +# Xcode # +######### +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +*.xcworkspace +!default.xcworkspace +xcuserdata +profile +*.moved-aside +DerivedData +.idea/ diff --git a/My Mind/Carthage/Checkouts/SwiftForms/.swift-version b/My Mind/Carthage/Checkouts/SwiftForms/.swift-version new file mode 100644 index 0000000..bf77d54 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/.swift-version @@ -0,0 +1 @@ +4.2 diff --git a/My Mind/Carthage/Checkouts/SwiftForms/LICENSE b/My Mind/Carthage/Checkouts/SwiftForms/LICENSE new file mode 100644 index 0000000..03d0bb6 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Xmartlabs ( http://xmartlabs.com ) +Copyright (c) 2014 Miguel Ángel Ortuño ( ortuman@gmail.com ) + +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/My Mind/Carthage/Checkouts/SwiftForms/README.MD b/My Mind/Carthage/Checkouts/SwiftForms/README.MD new file mode 100644 index 0000000..dd0afa3 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/README.MD @@ -0,0 +1,155 @@ + +[![Version](https://img.shields.io/badge/pod-1.8.2-orange.svg)](http://cocoadocs.org/docsets/SwiftForms) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +[![License](https://img.shields.io/badge/license-MIT-gray.svg)](http://cocoadocs.org/docsets/SwiftForms) +[![Platform](https://img.shields.io/badge/platform-iOS-lightgrey.svg)](http://cocoadocs.org/docsets/SwiftForms) + +SwiftForms +========== + +Purpose +------- +SwiftForms is a powerful and extremely flexible library written in Swift that allows to create forms by just defining them in a couple of lines. It also provides the ability to customize cells appearance, use custom cells and define your own selector controllers. + +Here is an screenshot from an example application using SwiftForms + +![Screenshot of Example application](SwiftFormsApplication/Example.gif) + +How to create a form +-------------------- + +Creating a form using SwiftForms is pretty straightforward. All you need is to derive your controller from `FormViewController` and define a `FormDescriptor` instance along with its sections and rows. Here is an example of how to create a simple form to input an email and a user password. + +```swift + +// Create form instace +var form = FormDescriptor() +form.title = "Example form" + +// Define first section +var section1 = FormSectionDescriptor() + +var row = FormRowDescriptor(tag: "name", rowType: .Email, title: "Email") +section1.rows.append(row) + +row = FormRowDescriptor(tag: "pass", rowType: .Password, title: "Password") +section1.rows.append(row) + +// Define second section +var section2 = FormSectionDescriptor() + +row = FormRowDescriptor(tag: "button", rowType: .Button, title: "Submit") +section2.rows.append(row) + +form.sections = [section1, section2] + +self.form = form +``` +To see a more complex form definition you can take a look to the example application. + +Cell appearance +---------------------- + +Every row descriptor has a `configuration` dictionary that allows to customize cell's appearance and behavior. In order to change concrete visual aspects of a row simply set `row.configuration.cell.appearance` value to a dictionary containing custom key-value coding properties. + +Here's an example: + +```swift +row.configuration.cell.appearance = ["titleLabel.font" : UIFont.boldSystemFontOfSize(30.0), "segmentedControl.tintColor" : UIColor.redColor()] +``` + +Custom cells +----------------- + +In addition, it is possible to create 100% custom cells by deriving from `FormBaseCell` class. In that case, don't forget to override `configure` and `update` methods. First method will be called only once and after cell has been created, and the second one every time cell content should be refreshed. + +Here are the methods that help you to define custom cell behavior. +```swift +func configure() { + /// override +} + +func update() { + /// override +} + +class func formRowCellHeight() -> CGFloat { + return 44.0 +} + +class func formViewController(formViewController: FormViewController, didSelectRow: FormBaseCell) { +} +``` +Once you have defined your custom cell, and in order to use it for a concrete row, you'll have to set `FormRowDescriptor` cellClass property. + +Custom selector controllers +------------------------------------- + +In order to customize selector controller your class should conform to `FormSelector` protocol. That way you'll have access to the cell instance that pushed the controller, being able to alter its properties or setting it's row value accordingly to user interaction. + +After defining your class, don't forget to set `row.configuration.selection.controllerClass` value in the configuration dictionary to use your custom selector controller. + +Requirements +--------------------- + +* iOS 8.0 and above + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. + +CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +To integrate SwiftForms into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'SwiftForms' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +Simply add the following line to your `Cartfile`: + +``` +github "ortuman/SwiftForms" +``` + +Then run: + +```bash +$ carthage update +``` + +For more information on [Carthage](https://github.com/Carthage/Carthage) see the [README](https://github.com/Carthage/Carthage/blob/master/README.md) + +Copyright +--------- + +SwiftForms is originally based on XLForm github project. (https://github.com/xmartlabs/XLForm) + +Check LICENSE file for more details. + +Contact +------- + +If you are using SwiftForms in your project and have any suggestion or question: + +Miguel Angel Ortuño, + +[@ortuman](http://twitter.com/ortuman) + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms.podspec b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms.podspec new file mode 100644 index 0000000..33e6a1c --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms.podspec @@ -0,0 +1,11 @@ +Pod::Spec.new do |s| + s.name = "SwiftForms" + s.version = "1.8.2" + s.summary = "A small and lightweight library written in Swift that allows you to easily create forms" + s.homepage = "https://github.com/ortuman/SwiftForms" + s.license = { :type => "MIT", :file => "LICENSE" } + s.authors = "Miguel Ángel Ortuño" + s.ios.deployment_target = "8.0" + s.source = { :git => "https://github.com/ortuman/SwiftForms.git", :tag => '1.8.2' } + s.source_files = 'SwiftForms/*.swift','SwiftForms/descriptors/*.swift', 'SwiftForms/cells/base/*.swift', 'SwiftForms/cells/*.swift', 'SwiftForms/controllers/*.swift' +end diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift new file mode 100644 index 0000000..37356e8 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/FormErrorType.swift @@ -0,0 +1,12 @@ +// +// FormErrorType.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 2/1/16. +// Copyright © 2016 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +public enum FormErrorType: Error { + case sectionOutOfIndex + case rowOutOfIndex +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/Info.plist b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/Info.plist new file mode 100644 index 0000000..61ecdb0 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.8.2 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/SwiftForms.h b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/SwiftForms.h new file mode 100644 index 0000000..b14d579 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/SwiftForms.h @@ -0,0 +1,19 @@ +// +// SwiftForms.h +// SwiftForms +// +// Created by Miguel Angel Ortuno Ortuno on 14/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +#import + +//! Project version number for SwiftForms. +FOUNDATION_EXPORT double SwiftFormsVersionNumber; + +//! Project version string for SwiftForms. +FOUNDATION_EXPORT const unsigned char SwiftFormsVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift new file mode 100644 index 0000000..0d3dcdb --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormButtonCell.swift @@ -0,0 +1,24 @@ +// +// FormButtonCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormButtonCell: FormTitleCell { + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + titleLabel.textAlignment = .center + } + + open override func update() { + super.update() + titleLabel.text = rowDescriptor?.title + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift new file mode 100644 index 0000000..818c355 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormCheckCell.swift @@ -0,0 +1,55 @@ +// +// FormCheckCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormCheckCell: FormTitleCell { + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + selectionStyle = .default + accessoryType = .none + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + var rowValue: Bool + if let value = rowDescriptor?.value as? Bool { + rowValue = value + } else { + rowValue = false + rowDescriptor?.value = rowValue as AnyObject + } + + accessoryType = (rowValue) ? .checkmark : .none + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormCheckCell else { return } + row.check() + } + + // MARK: Private interface + + fileprivate func check() { + var newValue: Bool + if let value = rowDescriptor?.value as? Bool { + newValue = !value + } + else { + newValue = true + } + rowDescriptor?.value = newValue as AnyObject + update() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift new file mode 100644 index 0000000..001c805 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormDateCell.swift @@ -0,0 +1,98 @@ +// +// FormDateCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormDateCell: FormValueCell { + + // MARK: Properties + + private let datePicker = UIDatePicker() + private let hiddenTextField = UITextField(frame: CGRect.zero) + + private let defaultDateFormatter = DateFormatter() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + contentView.addSubview(hiddenTextField) + hiddenTextField.inputView = datePicker + hiddenTextField.isAccessibilityElement = false + datePicker.datePickerMode = .date + datePicker.addTarget(self, action: #selector(FormDateCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && hiddenTextField.inputAccessoryView == nil { + hiddenTextField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + + if let rowType = rowDescriptor?.type { + switch rowType { + case .date: + datePicker.datePickerMode = .date + defaultDateFormatter.dateStyle = .long + defaultDateFormatter.timeStyle = .none + case .time: + datePicker.datePickerMode = .time + defaultDateFormatter.dateStyle = .none + defaultDateFormatter.timeStyle = .short + default: + datePicker.datePickerMode = .dateAndTime + defaultDateFormatter.dateStyle = .long + defaultDateFormatter.timeStyle = .short + } + } + + if let date = rowDescriptor?.value as? Date { + datePicker.date = date + valueLabel.text = getDateFormatter().string(from: date) + } + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormDateCell else { return } + + if row.rowDescriptor?.value == nil { + let date = Date() + row.rowDescriptor?.value = date as AnyObject + row.valueLabel.text = row.getDateFormatter().string(from: date) + row.update() + } + + row.hiddenTextField.becomeFirstResponder() + } + + open override func firstResponderElement() -> UIResponder? { + return hiddenTextField + } + + open override class func formRowCanBecomeFirstResponder() -> Bool { + return true + } + + // MARK: Actions + + @objc internal func valueChanged(_ sender: UIDatePicker) { + rowDescriptor?.value = sender.date as AnyObject + valueLabel.text = getDateFormatter().string(from: sender.date) + update() + } + + // MARK: Private interface + + fileprivate func getDateFormatter() -> DateFormatter { + guard let dateFormatter = rowDescriptor?.configuration.date.dateFormatter else { return defaultDateFormatter } + return dateFormatter + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift new file mode 100644 index 0000000..c3d9d30 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormLabelCell.swift @@ -0,0 +1,48 @@ +// +// FormTextFieldCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormLabelCell: FormValueCell { + + /// MARK: FormBaseCell + + override open func configure() { + super.configure() + + accessoryType = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + valueLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + valueLabel.textColor = UIColor.lightGray + valueLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(valueLabel) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + // apply constant constraints + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + override open func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + valueLabel.text = rowDescriptor?.configuration.cell.placeholder + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift new file mode 100644 index 0000000..cf2cf76 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormPickerCell.swift @@ -0,0 +1,106 @@ +// +// FormPickerCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource { + + // MARK: Properties + + private let picker = UIPickerView() + private let hiddenTextField = UITextField(frame: CGRect.zero) + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + accessoryType = .none + + picker.delegate = self + picker.dataSource = self + hiddenTextField.inputView = picker + hiddenTextField.isAccessibilityElement = false + + contentView.addSubview(hiddenTextField) + } + + open override func update() { + super.update() + picker.reloadAllComponents() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && hiddenTextField.inputAccessoryView == nil { + hiddenTextField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + valueLabel.text = "" + + if let selectedValue = rowDescriptor?.value { + valueLabel.text = rowDescriptor?.configuration.selection.optionTitleClosure?(selectedValue) + if let options = rowDescriptor?.configuration.selection.options , !options.isEmpty { + var selectedIndex: Int? + for (index, value) in options.enumerated() { + if value === selectedValue { + selectedIndex = index + break + } + } + if let index = selectedIndex { + picker.selectRow(index, inComponent: 0, animated: false) + } + } + } + } + + open override func firstResponderElement() -> UIResponder? { + return hiddenTextField + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormPickerCell else { return } + + if selectedRow.rowDescriptor?.value == nil { + guard let options = selectedRow.rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + let value = options[0] + selectedRow.rowDescriptor?.value = value + row.valueLabel.text = selectedRow.rowDescriptor?.configuration.selection.optionTitleClosure?(value) + row.hiddenTextField.becomeFirstResponder() + } else { + guard let value = selectedRow.rowDescriptor?.value else { return } + row.valueLabel.text = selectedRow.rowDescriptor?.configuration.selection.optionTitleClosure?(value) + row.hiddenTextField.becomeFirstResponder() + } + } + + // MARK: UIPickerViewDelegate + + open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return nil } + guard row < options.count else { return nil } + return rowDescriptor?.configuration.selection.optionTitleClosure?(options[row]) + } + + open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + guard row < options.count else { return } + let newValue = options[row] + rowDescriptor?.value = newValue + valueLabel.text = rowDescriptor?.configuration.selection.optionTitleClosure?(newValue) + } + + // MARK: UIPickerViewDataSource + + open func numberOfComponents(in pickerView: UIPickerView) -> Int { + return 1 + } + + open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + guard let options = rowDescriptor?.configuration.selection.options else { return 0 } + return options.count + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift new file mode 100644 index 0000000..99fe74b --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift @@ -0,0 +1,100 @@ +// +// FormSegmentedControlCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +@objc(FormSegmentedControlCell) +open class FormSegmentedControlCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let segmentedControl = UISegmentedControl() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject] = [] + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + segmentedControl.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 500), for: .horizontal) + segmentedControl.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(segmentedControl) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + segmentedControl.addTarget(self, action: #selector(FormSegmentedControlCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + updateSegmentedControl() + + guard let value = rowDescriptor?.value else { return } + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + + var idx = 0 + for optionValue in options { + if optionValue === value { + segmentedControl.selectedSegmentIndex = idx + break + } + idx += 1 + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl] + } + + open override func defaultVisualConstraints() -> [String] { + if let text = titleLabel.text , text.count > 0 { + return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"] + } else { + return ["H:|-16-[segmentedControl]-16-|"] + } + } + + // MARK: Actions + + @objc internal func valueChanged(_ sender: UISegmentedControl) { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + let value = options[sender.selectedSegmentIndex] + rowDescriptor?.value = value + } + + // MARK: Private + + fileprivate func updateSegmentedControl() { + segmentedControl.removeAllSegments() + + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + + var idx = 0 + for value in options { + let title = rowDescriptor?.configuration.selection.optionTitleClosure?(value) + segmentedControl.insertSegment(withTitle: title, at: idx, animated: false) + idx += 1 + } + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift new file mode 100644 index 0000000..5e7f956 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSelectorCell.swift @@ -0,0 +1,63 @@ +// +// FormSelectorCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormSelectorCell: FormValueCell { + + // MARK: FormBaseCell + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + var title: String? + if let multipleValues = rowDescriptor?.value as? [AnyObject] { + var multipleValuesTitle = "" + for (index, selectedValue) in multipleValues.enumerated() { + guard let selectedValueTitle = rowDescriptor?.configuration.selection.optionTitleClosure?(selectedValue) else { continue } + if index != 0 { + multipleValuesTitle += ", " + } + multipleValuesTitle += selectedValueTitle + } + title = multipleValuesTitle + } else if let singleValue = rowDescriptor?.value { + title = rowDescriptor?.configuration.selection.optionTitleClosure?(singleValue) + } + + if let title = title , title.count > 0 { + valueLabel.text = title + valueLabel.textColor = UIColor.black + } else { + valueLabel.text = rowDescriptor?.configuration.cell.placeholder + valueLabel.textColor = UIColor.lightGray + } + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormSelectorCell else { return } + + formViewController.view.endEditing(true) + + var selectorControllerClass: UIViewController.Type + + if let controllerClass = row.rowDescriptor?.configuration.selection.controllerClass as? UIViewController.Type { + selectorControllerClass = controllerClass + } else { // fallback to default cell class + selectorControllerClass = FormOptionsSelectorController.self + } + + let selectorController = selectorControllerClass.init() + guard let formRowDescriptorViewController = selectorController as? FormSelector else { return } + + formRowDescriptorViewController.formCell = row + formViewController.navigationController?.pushViewController(selectorController, animated: true) + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift new file mode 100644 index 0000000..5f7c0d5 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSliderCell.swift @@ -0,0 +1,75 @@ +// +// FormSliderCell.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 23/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +import UIKit + +open class FormSliderCell: FormTitleCell { + + // MARK: Cell views + + @objc public let sliderView = UISlider() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + sliderView.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(sliderView) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: sliderView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + sliderView.addTarget(self, action: #selector(FormSliderCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let maximumValue = rowDescriptor?.configuration.stepper.maximumValue { sliderView.maximumValue = Float(maximumValue) } + if let minimumValue = rowDescriptor?.configuration.stepper.minimumValue { sliderView.minimumValue = Float(minimumValue) } + if let continuous = rowDescriptor?.configuration.stepper.continuous { sliderView.isContinuous = continuous } + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Float { + sliderView.value = value + } else { + sliderView.value = sliderView.minimumValue + rowDescriptor?.value = sliderView.minimumValue as AnyObject + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "sliderView" : sliderView] + } + + open override func defaultVisualConstraints() -> [String] { + var constraints: [String] = [] + + constraints.append("V:|[titleLabel]|") + constraints.append("H:|-16-[titleLabel]-16-[sliderView]-16-|") + + return constraints + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISlider) { + rowDescriptor?.value = sliderView.value as AnyObject + update() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift new file mode 100644 index 0000000..5780e01 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormStepperCell.swift @@ -0,0 +1,82 @@ +// +// FormStepperCell.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 23/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +import UIKit + +open class FormStepperCell: FormTitleCell { + + // MARK: Cell views + + public let stepperView = UIStepper() + public let countLabel = UILabel() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + stepperView.translatesAutoresizingMaskIntoConstraints = false + countLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + countLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(countLabel) + contentView.addSubview(stepperView) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: stepperView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + stepperView.addTarget(self, action: #selector(FormStepperCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let maximumValue = rowDescriptor?.configuration.stepper.maximumValue { stepperView.maximumValue = maximumValue } + if let minimumValue = rowDescriptor?.configuration.stepper.minimumValue { stepperView.minimumValue = minimumValue } + if let steps = rowDescriptor?.configuration.stepper.steps { stepperView.stepValue = steps } + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Double { + stepperView.value = value + countLabel.text = String(value) + } else { + stepperView.value = stepperView.minimumValue + rowDescriptor?.value = stepperView.minimumValue as AnyObject + countLabel.text = String(stepperView.minimumValue) + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "countLabel" : countLabel, "stepperView" : stepperView] + } + + open override func defaultVisualConstraints() -> [String] { + var constraints: [String] = [] + + constraints.append("V:|[titleLabel]|") + constraints.append("V:|[countLabel]|") + + constraints.append("H:|-16-[titleLabel][countLabel]-[stepperView]-16-|") + return constraints + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISwitch) { + rowDescriptor?.value = stepperView.value as AnyObject + update() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift new file mode 100644 index 0000000..1a49db5 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormSwitchCell.swift @@ -0,0 +1,47 @@ +// +// FormSwitchCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormSwitchCell: FormTitleCell { + + // MARK: Cell views + + public let switchView = UISwitch() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + switchView.addTarget(self, action: #selector(FormSwitchCell.valueChanged(_:)), for: .valueChanged) + accessoryView = switchView + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Bool { + switchView.isOn = value + } else { + switchView.isOn = false + rowDescriptor?.value = false as AnyObject + } + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISwitch) { + rowDescriptor?.value = switchView.isOn as AnyObject + update() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift new file mode 100644 index 0000000..3916ce1 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift @@ -0,0 +1,148 @@ +// +// FormTextFieldCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTextFieldCell: FormBaseCell { + + // MARK: Cell views + + public let titleLabel = UILabel() + @objc public let textField = UITextField() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject] = [] + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + textField.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + textField.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(textField) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + textField.addTarget(self, action: #selector(FormTextFieldCell.editingChanged(_:)), for: .editingChanged) + } + + open override func update() { + super.update() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && textField.inputAccessoryView == nil { + textField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + textField.text = rowDescriptor?.value as? String + textField.placeholder = rowDescriptor?.configuration.cell.placeholder + + textField.isSecureTextEntry = false + textField.clearButtonMode = .whileEditing + + if let type = rowDescriptor?.type { + switch type { + case .text: + textField.autocorrectionType = .default + textField.autocapitalizationType = .sentences + textField.keyboardType = .default + case .number: + textField.keyboardType = .numberPad + case .numbersAndPunctuation: + textField.keyboardType = .numbersAndPunctuation + case .decimal: + textField.keyboardType = .decimalPad + case .name: + textField.autocorrectionType = .no + textField.autocapitalizationType = .words + textField.keyboardType = .default + case .phone: + textField.keyboardType = .phonePad + case .namePhone: + textField.autocorrectionType = .no + textField.autocapitalizationType = .words + textField.keyboardType = .namePhonePad + case .url: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .URL + case .twitter: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .twitter + case .email: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .emailAddress + case .asciiCapable: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .asciiCapable + case .password: + textField.isSecureTextEntry = true + textField.clearsOnBeginEditing = false + default: + break + } + } + } + + open override func constraintsViews() -> [String : UIView] { + var views = ["titleLabel" : titleLabel, "textField" : textField] + if self.imageView!.image != nil { + views["imageView"] = imageView + } + return views + } + + open override func defaultVisualConstraints() -> [String] { + if self.imageView!.image != nil { + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:[imageView]-[titleLabel]-[textField]-16-|"] + } else { + return ["H:[imageView]-[textField]-16-|"] + } + } else { + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:|-16-[titleLabel]-[textField]-16-|"] + } else { + return ["H:|-16-[textField]-16-|"] + } + } + } + + open override func firstResponderElement() -> UIResponder? { + return textField + } + + open override class func formRowCanBecomeFirstResponder() -> Bool { + return true + } + + // MARK: Actions + + @objc func editingChanged(_ sender: UITextField) { + guard let text = sender.text, text.count > 0 else { rowDescriptor?.value = nil; update(); return } + rowDescriptor?.value = text as AnyObject + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift new file mode 100644 index 0000000..f507603 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/FormTextViewCell.swift @@ -0,0 +1,96 @@ +// +// FormTextViewCell.swift +// SwiftForms +// +// Created by Joey Padot on 12/6/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTextViewCell : FormBaseCell, UITextViewDelegate { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let textField = UITextView() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject]! + + // MARK: Class Funcs + + open override class func formRowCellHeight() -> CGFloat { + return 110.0 + } + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + textField.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + textField.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(textField) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1.0, constant: 0.0)) + + textField.delegate = self + } + + open override func update() { + + titleLabel.text = rowDescriptor?.title + textField.text = rowDescriptor?.value as? String + + textField.isSecureTextEntry = false + textField.autocorrectionType = .default + textField.autocapitalizationType = .sentences + textField.keyboardType = .default + } + + open override func constraintsViews() -> [String : UIView] { + var views = ["titleLabel" : titleLabel, "textField" : textField] + if self.imageView!.image != nil { + views["imageView"] = imageView + } + return views + } + + open override func defaultVisualConstraints() -> [String] { + if self.imageView!.image != nil { + if let text = titleLabel.text , text.count > 0 { + return ["H:[imageView]-[titleLabel]-[textField]-16-|"] + } else { + return ["H:[imageView]-[textField]-16-|"] + } + } else { + if let text = titleLabel.text , text.count > 0 { + return ["H:|-16-[titleLabel]-[textField]-16-|"] + } else { + return ["H:|-16-[textField]-16-|"] + } + } + } + + // MARK: UITextViewDelegate + + open func textViewDidChange(_ textView: UITextView) { + guard let text = textView.text , text.count > 0 else { rowDescriptor?.value = nil; update(); return } + rowDescriptor?.value = text as AnyObject + update() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift new file mode 100644 index 0000000..24cf005 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift @@ -0,0 +1,118 @@ +// +// FormBaseCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormBaseCell: UITableViewCell { + + // MARK: Properties + + open var rowDescriptor: FormRowDescriptor? { + didSet { + self.update() + } + } + + open weak var formViewController: FormViewController? + + fileprivate var customConstraints: [NSLayoutConstraint] = [] + + // MARK: Init + + public required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + // MARK: Public interface + + open func configure() { + /// override + } + + open func update() { + /// override + } + + open func defaultVisualConstraints() -> [String] { + /// override + return [] + } + + open func constraintsViews() -> [String : UIView] { + /// override + return [:] + } + + open func firstResponderElement() -> UIResponder? { + /// override + return nil + } + + open func inputAccesoryView() -> UIToolbar { + + let actionBar = UIToolbar() + actionBar.isTranslucent = true + actionBar.sizeToFit() + actionBar.barStyle = .default + + let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FormBaseCell.handleDoneAction(_:))) + let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) + actionBar.items = [flexible, doneButton] + + return actionBar + } + + @objc internal func handleDoneAction(_: UIBarButtonItem) { + firstResponderElement()?.resignFirstResponder() + } + + open class func formRowCellHeight() -> CGFloat { + return 44.0 + } + + open class func formRowCanBecomeFirstResponder() -> Bool { + return false + } + + open class func formViewController(_ formViewController: FormViewController, didSelectRow: FormBaseCell) { + } + + // MARK: Constraints + + open override func updateConstraints() { + if customConstraints.count > 0 { + contentView.removeConstraints(customConstraints) + } + + let views = constraintsViews() + + customConstraints.removeAll() + + var visualConstraints = [String]() + + if let visualConstraintsClosure = rowDescriptor?.configuration.cell.visualConstraintsClosure { + visualConstraints = visualConstraintsClosure(self) + } else { + visualConstraints = defaultVisualConstraints() + } + + for visualConstraint in visualConstraints { + let constraints = NSLayoutConstraint.constraints(withVisualFormat: visualConstraint, options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views) + for constraint in constraints { + customConstraints.append(constraint) + } + } + + contentView.addConstraints(customConstraints) + super.updateConstraints() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift new file mode 100644 index 0000000..8cadad5 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift @@ -0,0 +1,38 @@ +// +// FormTitleCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 13/11/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTitleCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + // apply constant constraints + contentView.addSubview(titleLabel) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel] + } + + open override func defaultVisualConstraints() -> [String] { + return ["H:|-16-[titleLabel]-16-|"] + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift new file mode 100644 index 0000000..1bc7820 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/cells/base/FormValueCell.swift @@ -0,0 +1,70 @@ +// +// FormValueCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 13/11/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormValueCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let valueLabel = UILabel() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject]! + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + accessoryType = .disclosureIndicator + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + valueLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + valueLabel.textColor = UIColor.lightGray + valueLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(valueLabel) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + // apply constant constraints + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "valueLabel" : valueLabel] + } + + open override func defaultVisualConstraints() -> [String] { + + // apply default constraints + var rightPadding = 0 + if accessoryType == .none { + rightPadding = 16 + } + + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:|-16-[titleLabel]-[valueLabel]-\(rightPadding)-|"] + } + else { + return ["H:|-16-[valueLabel]-\(rightPadding)-|"] + } + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift new file mode 100644 index 0000000..1146359 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift @@ -0,0 +1,125 @@ +// +// FormOptionsSelectorController.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormOptionsSelectorController: UITableViewController, FormSelector { + + // MARK: FormSelector + + open var formCell: FormBaseCell? + + // MARK: Init + + public init() { + super.init(style: .grouped) + } + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + } + + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + open override func viewDidLoad() { + super.viewDidLoad() + self.navigationItem.title = formCell?.rowDescriptor?.title + } + + // MARK: UITableViewDataSource + + open override func numberOfSections(in tableView: UITableView) -> Int { + return 1 + } + + open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + guard let options = formCell?.rowDescriptor?.configuration.selection.options , !options.isEmpty else { return 0 } + return options.count + } + + open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + return 0.1 + } + + open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + + let reuseIdentifier = NSStringFromClass(type(of: self)) + + var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) + if cell == nil { + cell = UITableViewCell(style: .default, reuseIdentifier: reuseIdentifier) + } + + let options = formCell!.rowDescriptor!.configuration.selection.options + let optionValue = options[(indexPath as NSIndexPath).row] + + cell?.textLabel?.text = formCell?.rowDescriptor?.configuration.selection.optionTitleClosure?(optionValue) + + if let selectedOptions = formCell?.rowDescriptor?.value as? [AnyObject] { + if let _ = selectedOptions.index(where: { $0 === optionValue }) { + cell?.accessoryType = .checkmark + } else { + cell?.accessoryType = .none + } + + } else if let selectedOption = formCell?.rowDescriptor?.value { + if optionValue === selectedOption { + cell?.accessoryType = .checkmark + } else { + cell?.accessoryType = .none + } + } + + return cell! + } + + // MARK: UITableViewDelegate + + open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + + let cell = tableView.cellForRow(at: indexPath) + + var allowsMultipleSelection = false + if let allowsMultipleSelectionValue = formCell?.rowDescriptor?.configuration.selection.allowsMultipleSelection { + allowsMultipleSelection = allowsMultipleSelectionValue + } + + let options = formCell!.rowDescriptor!.configuration.selection.options + let selectedOption = options[(indexPath as NSIndexPath).row] + + if allowsMultipleSelection { + if var selectedOptions = formCell?.rowDescriptor?.value as? [AnyObject] { + if let index = selectedOptions.index(where: { $0 === selectedOption }) { + selectedOptions.remove(at: index) + cell?.accessoryType = .none + } else { + selectedOptions.append(selectedOption) + cell?.accessoryType = .checkmark + } + formCell?.rowDescriptor?.value = selectedOptions as AnyObject + + } else { + formCell?.rowDescriptor?.value = [AnyObject](arrayLiteral: selectedOption) as AnyObject + cell?.accessoryType = .checkmark + } + + } else { + formCell?.rowDescriptor?.value = selectedOption + } + + formCell?.update() + + if allowsMultipleSelection { + tableView.deselectRow(at: indexPath, animated: true) + } else { + let _ = self.navigationController?.popViewController(animated: true) + } + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift new file mode 100644 index 0000000..0032995 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormSelector.swift @@ -0,0 +1,13 @@ +// +// FormSelector.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +@objc public protocol FormSelector: NSObjectProtocol { + var formCell: FormBaseCell? { get set } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift new file mode 100644 index 0000000..257f82b --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/controllers/FormViewController.swift @@ -0,0 +1,225 @@ +// +// FormViewController.swift +// SwiftForms +// +// Created by Miguel Angel Ortuño on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormViewController : UITableViewController { + + private static var __once: () = { + FormViewController.defaultCellClasses[.text] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.label] = FormLabelCell.self + FormViewController.defaultCellClasses[.number] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.numbersAndPunctuation] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.decimal] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.name] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.phone] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.url] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.twitter] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.namePhone] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.email] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.asciiCapable] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.password] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.button] = FormButtonCell.self + FormViewController.defaultCellClasses[.booleanSwitch] = FormSwitchCell.self + FormViewController.defaultCellClasses[.booleanCheck] = FormCheckCell.self + FormViewController.defaultCellClasses[.segmentedControl] = FormSegmentedControlCell.self + FormViewController.defaultCellClasses[.picker] = FormPickerCell.self + FormViewController.defaultCellClasses[.date] = FormDateCell.self + FormViewController.defaultCellClasses[.time] = FormDateCell.self + FormViewController.defaultCellClasses[.dateAndTime] = FormDateCell.self + FormViewController.defaultCellClasses[.stepper] = FormStepperCell.self + FormViewController.defaultCellClasses[.slider] = FormSliderCell.self + FormViewController.defaultCellClasses[.multipleSelector] = FormSelectorCell.self + FormViewController.defaultCellClasses[.multilineText] = FormTextViewCell.self + }() + + // MARK: Class variables + + fileprivate static var onceDefaultCellClass: Int = 0 + fileprivate static var defaultCellClasses: [FormRowDescriptor.RowType : FormBaseCell.Type] = [:] + + // MARK: Properties + + open var form = FormDescriptor() + + // MARK: Init + + public convenience init() { + self.init(style: .grouped) + } + + public convenience init(form: FormDescriptor) { + self.init(style: .grouped) + self.form = form + } + + public override init(style: UITableView.Style) { + super.init(style: style) + } + + public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + } + + // MARK: View life cycle + + open override func viewDidLoad() { + super.viewDidLoad() + navigationItem.title = form.title + } + + // MARK: Public interface + + open func valueForTag(_ tag: String) -> AnyObject? { + for section in form.sections { + for row in section.rows { + if row.tag == tag { + return row.value + } + } + } + return nil + } + + open func setValue(_ value: AnyObject, forTag tag: String) { + for (sectionIndex, section) in form.sections.enumerated() { + for (rowIndex, row) in section.rows.enumerated() { + if row.tag == tag { + form.sections[sectionIndex].rows[rowIndex].value = value + if let cell = self.tableView.cellForRow(at: IndexPath(row: rowIndex, section: sectionIndex)) as? FormBaseCell { + cell.update() + } + return + } + } + } + } + + // MARK: UITableViewDataSource + + open override func numberOfSections(in tableView: UITableView) -> Int { + return form.sections.count + } + + open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return form.sections[section].rows.count + } + + open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) + + let reuseIdentifier = NSStringFromClass(formBaseCellClass!) + + var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? FormBaseCell + if cell == nil { + cell = formBaseCellClass?.init(style: .default, reuseIdentifier: reuseIdentifier) + cell?.formViewController = self + cell?.configure() + } + + cell?.rowDescriptor = rowDescriptor + + // apply cell custom design + for (keyPath, value) in rowDescriptor.configuration.cell.appearance { + cell?.setValue(value, forKeyPath: keyPath) + } + return cell! + } + + open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + return form.sections[section].headerTitle + } + + open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { + return form.sections[section].footerTitle + } + + open override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + guard let headerView = form.sections[section].headerView else { return nil } + return headerView + } + + open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { + guard let footerView = form.sections[section].footerView else { return nil } + return footerView + } + + open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + guard let headerView = form.sections[section].headerView , headerView.translatesAutoresizingMaskIntoConstraints else { + return form.sections[section].headerViewHeight + } + return headerView.frame.size.height + } + + open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { + guard let footerView = form.sections[section].footerView , footerView.translatesAutoresizingMaskIntoConstraints else { + return form.sections[section].footerViewHeight + } + return footerView.frame.size.height + } + + // MARK: UITableViewDelegate + + open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { + return formBaseCellClass.formRowCellHeight() + } + return super.tableView(tableView, heightForRowAt: indexPath) + } + + open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + if let selectedRow = tableView.cellForRow(at: indexPath) as? FormBaseCell { + if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { + formBaseCellClass.formViewController(self, didSelectRow: selectedRow) + } + } + + if let didSelectClosure = rowDescriptor.configuration.button.didSelectClosure { + didSelectClosure(rowDescriptor) + } + + tableView.deselectRow(at: indexPath, animated: true) + } + + fileprivate class func defaultCellClassForRowType(_ rowType: FormRowDescriptor.RowType) -> FormBaseCell.Type { + _ = FormViewController.__once + return FormViewController.defaultCellClasses[rowType]! + } + + fileprivate func formRowDescriptorAtIndexPath(_ indexPath: IndexPath) -> FormRowDescriptor { + + let section = form.sections[(indexPath as NSIndexPath).section] + let rowDescriptor = section.rows[(indexPath as NSIndexPath).row] + return rowDescriptor + } + + fileprivate func formBaseCellClassFromRowDescriptor(_ rowDescriptor: FormRowDescriptor) -> FormBaseCell.Type! { + + var formBaseCellClass: FormBaseCell.Type + + if let cellClass = rowDescriptor.configuration.cell.cellClass as? FormBaseCell.Type { + formBaseCellClass = cellClass + } else { + formBaseCellClass = FormViewController.defaultCellClassForRowType(rowDescriptor.type) + } + return formBaseCellClass + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift new file mode 100644 index 0000000..fbe7980 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift @@ -0,0 +1,58 @@ +// +// FormDescriptor.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormDescriptor { + + // MARK: Properties + + public var title: String + public var sections: [FormSectionDescriptor] = [] + + // MARK: Init + + public init() { + self.title = "" + } + + public init(title: String) { + self.title = title + } + + // MARK: Public + + public func formValues() -> [String : AnyObject] { + + var formValues: [String : AnyObject] = [:] + + for section in sections { + for row in section.rows { + if row.type != .button { + if let value = row.value { + formValues[row.tag] = value + } else { + formValues[row.tag] = NSNull() + } + } + } + } + return formValues + } + + public func validateForm() -> FormRowDescriptor? { + for section in sections { + for row in section.rows { + if row.configuration.cell.required && row.value == nil { + return row + } + } + } + return nil + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift new file mode 100644 index 0000000..9760ca3 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift @@ -0,0 +1,159 @@ +// +// FormRowDescriptor.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormRowDescriptor { + + // MARK: Types + + public enum RowType { + case unknown + case label + case text + case url + case number + case numbersAndPunctuation + case decimal + case name + case phone + case namePhone + case email + case twitter + case asciiCapable + case password + case button + case booleanSwitch + case booleanCheck + case segmentedControl + case picker + case date + case time + case dateAndTime + case stepper + case slider + case multipleSelector + case multilineText + } + + public struct CellConfiguration { + public var cellClass: AnyClass? + public var appearance: [String : AnyObject] + public var placeholder: String? + public var showsInputToolbar: Bool + public var required: Bool + public var willUpdateClosure: ((FormRowDescriptor) -> Void)? + public var didUpdateClosure: ((FormRowDescriptor) -> Void)? + public var visualConstraintsClosure: ((FormBaseCell) -> [String])? + + public init() { + cellClass = nil + appearance = [:] + placeholder = nil + showsInputToolbar = false + required = true + willUpdateClosure = nil + didUpdateClosure = nil + visualConstraintsClosure = nil + } + } + + public struct SelectionConfiguration { + public var controllerClass: AnyClass? + public var options: [AnyObject] + public var optionTitleClosure: ((AnyObject) -> String)? + public var allowsMultipleSelection: Bool + + public init() { + controllerClass = nil + options = [] + optionTitleClosure = nil + allowsMultipleSelection = false + } + } + + public struct ButtonConfiguration { + public var didSelectClosure: ((FormRowDescriptor) -> Void)? + + public init() { + didSelectClosure = nil + } + } + + public struct StepperConfiguration { + public var maximumValue: Double + public var minimumValue: Double + public var steps: Double + public var continuous: Bool + + public init() { + maximumValue = 0.0 + minimumValue = 0.0 + steps = 0.0 + continuous = false + } + } + + public struct DateConfiguration { + public var dateFormatter: DateFormatter? + } + + public struct RowConfiguration { + public var cell: CellConfiguration + public var selection: SelectionConfiguration + public var button: ButtonConfiguration + public var stepper: StepperConfiguration + public var date: DateConfiguration + public var userInfo: [String : AnyObject] + + init() { + cell = CellConfiguration() + selection = SelectionConfiguration() + button = ButtonConfiguration() + stepper = StepperConfiguration() + date = DateConfiguration() + userInfo = [:] + } + } + + // MARK: Properties + + public let tag: String + public let type: RowType + + public var title: String? + + public var value: AnyObject? { + willSet { + guard let willUpdateBlock = configuration.cell.willUpdateClosure else { return } + willUpdateBlock(self) + } + didSet { + guard let didUpdateBlock = configuration.cell.didUpdateClosure else { return } + didUpdateBlock(self) + } + } + + public var configuration: RowConfiguration + + // MARK: Init + + public init(tag: String, type: RowType, title: String, configuration: RowConfiguration) { + self.tag = tag + self.type = type + self.title = title + self.configuration = configuration + } + + public init(tag: String, type: RowType, title: String) { + self.tag = tag + self.type = type + self.title = title + self.configuration = RowConfiguration() + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift new file mode 100644 index 0000000..eab041a --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift @@ -0,0 +1,32 @@ +// +// FormSectionDescriptor.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormSectionDescriptor { + + // MARK: Properties + + public var rows: [FormRowDescriptor] = [] + + public var headerTitle: String? + public var footerTitle: String? + + public var headerView: UIView? + public var footerView: UIView? + + public var headerViewHeight: CGFloat = UITableView.automaticDimension + public var footerViewHeight: CGFloat = UITableView.automaticDimension + + // MARK: Init + + public init(headerTitle: String?, footerTitle: String?) { + self.headerTitle = headerTitle + self.footerTitle = footerTitle + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/project.pbxproj b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/project.pbxproj new file mode 100644 index 0000000..015ee3b --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 0C9D1DF31D2267EE00909941 /* FormOptionsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C9D1DF21D2267EE00909941 /* FormOptionsViewController.swift */; }; + 0CB1F6C31C37F9B900CD2A7B /* FormErrorType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CB1F6C21C37F9B900CD2A7B /* FormErrorType.swift */; }; + 0CCA33DD1B04FA5A006D9666 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA33DC1B04FA5A006D9666 /* AppDelegate.swift */; }; + 0CCA33DF1B04FA5A006D9666 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA33DE1B04FA5A006D9666 /* ViewController.swift */; }; + 0CCA33E21B04FA5A006D9666 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0CCA33E01B04FA5A006D9666 /* Main.storyboard */; }; + 0CCA33E41B04FA5A006D9666 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0CCA33E31B04FA5A006D9666 /* Images.xcassets */; }; + 0CCA34141B04FAD3006D9666 /* ExampleFormViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA33FC1B04FAD3006D9666 /* ExampleFormViewController.swift */; }; + 0CCA34311B04FBE0006D9666 /* SwiftForms.h in Headers */ = {isa = PBXBuildFile; fileRef = 0CCA34301B04FBE0006D9666 /* SwiftForms.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0CCA34431B04FBE0006D9666 /* SwiftForms.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0CCA342C1B04FBDF006D9666 /* SwiftForms.framework */; }; + 0CCA34441B04FBE0006D9666 /* SwiftForms.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 0CCA342C1B04FBDF006D9666 /* SwiftForms.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 0CCA34611B0502B5006D9666 /* Launch.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0CCA34601B0502B5006D9666 /* Launch.storyboard */; }; + 0CCA34781B050525006D9666 /* FormBaseCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34641B050525006D9666 /* FormBaseCell.swift */; }; + 0CCA34791B050525006D9666 /* FormTitleCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34651B050525006D9666 /* FormTitleCell.swift */; }; + 0CCA347A1B050525006D9666 /* FormValueCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34661B050525006D9666 /* FormValueCell.swift */; }; + 0CCA347B1B050525006D9666 /* FormButtonCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34671B050525006D9666 /* FormButtonCell.swift */; }; + 0CCA347C1B050525006D9666 /* FormCheckCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34681B050525006D9666 /* FormCheckCell.swift */; }; + 0CCA347D1B050525006D9666 /* FormDateCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34691B050525006D9666 /* FormDateCell.swift */; }; + 0CCA347E1B050525006D9666 /* FormPickerCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346A1B050525006D9666 /* FormPickerCell.swift */; }; + 0CCA347F1B050525006D9666 /* FormSegmentedControlCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346B1B050525006D9666 /* FormSegmentedControlCell.swift */; }; + 0CCA34801B050525006D9666 /* FormSelectorCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346C1B050525006D9666 /* FormSelectorCell.swift */; }; + 0CCA34811B050525006D9666 /* FormSwitchCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346D1B050525006D9666 /* FormSwitchCell.swift */; }; + 0CCA34821B050525006D9666 /* FormTextFieldCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346E1B050525006D9666 /* FormTextFieldCell.swift */; }; + 0CCA34831B050525006D9666 /* FormTextViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA346F1B050525006D9666 /* FormTextViewCell.swift */; }; + 0CCA34851B050525006D9666 /* FormSelector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34721B050525006D9666 /* FormSelector.swift */; }; + 0CCA34861B050525006D9666 /* FormViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34731B050525006D9666 /* FormViewController.swift */; }; + 0CCA34871B050525006D9666 /* FormDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34751B050525006D9666 /* FormDescriptor.swift */; }; + 0CCA34881B050525006D9666 /* FormRowDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34761B050525006D9666 /* FormRowDescriptor.swift */; }; + 0CCA34891B050525006D9666 /* FormSectionDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CCA34771B050525006D9666 /* FormSectionDescriptor.swift */; }; + 0CDBB4F11B10699A00BE6ACF /* FormStepperCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CDBB4F01B10699A00BE6ACF /* FormStepperCell.swift */; }; + 0CDBB4F31B10724600BE6ACF /* FormSliderCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CDBB4F21B10724600BE6ACF /* FormSliderCell.swift */; }; + BDD1087A1C925D14000EDEE5 /* FormLabelCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDD108791C925D14000EDEE5 /* FormLabelCell.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0CCA34411B04FBE0006D9666 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0CCA33CF1B04FA5A006D9666 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0CCA342B1B04FBDF006D9666; + remoteInfo = SwiftForms; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 0CCA34481B04FBE0006D9666 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 0CCA34441B04FBE0006D9666 /* SwiftForms.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 0C9D1DF21D2267EE00909941 /* FormOptionsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormOptionsViewController.swift; sourceTree = ""; }; + 0CB1F6C21C37F9B900CD2A7B /* FormErrorType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormErrorType.swift; sourceTree = ""; }; + 0CCA33D71B04FA5A006D9666 /* SwiftFormsApplication.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftFormsApplication.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 0CCA33DB1B04FA5A006D9666 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0CCA33DC1B04FA5A006D9666 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 0CCA33DE1B04FA5A006D9666 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 0CCA33E11B04FA5A006D9666 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 0CCA33E31B04FA5A006D9666 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; + 0CCA33FC1B04FAD3006D9666 /* ExampleFormViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExampleFormViewController.swift; sourceTree = ""; }; + 0CCA342C1B04FBDF006D9666 /* SwiftForms.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftForms.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0CCA342F1B04FBE0006D9666 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0CCA34301B04FBE0006D9666 /* SwiftForms.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftForms.h; sourceTree = ""; }; + 0CCA34601B0502B5006D9666 /* Launch.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Launch.storyboard; sourceTree = ""; }; + 0CCA34641B050525006D9666 /* FormBaseCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormBaseCell.swift; sourceTree = ""; }; + 0CCA34651B050525006D9666 /* FormTitleCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormTitleCell.swift; sourceTree = ""; }; + 0CCA34661B050525006D9666 /* FormValueCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormValueCell.swift; sourceTree = ""; }; + 0CCA34671B050525006D9666 /* FormButtonCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormButtonCell.swift; sourceTree = ""; }; + 0CCA34681B050525006D9666 /* FormCheckCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormCheckCell.swift; sourceTree = ""; }; + 0CCA34691B050525006D9666 /* FormDateCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormDateCell.swift; sourceTree = ""; }; + 0CCA346A1B050525006D9666 /* FormPickerCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormPickerCell.swift; sourceTree = ""; }; + 0CCA346B1B050525006D9666 /* FormSegmentedControlCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSegmentedControlCell.swift; sourceTree = ""; }; + 0CCA346C1B050525006D9666 /* FormSelectorCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSelectorCell.swift; sourceTree = ""; }; + 0CCA346D1B050525006D9666 /* FormSwitchCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSwitchCell.swift; sourceTree = ""; }; + 0CCA346E1B050525006D9666 /* FormTextFieldCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormTextFieldCell.swift; sourceTree = ""; }; + 0CCA346F1B050525006D9666 /* FormTextViewCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormTextViewCell.swift; sourceTree = ""; }; + 0CCA34721B050525006D9666 /* FormSelector.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSelector.swift; sourceTree = ""; }; + 0CCA34731B050525006D9666 /* FormViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormViewController.swift; sourceTree = ""; }; + 0CCA34751B050525006D9666 /* FormDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormDescriptor.swift; sourceTree = ""; }; + 0CCA34761B050525006D9666 /* FormRowDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormRowDescriptor.swift; sourceTree = ""; }; + 0CCA34771B050525006D9666 /* FormSectionDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSectionDescriptor.swift; sourceTree = ""; }; + 0CDBB4F01B10699A00BE6ACF /* FormStepperCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormStepperCell.swift; sourceTree = ""; }; + 0CDBB4F21B10724600BE6ACF /* FormSliderCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormSliderCell.swift; sourceTree = ""; }; + BDD108791C925D14000EDEE5 /* FormLabelCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormLabelCell.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0CCA33D41B04FA5A006D9666 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0CCA34431B04FBE0006D9666 /* SwiftForms.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0CCA34281B04FBDF006D9666 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0CCA33CE1B04FA5A006D9666 = { + isa = PBXGroup; + children = ( + 0CCA33D91B04FA5A006D9666 /* SwiftFormsApplication */, + 0CCA342D1B04FBE0006D9666 /* SwiftForms */, + 0CCA33D81B04FA5A006D9666 /* Products */, + ); + sourceTree = ""; + }; + 0CCA33D81B04FA5A006D9666 /* Products */ = { + isa = PBXGroup; + children = ( + 0CCA33D71B04FA5A006D9666 /* SwiftFormsApplication.app */, + 0CCA342C1B04FBDF006D9666 /* SwiftForms.framework */, + ); + name = Products; + sourceTree = ""; + }; + 0CCA33D91B04FA5A006D9666 /* SwiftFormsApplication */ = { + isa = PBXGroup; + children = ( + 0CCA33FC1B04FAD3006D9666 /* ExampleFormViewController.swift */, + 0CCA33DC1B04FA5A006D9666 /* AppDelegate.swift */, + 0CCA33DE1B04FA5A006D9666 /* ViewController.swift */, + 0CCA33E01B04FA5A006D9666 /* Main.storyboard */, + 0CCA33E31B04FA5A006D9666 /* Images.xcassets */, + 0CCA33DA1B04FA5A006D9666 /* Supporting Files */, + 0CCA34601B0502B5006D9666 /* Launch.storyboard */, + ); + path = SwiftFormsApplication; + sourceTree = ""; + }; + 0CCA33DA1B04FA5A006D9666 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 0CCA33DB1B04FA5A006D9666 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 0CCA342D1B04FBE0006D9666 /* SwiftForms */ = { + isa = PBXGroup; + children = ( + 0CCA34621B050525006D9666 /* cells */, + 0CCA34701B050525006D9666 /* controllers */, + 0CCA34741B050525006D9666 /* descriptors */, + 0CB1F6C21C37F9B900CD2A7B /* FormErrorType.swift */, + 0CCA34301B04FBE0006D9666 /* SwiftForms.h */, + 0CCA342E1B04FBE0006D9666 /* Supporting Files */, + ); + path = SwiftForms; + sourceTree = ""; + }; + 0CCA342E1B04FBE0006D9666 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 0CCA342F1B04FBE0006D9666 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 0CCA34621B050525006D9666 /* cells */ = { + isa = PBXGroup; + children = ( + 0CCA34631B050525006D9666 /* base */, + 0CCA34671B050525006D9666 /* FormButtonCell.swift */, + BDD108791C925D14000EDEE5 /* FormLabelCell.swift */, + 0CCA34681B050525006D9666 /* FormCheckCell.swift */, + 0CCA34691B050525006D9666 /* FormDateCell.swift */, + 0CCA346A1B050525006D9666 /* FormPickerCell.swift */, + 0CCA346B1B050525006D9666 /* FormSegmentedControlCell.swift */, + 0CCA346C1B050525006D9666 /* FormSelectorCell.swift */, + 0CCA346D1B050525006D9666 /* FormSwitchCell.swift */, + 0CCA346E1B050525006D9666 /* FormTextFieldCell.swift */, + 0CCA346F1B050525006D9666 /* FormTextViewCell.swift */, + 0CDBB4F01B10699A00BE6ACF /* FormStepperCell.swift */, + 0CDBB4F21B10724600BE6ACF /* FormSliderCell.swift */, + ); + path = cells; + sourceTree = ""; + }; + 0CCA34631B050525006D9666 /* base */ = { + isa = PBXGroup; + children = ( + 0CCA34641B050525006D9666 /* FormBaseCell.swift */, + 0CCA34651B050525006D9666 /* FormTitleCell.swift */, + 0CCA34661B050525006D9666 /* FormValueCell.swift */, + ); + path = base; + sourceTree = ""; + }; + 0CCA34701B050525006D9666 /* controllers */ = { + isa = PBXGroup; + children = ( + 0CCA34721B050525006D9666 /* FormSelector.swift */, + 0CCA34731B050525006D9666 /* FormViewController.swift */, + 0C9D1DF21D2267EE00909941 /* FormOptionsViewController.swift */, + ); + path = controllers; + sourceTree = ""; + }; + 0CCA34741B050525006D9666 /* descriptors */ = { + isa = PBXGroup; + children = ( + 0CCA34751B050525006D9666 /* FormDescriptor.swift */, + 0CCA34761B050525006D9666 /* FormRowDescriptor.swift */, + 0CCA34771B050525006D9666 /* FormSectionDescriptor.swift */, + ); + path = descriptors; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0CCA34291B04FBDF006D9666 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 0CCA34311B04FBE0006D9666 /* SwiftForms.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 0CCA33D61B04FA5A006D9666 /* SwiftFormsApplication */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0CCA33F61B04FA5A006D9666 /* Build configuration list for PBXNativeTarget "SwiftFormsApplication" */; + buildPhases = ( + 0CCA33D31B04FA5A006D9666 /* Sources */, + 0CCA33D41B04FA5A006D9666 /* Frameworks */, + 0CCA33D51B04FA5A006D9666 /* Resources */, + 0CCA34481B04FBE0006D9666 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 0CCA34421B04FBE0006D9666 /* PBXTargetDependency */, + ); + name = SwiftFormsApplication; + productName = SwiftFormsApplication; + productReference = 0CCA33D71B04FA5A006D9666 /* SwiftFormsApplication.app */; + productType = "com.apple.product-type.application"; + }; + 0CCA342B1B04FBDF006D9666 /* SwiftForms */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0CCA34451B04FBE0006D9666 /* Build configuration list for PBXNativeTarget "SwiftForms" */; + buildPhases = ( + 0CCA34271B04FBDF006D9666 /* Sources */, + 0CCA34281B04FBDF006D9666 /* Frameworks */, + 0CCA34291B04FBDF006D9666 /* Headers */, + 0CCA342A1B04FBDF006D9666 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftForms; + productName = SwiftForms; + productReference = 0CCA342C1B04FBDF006D9666 /* SwiftForms.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 0CCA33CF1B04FA5A006D9666 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftMigration = 0700; + LastSwiftUpdateCheck = 0700; + LastUpgradeCheck = 1000; + ORGANIZATIONNAME = "Miguel Angel Ortuno Ortuno"; + TargetAttributes = { + 0CCA33D61B04FA5A006D9666 = { + CreatedOnToolsVersion = 6.3.1; + LastSwiftMigration = 1000; + }; + 0CCA342B1B04FBDF006D9666 = { + CreatedOnToolsVersion = 6.3.1; + LastSwiftMigration = 1000; + }; + }; + }; + buildConfigurationList = 0CCA33D21B04FA5A006D9666 /* Build configuration list for PBXProject "SwiftFormsApplication" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 0CCA33CE1B04FA5A006D9666; + productRefGroup = 0CCA33D81B04FA5A006D9666 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 0CCA33D61B04FA5A006D9666 /* SwiftFormsApplication */, + 0CCA342B1B04FBDF006D9666 /* SwiftForms */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 0CCA33D51B04FA5A006D9666 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0CCA33E21B04FA5A006D9666 /* Main.storyboard in Resources */, + 0CCA34611B0502B5006D9666 /* Launch.storyboard in Resources */, + 0CCA33E41B04FA5A006D9666 /* Images.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0CCA342A1B04FBDF006D9666 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0CCA33D31B04FA5A006D9666 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0CCA33DF1B04FA5A006D9666 /* ViewController.swift in Sources */, + 0CCA34141B04FAD3006D9666 /* ExampleFormViewController.swift in Sources */, + 0CCA33DD1B04FA5A006D9666 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0CCA34271B04FBDF006D9666 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0CCA34851B050525006D9666 /* FormSelector.swift in Sources */, + 0CCA34791B050525006D9666 /* FormTitleCell.swift in Sources */, + 0CDBB4F31B10724600BE6ACF /* FormSliderCell.swift in Sources */, + 0CCA34891B050525006D9666 /* FormSectionDescriptor.swift in Sources */, + 0CCA34871B050525006D9666 /* FormDescriptor.swift in Sources */, + 0CCA34781B050525006D9666 /* FormBaseCell.swift in Sources */, + BDD1087A1C925D14000EDEE5 /* FormLabelCell.swift in Sources */, + 0CCA34831B050525006D9666 /* FormTextViewCell.swift in Sources */, + 0CB1F6C31C37F9B900CD2A7B /* FormErrorType.swift in Sources */, + 0CCA34861B050525006D9666 /* FormViewController.swift in Sources */, + 0CCA347B1B050525006D9666 /* FormButtonCell.swift in Sources */, + 0CDBB4F11B10699A00BE6ACF /* FormStepperCell.swift in Sources */, + 0CCA34801B050525006D9666 /* FormSelectorCell.swift in Sources */, + 0CCA34811B050525006D9666 /* FormSwitchCell.swift in Sources */, + 0CCA347C1B050525006D9666 /* FormCheckCell.swift in Sources */, + 0CCA347A1B050525006D9666 /* FormValueCell.swift in Sources */, + 0CCA347F1B050525006D9666 /* FormSegmentedControlCell.swift in Sources */, + 0CCA34821B050525006D9666 /* FormTextFieldCell.swift in Sources */, + 0CCA347E1B050525006D9666 /* FormPickerCell.swift in Sources */, + 0C9D1DF31D2267EE00909941 /* FormOptionsViewController.swift in Sources */, + 0CCA347D1B050525006D9666 /* FormDateCell.swift in Sources */, + 0CCA34881B050525006D9666 /* FormRowDescriptor.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0CCA34421B04FBE0006D9666 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 0CCA342B1B04FBDF006D9666 /* SwiftForms */; + targetProxy = 0CCA34411B04FBE0006D9666 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 0CCA33E01B04FA5A006D9666 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 0CCA33E11B04FA5A006D9666 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 0CCA33F41B04FA5A006D9666 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + 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[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + 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 = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 0CCA33F51B04FA5A006D9666 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + 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[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + 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; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 0CCA33F71B04FA5A006D9666 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwiftFormsApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ortulabs.SwiftFormsApplication; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + 0CCA33F81B04FA5A006D9666 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = SwiftFormsApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.ortulabs.SwiftFormsApplication; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + }; + name = Release; + }; + 0CCA34461B04FBE0006D9666 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = SwiftForms/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.ortulabs.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.2; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 0CCA34471B04FBE0006D9666 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = SwiftForms/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.ortulabs.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 4.2; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 0CCA33D21B04FA5A006D9666 /* Build configuration list for PBXProject "SwiftFormsApplication" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0CCA33F41B04FA5A006D9666 /* Debug */, + 0CCA33F51B04FA5A006D9666 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0CCA33F61B04FA5A006D9666 /* Build configuration list for PBXNativeTarget "SwiftFormsApplication" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0CCA33F71B04FA5A006D9666 /* Debug */, + 0CCA33F81B04FA5A006D9666 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0CCA34451B04FBE0006D9666 /* Build configuration list for PBXNativeTarget "SwiftForms" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0CCA34461B04FBE0006D9666 /* Debug */, + 0CCA34471B04FBE0006D9666 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 0CCA33CF1B04FA5A006D9666 /* Project object */; +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/xcshareddata/xcschemes/SwiftForms.xcscheme b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/xcshareddata/xcschemes/SwiftForms.xcscheme new file mode 100644 index 0000000..9518433 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication.xcodeproj/xcshareddata/xcschemes/SwiftForms.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/AppDelegate.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/AppDelegate.swift new file mode 100644 index 0000000..3326be9 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/AppDelegate.swift @@ -0,0 +1,35 @@ +// +// AppDelegate.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : Any]?) -> Bool { + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + } + + func applicationDidEnterBackground(_ application: UIApplication) { + } + + func applicationWillEnterForeground(_ application: UIApplication) { + } + + func applicationDidBecomeActive(_ application: UIApplication) { + } + + func applicationWillTerminate(_ application: UIApplication) { + } +} + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Base.lproj/Main.storyboard b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Base.lproj/Main.storyboard new file mode 100644 index 0000000..6fcfd4c --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Base.lproj/Main.storyboard @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Example.gif b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Example.gif new file mode 100644 index 0000000..1ccfd34 Binary files /dev/null and b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Example.gif differ diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ExampleFormViewController.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ExampleFormViewController.swift new file mode 100644 index 0000000..b5cfb87 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ExampleFormViewController.swift @@ -0,0 +1,229 @@ +// +// ExampleFormViewController.swift +// SwiftForms +//® +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit +import SwiftForms + +class ExampleFormViewController: FormViewController { + + let pickerOptions = ["One", "Two", "Three"] as [AnyObject] + + struct Static { + static let nameTag = "name" + static let passwordTag = "password" + static let lastNameTag = "lastName" + static let jobTag = "job" + static let emailTag = "email" + static let URLTag = "url" + static let phoneTag = "phone" + static let enabled = "enabled" + static let check = "check" + static let segmented = "segmented" + static let picker = "picker" + static let birthday = "birthday" + static let categories = "categories" + static let button = "button" + static let stepper = "stepper" + static let slider = "slider" + static let textView = "textview" + } + + required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + self.loadForm() + } + + override func viewDidLoad() { + super.viewDidLoad() + self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .plain, target: self, action: #selector(ExampleFormViewController.submit(_:))) + } + + // MARK: Actions + + @objc func submit(_: UIBarButtonItem!) { + + let message = self.form.formValues().description + + let alertController = UIAlertController(title: "Form output", message: message, preferredStyle: .alert) + + let cancel = UIAlertAction(title: "OK", style: .cancel) { (action) in + } + + alertController.addAction(cancel) + + self.present(alertController, animated: true, completion: nil) + } + + // MARK: Private interface + + fileprivate func loadForm() { + + let form = FormDescriptor(title: "Example Form") + + let section1 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) + + var row = FormRowDescriptor(tag: Static.emailTag, type: .email, title: "Email") + row.configuration.cell.appearance = ["textField.placeholder" : "john@gmail.com" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject ] + section1.rows.append(row) + + row = FormRowDescriptor(tag: Static.passwordTag, type: .password, title: "Password") + row.configuration.cell.appearance = ["textField.placeholder" : "Enter password" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section1.rows.append(row) + + let section2 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) + + row = FormRowDescriptor(tag: Static.nameTag, type: .name, title: "First Name") + row.configuration.cell.appearance = ["textField.placeholder" : "e.g. Miguel Ángel" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section2.rows.append(row) + + row = FormRowDescriptor(tag: Static.lastNameTag, type: .name, title: "Last Name") + row.configuration.cell.appearance = ["textField.placeholder" : "e.g. Ortuño" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section2.rows.append(row) + + row = FormRowDescriptor(tag: Static.jobTag, type: .text, title: "Job") + row.configuration.cell.appearance = ["textField.placeholder" : "e.g. Entrepreneur" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section2.rows.append(row) + + let section3 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) + + row = FormRowDescriptor(tag: Static.URLTag, type: .url, title: "URL") + row.configuration.cell.appearance = ["textField.placeholder" : "e.g. gethooksapp.com" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section3.rows.append(row) + + row = FormRowDescriptor(tag: Static.phoneTag, type: .phone, title: "Phone") + row.configuration.cell.appearance = ["textField.placeholder" : "e.g. 0034666777999" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject] + section3.rows.append(row) + + let section4 = FormSectionDescriptor(headerTitle: "An example header title", footerTitle: "An example footer title") + + row = FormRowDescriptor(tag: Static.enabled, type: .booleanSwitch, title: "Enable") + section4.rows.append(row) + + row = FormRowDescriptor(tag: Static.check, type: .booleanCheck, title: "Doable") + section4.rows.append(row) + + row = FormRowDescriptor(tag: Static.segmented, type: .segmentedControl, title: "Priority") + row.configuration.selection.options = ([0, 1, 2, 3] as [Int]) as [AnyObject] + row.configuration.selection.optionTitleClosure = { value in + guard let option = value as? Int else { return "" } + switch option { + case 0: + return "None" + case 1: + return "!" + case 2: + return "!!" + case 3: + return "!!!" + default: + return "" + } + } + + row.configuration.cell.appearance = ["titleLabel.font" : UIFont.boldSystemFont(ofSize: 30.0), "segmentedControl.tintColor" : UIColor.red] + + section4.rows.append(row) + + let section5 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) + + row = FormRowDescriptor(tag: Static.picker, type: .picker, title: "Gender") + row.configuration.cell.showsInputToolbar = true + row.configuration.selection.options = (["F", "M", "U"] as [String]) as [AnyObject] + row.configuration.selection.optionTitleClosure = { value in + guard let option = value as? String else { return "" } + switch option { + case "F": + return "Female" + case "M": + return "Male" + case "U": + return "I'd rather not to say" + default: + return "" + } + } + + row.value = "M" as AnyObject + + section5.rows.append(row) + + row = FormRowDescriptor(tag: Static.birthday, type: .date, title: "Birthday") + row.configuration.cell.showsInputToolbar = true + section5.rows.append(row) + + row = FormRowDescriptor(tag: Static.categories, type: .multipleSelector, title: "Categories") + row.configuration.selection.options = ([0, 1, 2, 3, 4] as [Int]) as [AnyObject] + row.configuration.selection.allowsMultipleSelection = true + row.configuration.selection.optionTitleClosure = { value in + guard let option = value as? Int else { return "" } + switch option { + case 0: + return "Restaurant" + case 1: + return "Pub" + case 2: + return "Shop" + case 3: + return "Hotel" + case 4: + return "Camping" + default: + return "" + } + } + + section5.rows.append(row) + + let section6 = FormSectionDescriptor(headerTitle: "Stepper & Slider", footerTitle: nil) + + row = FormRowDescriptor(tag: Static.stepper, type: .stepper, title: "Step count") + row.configuration.stepper.maximumValue = 200.0 + row.configuration.stepper.minimumValue = 20.0 + row.configuration.stepper.steps = 2.0 + section6.rows.append(row) + + row = FormRowDescriptor(tag: Static.slider, type: .slider, title: "Slider") + row.configuration.stepper.maximumValue = 200.0 + row.configuration.stepper.minimumValue = 20.0 + row.configuration.stepper.steps = 2.0 + row.value = 0.5 as AnyObject + row.configuration.cell.appearance = ["titleLabel.textColor": UIColor.black, + "sliderView.tintColor": UIColor.red] + section6.rows.append(row) + + row = FormRowDescriptor(tag: Static.picker, type: .picker, title: "Favorite") + row.configuration.cell.showsInputToolbar = true + row.configuration.selection.options = pickerOptions + row.configuration.selection.optionTitleClosure = { value in + guard let option = value as? String else { return "" } + return option + } + row.value = pickerOptions[0] as AnyObject + row.configuration.cell.appearance = [ + "valueLabel.accessibilityIdentifier": "PickerTextFied" as AnyObject] + section6.rows.append(row) + + let section7 = FormSectionDescriptor(headerTitle: "Multiline TextView", footerTitle: nil) + row = FormRowDescriptor(tag: Static.textView, type: .multilineText, title: "Notes") + row.configuration.cell.appearance = ["textField.textColor": UIColor.blue, + "textField.text": "This is a non-text view" as AnyObject] + section7.rows.append(row) + + let section8 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) + + row = FormRowDescriptor(tag: Static.button, type: .button, title: "Dismiss") + row.configuration.button.didSelectClosure = { _ in + self.view.endEditing(true) + } + section8.rows.append(row) + + form.sections = [section1, section2, section3, section4, section5, section6, section7, section8] + + self.form = form + } +} diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/AppIcon.appiconset/Contents.json b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "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/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/Contents.json b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/Contents.json new file mode 100644 index 0000000..cd2f7b1 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/Contents.json @@ -0,0 +1,143 @@ +{ + "images" : [ + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "minimum-system-version" : "8.0", + "subtype" : "736h", + "scale" : "3x" + }, + { + "orientation" : "landscape", + "idiom" : "iphone", + "extent" : "full-screen", + "minimum-system-version" : "8.0", + "subtype" : "736h", + "scale" : "3x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "minimum-system-version" : "8.0", + "subtype" : "667h", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "extent" : "full-screen", + "idiom" : "iphone", + "subtype" : "retina4", + "filename" : "iphone5_splash.png", + "minimum-system-version" : "7.0", + "orientation" : "portrait", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "1x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "1x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "scale" : "1x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "subtype" : "retina4", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "to-status-bar", + "scale" : "1x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "scale" : "1x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "to-status-bar", + "scale" : "1x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "scale" : "1x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "to-status-bar", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "scale" : "2x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "to-status-bar", + "scale" : "2x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/iphone5_splash.png b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/iphone5_splash.png new file mode 100644 index 0000000..1f80f40 Binary files /dev/null and b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Images.xcassets/LaunchImage.launchimage/iphone5_splash.png differ diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Info.plist b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Info.plist new file mode 100644 index 0000000..073f648 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Info.plist @@ -0,0 +1,38 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + Launch + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Launch.storyboard b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Launch.storyboard new file mode 100644 index 0000000..0b061a3 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Launch.storyboard @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Screenshot.png b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Screenshot.png new file mode 100644 index 0000000..ee051ec Binary files /dev/null and b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/Screenshot.png differ diff --git a/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ViewController.swift b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ViewController.swift new file mode 100644 index 0000000..f4efe22 --- /dev/null +++ b/My Mind/Carthage/Checkouts/SwiftForms/SwiftFormsApplication/ViewController.swift @@ -0,0 +1,23 @@ +// +// ViewController.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 14/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } +} + diff --git a/My Mind/My Mind.xcodeproj/project.pbxproj b/My Mind/My Mind.xcodeproj/project.pbxproj new file mode 100644 index 0000000..895f59a --- /dev/null +++ b/My Mind/My Mind.xcodeproj/project.pbxproj @@ -0,0 +1,746 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 54B35A13608BADDA46E984A4 /* Pods_My_MindTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F4CD8F77375199A310F844F3 /* Pods_My_MindTests.framework */; }; + 5F65059821D31E6100EEF460 /* OnBoardingController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F65059721D31E6100EEF460 /* OnBoardingController.swift */; }; + 5FB915EA21D447A400756E3E /* LoginInterfaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FB915E921D447A400756E3E /* LoginInterfaces.swift */; }; + 5FDA289221D3199500670060 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FDA289121D3199500670060 /* AppDelegate.swift */; }; + 5FDA289921D3199500670060 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5FDA289721D3199500670060 /* Main.storyboard */; }; + 5FDA289B21D3199700670060 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5FDA289A21D3199700670060 /* Assets.xcassets */; }; + 5FDA289E21D3199700670060 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5FDA289C21D3199700670060 /* LaunchScreen.storyboard */; }; + 5FDA28A921D3199700670060 /* My_MindTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FDA28A821D3199700670060 /* My_MindTests.swift */; }; + 5FDA28B421D3199700670060 /* My_MindUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FDA28B321D3199700670060 /* My_MindUITests.swift */; }; + 93464BBFC2118E9B8957BA52 /* Pods_My_Mind.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29D9F228DBCF906382669F17 /* Pods_My_Mind.framework */; }; + EA9E00CE71599AECCADA6B33 /* Pods_My_MindUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50DA9DC03A901B75E8E4B3A4 /* Pods_My_MindUITests.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 5FDA28A521D3199700670060 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 5FDA288621D3199500670060 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5FDA288D21D3199500670060; + remoteInfo = "My Mind"; + }; + 5FDA28B021D3199700670060 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 5FDA288621D3199500670060 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5FDA288D21D3199500670060; + remoteInfo = "My Mind"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0551EF0922602C8062E5541B /* Pods-My MindTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My MindTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.debug.xcconfig"; sourceTree = ""; }; + 1042D1A5D303E942D4AFE1C1 /* Pods-My Mind.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My Mind.debug.xcconfig"; path = "Pods/Target Support Files/Pods-My Mind/Pods-My Mind.debug.xcconfig"; sourceTree = ""; }; + 29D9F228DBCF906382669F17 /* Pods_My_Mind.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_My_Mind.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 50DA9DC03A901B75E8E4B3A4 /* Pods_My_MindUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_My_MindUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 523A962748FE07E7626065C8 /* Pods-My MindTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My MindTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.release.xcconfig"; sourceTree = ""; }; + 5F65059721D31E6100EEF460 /* OnBoardingController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnBoardingController.swift; sourceTree = ""; }; + 5FB915E921D447A400756E3E /* LoginInterfaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = LoginInterfaces.swift; path = "/Users/alexanderdavis/Documents/GitHub/My-Mind-2.0/My Mind/My Mind/LoginInterfaces.swift"; sourceTree = ""; }; + 5FDA288E21D3199500670060 /* My Mind.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "My Mind.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5FDA289121D3199500670060 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 5FDA289821D3199500670060 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 5FDA289A21D3199700670060 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 5FDA289D21D3199700670060 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 5FDA289F21D3199700670060 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5FDA28A421D3199700670060 /* My MindTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "My MindTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5FDA28A821D3199700670060 /* My_MindTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = My_MindTests.swift; sourceTree = ""; }; + 5FDA28AA21D3199700670060 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5FDA28AF21D3199700670060 /* My MindUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "My MindUITests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5FDA28B321D3199700670060 /* My_MindUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = My_MindUITests.swift; sourceTree = ""; }; + 5FDA28B521D3199700670060 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A7722539AB57A2EBEE52BDF6 /* Pods-My Mind.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My Mind.release.xcconfig"; path = "Pods/Target Support Files/Pods-My Mind/Pods-My Mind.release.xcconfig"; sourceTree = ""; }; + DA191761ED3CD7B6B2626140 /* Pods-My MindUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My MindUITests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.debug.xcconfig"; sourceTree = ""; }; + E703D2ACFC7C1D9097E40E05 /* Pods-My MindUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-My MindUITests.release.xcconfig"; path = "Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.release.xcconfig"; sourceTree = ""; }; + F4CD8F77375199A310F844F3 /* Pods_My_MindTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_My_MindTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 5FDA288B21D3199500670060 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 93464BBFC2118E9B8957BA52 /* Pods_My_Mind.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28A121D3199700670060 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 54B35A13608BADDA46E984A4 /* Pods_My_MindTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28AC21D3199700670060 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EA9E00CE71599AECCADA6B33 /* Pods_My_MindUITests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 5FDA288521D3199500670060 = { + isa = PBXGroup; + children = ( + 5FDA289021D3199500670060 /* My Mind */, + 5FDA28A721D3199700670060 /* My MindTests */, + 5FDA28B221D3199700670060 /* My MindUITests */, + 5FDA288F21D3199500670060 /* Products */, + AD0A75B5A0BB6EF6862F0834 /* Pods */, + 71AD7FCFD401872222F06230 /* Frameworks */, + ); + sourceTree = ""; + }; + 5FDA288F21D3199500670060 /* Products */ = { + isa = PBXGroup; + children = ( + 5FDA288E21D3199500670060 /* My Mind.app */, + 5FDA28A421D3199700670060 /* My MindTests.xctest */, + 5FDA28AF21D3199700670060 /* My MindUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 5FDA289021D3199500670060 /* My Mind */ = { + isa = PBXGroup; + children = ( + 5FB915E921D447A400756E3E /* LoginInterfaces.swift */, + 5FDA289121D3199500670060 /* AppDelegate.swift */, + 5FDA289721D3199500670060 /* Main.storyboard */, + 5F65059721D31E6100EEF460 /* OnBoardingController.swift */, + 5FDA289A21D3199700670060 /* Assets.xcassets */, + 5FDA289C21D3199700670060 /* LaunchScreen.storyboard */, + 5FDA289F21D3199700670060 /* Info.plist */, + ); + path = "My Mind"; + sourceTree = ""; + }; + 5FDA28A721D3199700670060 /* My MindTests */ = { + isa = PBXGroup; + children = ( + 5FDA28A821D3199700670060 /* My_MindTests.swift */, + 5FDA28AA21D3199700670060 /* Info.plist */, + ); + path = "My MindTests"; + sourceTree = ""; + }; + 5FDA28B221D3199700670060 /* My MindUITests */ = { + isa = PBXGroup; + children = ( + 5FDA28B321D3199700670060 /* My_MindUITests.swift */, + 5FDA28B521D3199700670060 /* Info.plist */, + ); + path = "My MindUITests"; + sourceTree = ""; + }; + 71AD7FCFD401872222F06230 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 29D9F228DBCF906382669F17 /* Pods_My_Mind.framework */, + F4CD8F77375199A310F844F3 /* Pods_My_MindTests.framework */, + 50DA9DC03A901B75E8E4B3A4 /* Pods_My_MindUITests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + AD0A75B5A0BB6EF6862F0834 /* Pods */ = { + isa = PBXGroup; + children = ( + 1042D1A5D303E942D4AFE1C1 /* Pods-My Mind.debug.xcconfig */, + A7722539AB57A2EBEE52BDF6 /* Pods-My Mind.release.xcconfig */, + 0551EF0922602C8062E5541B /* Pods-My MindTests.debug.xcconfig */, + 523A962748FE07E7626065C8 /* Pods-My MindTests.release.xcconfig */, + DA191761ED3CD7B6B2626140 /* Pods-My MindUITests.debug.xcconfig */, + E703D2ACFC7C1D9097E40E05 /* Pods-My MindUITests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 5FDA288D21D3199500670060 /* My Mind */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5FDA28B821D3199700670060 /* Build configuration list for PBXNativeTarget "My Mind" */; + buildPhases = ( + 2633DBEDBFD6C0700D6749D3 /* [CP] Check Pods Manifest.lock */, + 5FDA288A21D3199500670060 /* Sources */, + 5FDA288B21D3199500670060 /* Frameworks */, + 5FDA288C21D3199500670060 /* Resources */, + CC22E31517B639AD5E6E434B /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "My Mind"; + productName = "My Mind"; + productReference = 5FDA288E21D3199500670060 /* My Mind.app */; + productType = "com.apple.product-type.application"; + }; + 5FDA28A321D3199700670060 /* My MindTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5FDA28BB21D3199700670060 /* Build configuration list for PBXNativeTarget "My MindTests" */; + buildPhases = ( + CE1414E2B13A7E94E867D9F2 /* [CP] Check Pods Manifest.lock */, + 5FDA28A021D3199700670060 /* Sources */, + 5FDA28A121D3199700670060 /* Frameworks */, + 5FDA28A221D3199700670060 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 5FDA28A621D3199700670060 /* PBXTargetDependency */, + ); + name = "My MindTests"; + productName = "My MindTests"; + productReference = 5FDA28A421D3199700670060 /* My MindTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 5FDA28AE21D3199700670060 /* My MindUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5FDA28BE21D3199700670060 /* Build configuration list for PBXNativeTarget "My MindUITests" */; + buildPhases = ( + ACD77EA174E5E770816ACFB8 /* [CP] Check Pods Manifest.lock */, + 5FDA28AB21D3199700670060 /* Sources */, + 5FDA28AC21D3199700670060 /* Frameworks */, + 5FDA28AD21D3199700670060 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 5FDA28B121D3199700670060 /* PBXTargetDependency */, + ); + name = "My MindUITests"; + productName = "My MindUITests"; + productReference = 5FDA28AF21D3199700670060 /* My MindUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 5FDA288621D3199500670060 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1010; + LastUpgradeCheck = 1010; + ORGANIZATIONNAME = "Alexander Davis"; + TargetAttributes = { + 5FDA288D21D3199500670060 = { + CreatedOnToolsVersion = 10.1; + }; + 5FDA28A321D3199700670060 = { + CreatedOnToolsVersion = 10.1; + TestTargetID = 5FDA288D21D3199500670060; + }; + 5FDA28AE21D3199700670060 = { + CreatedOnToolsVersion = 10.1; + TestTargetID = 5FDA288D21D3199500670060; + }; + }; + }; + buildConfigurationList = 5FDA288921D3199500670060 /* Build configuration list for PBXProject "My Mind" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 5FDA288521D3199500670060; + productRefGroup = 5FDA288F21D3199500670060 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 5FDA288D21D3199500670060 /* My Mind */, + 5FDA28A321D3199700670060 /* My MindTests */, + 5FDA28AE21D3199700670060 /* My MindUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 5FDA288C21D3199500670060 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5FDA289E21D3199700670060 /* LaunchScreen.storyboard in Resources */, + 5FDA289B21D3199700670060 /* Assets.xcassets in Resources */, + 5FDA289921D3199500670060 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28A221D3199700670060 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28AD21D3199700670060 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 2633DBEDBFD6C0700D6749D3 /* [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-My Mind-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; + }; + ACD77EA174E5E770816ACFB8 /* [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-My MindUITests-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; + }; + CC22E31517B639AD5E6E434B /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework", + "${BUILT_PRODUCTS_DIR}/GoogleUtilities/GoogleUtilities.framework", + "${BUILT_PRODUCTS_DIR}/Protobuf/Protobuf.framework", + "${BUILT_PRODUCTS_DIR}/SwiftForms/SwiftForms.framework", + "${BUILT_PRODUCTS_DIR}/leveldb-library/leveldb.framework", + "${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + ); + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GTMSessionFetcher.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GoogleUtilities.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Protobuf.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftForms.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/leveldb.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/nanopb.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + CE1414E2B13A7E94E867D9F2 /* [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-My MindTests-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 */ + 5FDA288A21D3199500670060 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5F65059821D31E6100EEF460 /* OnBoardingController.swift in Sources */, + 5FDA289221D3199500670060 /* AppDelegate.swift in Sources */, + 5FB915EA21D447A400756E3E /* LoginInterfaces.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28A021D3199700670060 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5FDA28A921D3199700670060 /* My_MindTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FDA28AB21D3199700670060 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5FDA28B421D3199700670060 /* My_MindUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 5FDA28A621D3199700670060 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 5FDA288D21D3199500670060 /* My Mind */; + targetProxy = 5FDA28A521D3199700670060 /* PBXContainerItemProxy */; + }; + 5FDA28B121D3199700670060 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 5FDA288D21D3199500670060 /* My Mind */; + targetProxy = 5FDA28B021D3199700670060 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 5FDA289721D3199500670060 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 5FDA289821D3199500670060 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 5FDA289C21D3199700670060 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 5FDA289D21D3199700670060 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 5FDA28B621D3199700670060 /* 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; + CODE_SIGN_IDENTITY = "iPhone Developer"; + 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 = 12.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; + }; + 5FDA28B721D3199700670060 /* 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; + CODE_SIGN_IDENTITY = "iPhone Developer"; + 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 = 12.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; + }; + 5FDA28B921D3199700670060 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1042D1A5D303E942D4AFE1C1 /* Pods-My Mind.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My Mind/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-Mind"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + 5FDA28BA21D3199700670060 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A7722539AB57A2EBEE52BDF6 /* Pods-My Mind.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My Mind/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-Mind"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; + 5FDA28BC21D3199700670060 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0551EF0922602C8062E5541B /* Pods-My MindTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My MindTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-MindTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/My Mind.app/My Mind"; + }; + name = Debug; + }; + 5FDA28BD21D3199700670060 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 523A962748FE07E7626065C8 /* Pods-My MindTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My MindTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-MindTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/My Mind.app/My Mind"; + }; + name = Release; + }; + 5FDA28BF21D3199700670060 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DA191761ED3CD7B6B2626140 /* Pods-My MindUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My MindUITests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-MindUITests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "My Mind"; + }; + name = Debug; + }; + 5FDA28C021D3199700670060 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E703D2ACFC7C1D9097E40E05 /* Pods-My MindUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 28CC8SCVUN; + INFOPLIST_FILE = "My MindUITests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "ADCM.My-MindUITests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "My Mind"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 5FDA288921D3199500670060 /* Build configuration list for PBXProject "My Mind" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5FDA28B621D3199700670060 /* Debug */, + 5FDA28B721D3199700670060 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5FDA28B821D3199700670060 /* Build configuration list for PBXNativeTarget "My Mind" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5FDA28B921D3199700670060 /* Debug */, + 5FDA28BA21D3199700670060 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5FDA28BB21D3199700670060 /* Build configuration list for PBXNativeTarget "My MindTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5FDA28BC21D3199700670060 /* Debug */, + 5FDA28BD21D3199700670060 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5FDA28BE21D3199700670060 /* Build configuration list for PBXNativeTarget "My MindUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5FDA28BF21D3199700670060 /* Debug */, + 5FDA28C021D3199700670060 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 5FDA288621D3199500670060 /* Project object */; +} diff --git a/My Mind/My Mind.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/My Mind/My Mind.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..e3a9677 --- /dev/null +++ b/My Mind/My Mind.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/My Mind/My Mind.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/My Mind/My Mind.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/My Mind/My Mind.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/My Mind/My Mind.xcodeproj/project.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate b/My Mind/My Mind.xcodeproj/project.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..285c15e Binary files /dev/null and b/My Mind/My Mind.xcodeproj/project.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/My Mind/My Mind.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist b/My Mind/My Mind.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..0c0e5f9 --- /dev/null +++ b/My Mind/My Mind.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + My Mind.xcscheme_^#shared#^_ + + orderHint + 14 + + + + diff --git a/My Mind/My Mind.xcworkspace/contents.xcworkspacedata b/My Mind/My Mind.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..9c4ab5c --- /dev/null +++ b/My Mind/My Mind.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/My Mind/My Mind.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/My Mind/My Mind.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/My Mind/My Mind.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/My Mind/My Mind.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate b/My Mind/My Mind.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..90da3ce Binary files /dev/null and b/My Mind/My Mind.xcworkspace/xcuserdata/alexanderdavis.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/My Mind/My Mind/.DS_Store b/My Mind/My Mind/.DS_Store new file mode 100644 index 0000000..e383fe4 Binary files /dev/null and b/My Mind/My Mind/.DS_Store differ diff --git a/My Mind/My Mind/AppDelegate.swift b/My Mind/My Mind/AppDelegate.swift new file mode 100644 index 0000000..81643b3 --- /dev/null +++ b/My Mind/My Mind/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// My Mind +// +// Created by Alexander Davis on 26/12/2018. +// Copyright © 2018 Alexander Davis. 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 + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Contents.json b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100755 index 0000000..c0b8464 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,157 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "filename" : "Icon-App-57x57@1x.png", + "scale" : "1x" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "filename" : "Icon-App-57x57@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "50x50", + "idiom" : "ipad", + "filename" : "Icon-Small-50x50@1x.png", + "scale" : "1x" + }, + { + "size" : "50x50", + "idiom" : "ipad", + "filename" : "Icon-Small-50x50@2x.png", + "scale" : "2x" + }, + { + "size" : "72x72", + "idiom" : "ipad", + "filename" : "Icon-App-72x72@1x.png", + "scale" : "1x" + }, + { + "size" : "72x72", + "idiom" : "ipad", + "filename" : "Icon-App-72x72@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100755 index 0000000..cb8c8dd Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100755 index 0000000..31a69a7 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100755 index 0000000..50bb01a Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100755 index 0000000..bdd7215 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100755 index 0000000..0f63d35 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100755 index 0000000..3ffb1d1 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100755 index 0000000..31a69a7 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100755 index 0000000..5f25168 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100755 index 0000000..5ccf3e8 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100755 index 0000000..8bf9ff2 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100755 index 0000000..290e064 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100755 index 0000000..5ccf3e8 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100755 index 0000000..2bd6152 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100755 index 0000000..f994c63 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100755 index 0000000..abe476f Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100755 index 0000000..ce5c7a6 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100755 index 0000000..49def24 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100755 index 0000000..e88b914 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@1x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@1x.png new file mode 100755 index 0000000..ce98871 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@2x.png b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@2x.png new file mode 100755 index 0000000..0833776 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/AppIcon.appiconset/Icon-Small-50x50@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Clock-50 (1).png b/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Clock-50 (1).png new file mode 100755 index 0000000..f1f9815 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Clock-50 (1).png differ diff --git a/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Contents.json new file mode 100755 index 0000000..9a52731 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Appointments.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Clock-50 (1).png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/Back.imageset/Back-50.png b/My Mind/My Mind/Assets.xcassets/Back.imageset/Back-50.png new file mode 100755 index 0000000..8bbd5ac Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Back.imageset/Back-50.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Back.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/Back.imageset/Contents.json new file mode 100755 index 0000000..09843e3 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Back.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Back-50.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/Contents.json b/My Mind/My Mind/Assets.xcassets/Contents.json new file mode 100755 index 0000000..da4a164 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/Contents.json new file mode 100755 index 0000000..371a6fd --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "graph150.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "graph300.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "graph450.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph150.png b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph150.png new file mode 100755 index 0000000..8768745 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph150.png differ diff --git a/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph300.png b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph300.png new file mode 100755 index 0000000..f521319 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph300.png differ diff --git a/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph450.png b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph450.png new file mode 100755 index 0000000..a504e40 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/CustomEvent.imageset/graph450.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Engage.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Contents.json new file mode 100755 index 0000000..6a1e4d7 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Engage50.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "Engage100.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "Engage150.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage100.png b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage100.png new file mode 100755 index 0000000..8003ffe Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage100.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage150.png b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage150.png new file mode 100755 index 0000000..2ab5485 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage150.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage50.png b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage50.png new file mode 100755 index 0000000..5bc1b1a Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Engage.imageset/Engage50.png differ diff --git a/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/Contents.json new file mode 100755 index 0000000..b909232 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "engage30.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "engage60.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "engage90.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage30.png b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage30.png new file mode 100755 index 0000000..b0047fe Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage30.png differ diff --git a/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage60.png b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage60.png new file mode 100755 index 0000000..27229ce Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage60.png differ diff --git a/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage90.png b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage90.png new file mode 100755 index 0000000..4be52b0 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/EngageSmall.imageset/engage90.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Forum.imageset/Brief-50 (1).png b/My Mind/My Mind/Assets.xcassets/Forum.imageset/Brief-50 (1).png new file mode 100755 index 0000000..503cb19 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Forum.imageset/Brief-50 (1).png differ diff --git a/My Mind/My Mind/Assets.xcassets/Forum.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/Forum.imageset/Contents.json new file mode 100755 index 0000000..770d22e --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Forum.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Brief-50 (1).png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/Contents.json new file mode 100755 index 0000000..81cee8d --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "money150.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "money300.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "money450.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money150.png b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money150.png new file mode 100755 index 0000000..b8274a6 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money150.png differ diff --git a/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money300.png b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money300.png new file mode 100755 index 0000000..9041f45 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money300.png differ diff --git a/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money450.png b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money450.png new file mode 100755 index 0000000..2f04699 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/MonetizationEvent.imageset/money450.png differ diff --git a/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Contents.json new file mode 100755 index 0000000..b196cf0 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "Create New-50 (1).png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Create New-50 (1).png b/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Create New-50 (1).png new file mode 100755 index 0000000..ed8ac64 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/Referrals.imageset/Create New-50 (1).png differ diff --git a/My Mind/My Mind/Assets.xcassets/first.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/first.imageset/Contents.json new file mode 100755 index 0000000..33a7451 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/first.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "first.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/first.imageset/first.pdf b/My Mind/My Mind/Assets.xcassets/first.imageset/first.pdf new file mode 100755 index 0000000..47d911d Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/first.imageset/first.pdf differ diff --git a/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/Contents.json new file mode 100755 index 0000000..43003d0 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "iTunesArtwork@1x.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "iTunesArtwork@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "iTunesArtwork@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@1x.png b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@1x.png new file mode 100755 index 0000000..5bb8a72 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@1x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@2x.png b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@2x.png new file mode 100755 index 0000000..17c0cb6 Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@2x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@3x.png b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@3x.png new file mode 100755 index 0000000..510b9df Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/iTunesArtwork.imageset/iTunesArtwork@3x.png differ diff --git a/My Mind/My Mind/Assets.xcassets/second.imageset/Contents.json b/My Mind/My Mind/Assets.xcassets/second.imageset/Contents.json new file mode 100755 index 0000000..03bd9c9 --- /dev/null +++ b/My Mind/My Mind/Assets.xcassets/second.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "second.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/My Mind/My Mind/Assets.xcassets/second.imageset/second.pdf b/My Mind/My Mind/Assets.xcassets/second.imageset/second.pdf new file mode 100755 index 0000000..401614e Binary files /dev/null and b/My Mind/My Mind/Assets.xcassets/second.imageset/second.pdf differ diff --git a/My Mind/My Mind/Base.lproj/LaunchScreen.storyboard b/My Mind/My Mind/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f935c5a --- /dev/null +++ b/My Mind/My Mind/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/My Mind/Base.lproj/Main.storyboard b/My Mind/My Mind/Base.lproj/Main.storyboard new file mode 100644 index 0000000..d6f094a --- /dev/null +++ b/My Mind/My Mind/Base.lproj/Main.storyboard @@ -0,0 +1,639 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/My Mind/Info.plist b/My Mind/My Mind/Info.plist new file mode 100644 index 0000000..a316d6e --- /dev/null +++ b/My Mind/My Mind/Info.plist @@ -0,0 +1,58 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 2.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UIStatusBarStyle + UIStatusBarStyleLightContent + UIStatusBarTintParameters + + UINavigationBar + + Style + UIBarStyleDefault + Translucent + + + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + UIInterfaceOrientationPortraitUpsideDown + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/My Mind/My Mind/LoginInterfaces.swift b/My Mind/My Mind/LoginInterfaces.swift new file mode 100644 index 0000000..dff057c --- /dev/null +++ b/My Mind/My Mind/LoginInterfaces.swift @@ -0,0 +1,167 @@ +// +// LoginInterfaces.swift +// +// +// Created by Alexander Davis on 26/12/2018. +// + +import Foundation +import UIKit +import Firebase +import FirebaseAuth + +class LoginView: UIViewController { + + @IBOutlet weak var Emailtbx: UITextField! + @IBOutlet weak var Passwordtbx: UITextField! + @IBAction func Loginbtn(_ sender: UIButton) { + if self.Emailtbx.text == "" || self.Passwordtbx.text == "" { + + //Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in + + let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert) + + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + + } else { + + FIRAuth.auth()?.signIn(withEmail: self.Emailtbx.text!, password: self.Passwordtbx.text!) { (user, error) in + + if error == nil { + + //Print into the console if successfully logged in + print("You have successfully logged in") + + //Go to the MainController if the login is sucessful + let alertController = UIAlertController(title: "Welcome", message: "You have successfully logged in", preferredStyle: .alert) + let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainController") + let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in self.present(vc!, animated: true, completion: nil);}) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + + } else { + + //Tells the user that there is an error and then gets firebase to tell them the error + let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) + + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + } + } + } + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } +} + +class SignUp : UIViewController { + + @IBOutlet weak var Emailtbx: UITextField! + @IBOutlet weak var Passwordtbx: UITextField! + @IBAction func createAccountbtn(_ sender: UIButton) { + if Emailtbx.text == "" { + let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert) + + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) + alertController.addAction(defaultAction) + + present(alertController, animated: true, completion: nil) + + } else { + FIRAuth.auth()?.createUser(withEmail: Emailtbx.text!, password: Passwordtbx.text!) { (user, error) in + + if error == nil { + let alertController = UIAlertController(title: "Sign Up Complete", message: "You have Successfully Signed Up", preferredStyle: .alert) + let vc = self.storyboard?.instantiateViewController(withIdentifier: "Login") + let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in self.present(vc!, animated: true, completion: nil);}) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + + } else { + let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) + + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + } + } + } + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } +} + +class ForgotPass : UIViewController { + + @IBOutlet weak var Emailtbx: UITextField! + @IBAction func Resetbtn(_ sender: UIButton) { + if self.Emailtbx.text == "" { + let alertController = UIAlertController(title: "Oops!", message: "Please enter an email.", preferredStyle: .alert) + + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) + alertController.addAction(defaultAction) + + present(alertController, animated: true, completion: nil) + + } else { + FIRAuth.auth()?.sendPasswordReset(withEmail: self.Emailtbx.text!, completion: { (error) in + + var title = "" + var message = "" + + if error != nil { + title = "Error!" + message = (error?.localizedDescription)! + } else { + title = "Success!" + message = "Password reset email sent." + self.Emailtbx.text = "" + } + + let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) + + let vc = self.storyboard?.instantiateViewController(withIdentifier: "Login") + let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: { action in self.present(vc!, animated: true, completion: nil);}) + alertController.addAction(defaultAction) + + self.present(alertController, animated: true, completion: nil) + }) + } + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } +} + +class Logout : UIViewController { + + @IBAction func Logoutbtn(_ sender: UIButton) { + if FIRAuth.auth()?.currentUser != nil { + do { + try FIRAuth.auth()?.signOut() + let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OnBoard") + present(vc, animated: true, completion: nil) + + } catch let error as NSError { + print(error.localizedDescription) + } + } + } + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } +} diff --git a/My Mind/My Mind/OnBoardingController.swift b/My Mind/My Mind/OnBoardingController.swift new file mode 100644 index 0000000..d6234cd --- /dev/null +++ b/My Mind/My Mind/OnBoardingController.swift @@ -0,0 +1,107 @@ +// +// OnBoardingController.swift +// My Mind +// +// Created by Alexander Davis on 26/12/2018. +// Copyright © 2018 Alexander Davis. All rights reserved. +// + +import Foundation +import UIKit + +class OnBoardingController : UIPageViewController { + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } + + override func viewDidLoad() { + // Set the dataSource and delegate in code. + // I can't figure out how to do this in the Storyboard! + dataSource = self + delegate = self + // This is the starting point. Start with step zero. + setViewControllers([getPageOne()], direction: .forward, animated: false, completion: nil) + } + + func getPageOne() -> PageOne { + return storyboard!.instantiateViewController(withIdentifier: "PageOne") as! PageOne + } + + func getPageTwo() -> PageTwo { + return storyboard!.instantiateViewController(withIdentifier: "PageTwo") as! PageTwo + } + + func getPageThree() -> PageThree { + return storyboard!.instantiateViewController(withIdentifier: "PageThree") as! PageThree + } + +} + +// MARK: - UIPageViewControllerDataSource methods + +extension OnBoardingController : UIPageViewControllerDataSource { + + func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { + if viewController.isKind(of: PageTwo.self) { + // 2 -> 1 + return getPageTwo() + } else if viewController.isKind(of: PageTwo.self) { + // 1 -> 0 + return getPageOne() + } else { + // 0 -> end of the road + return nil + } + } + + func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { + if viewController.isKind(of: PageOne.self) { + // 0 -> 1 + return getPageTwo() + } else if viewController.isKind(of: PageTwo.self) { + // 1 -> 2 + return getPageThree() + } else { + // 2 -> end of the road + return nil + } + } + + + // This only gets called once, when setViewControllers is called + func presentationIndex(for pageViewController: UIPageViewController) -> Int { + return 0 + } + +} + +// MARK: - UIPageViewControllerDelegate methods + +extension OnBoardingController : UIPageViewControllerDelegate { + +} + +class PageOne : UIViewController { + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } + +} + +class PageTwo : UIViewController { + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } + +} + +class PageThree : UIViewController { + + override var preferredStatusBarStyle: UIStatusBarStyle { + return .lightContent + } + +} diff --git a/My Mind/My MindTests/Info.plist b/My Mind/My MindTests/Info.plist new file mode 100644 index 0000000..6c40a6c --- /dev/null +++ b/My Mind/My MindTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/My Mind/My MindTests/My_MindTests.swift b/My Mind/My MindTests/My_MindTests.swift new file mode 100644 index 0000000..7f1388b --- /dev/null +++ b/My Mind/My MindTests/My_MindTests.swift @@ -0,0 +1,34 @@ +// +// My_MindTests.swift +// My MindTests +// +// Created by Alexander Davis on 26/12/2018. +// Copyright © 2018 Alexander Davis. All rights reserved. +// + +import XCTest +@testable import My_Mind + +class My_MindTests: XCTestCase { + + override func setUp() { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/My Mind/My MindUITests/Info.plist b/My Mind/My MindUITests/Info.plist new file mode 100644 index 0000000..6c40a6c --- /dev/null +++ b/My Mind/My MindUITests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/My Mind/My MindUITests/My_MindUITests.swift b/My Mind/My MindUITests/My_MindUITests.swift new file mode 100644 index 0000000..1f8e03a --- /dev/null +++ b/My Mind/My MindUITests/My_MindUITests.swift @@ -0,0 +1,34 @@ +// +// My_MindUITests.swift +// My MindUITests +// +// Created by Alexander Davis on 26/12/2018. +// Copyright © 2018 Alexander Davis. All rights reserved. +// + +import XCTest + +class My_MindUITests: XCTestCase { + + override func setUp() { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + XCUIApplication().launch() + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() { + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + +} diff --git a/My Mind/Podfile b/My Mind/Podfile new file mode 100644 index 0000000..269d935 --- /dev/null +++ b/My Mind/Podfile @@ -0,0 +1,31 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'My Mind' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + + # Pods for My Mind + source 'https://github.com/CocoaPods/Specs.git' + platform :ios, '12.1' + use_frameworks! + + pod 'SwiftForms' + pod 'Firebase/Core' + pod 'Firebase/Auth' + pod 'Firebase/Messaging' + pod 'Firebase/Database' + pod 'Firebase/Storage' + + + target 'My MindTests' do + inherit! :search_paths + # Pods for testing + end + + target 'My MindUITests' do + inherit! :search_paths + # Pods for testing + end + +end diff --git a/My Mind/Podfile.lock b/My Mind/Podfile.lock new file mode 100644 index 0000000..4a9fc77 --- /dev/null +++ b/My Mind/Podfile.lock @@ -0,0 +1,139 @@ +PODS: + - Firebase/Auth (5.15.0): + - Firebase/CoreOnly + - FirebaseAuth (= 5.2.0) + - Firebase/Core (5.15.0): + - Firebase/CoreOnly + - FirebaseAnalytics (= 5.4.0) + - Firebase/CoreOnly (5.15.0): + - FirebaseCore (= 5.1.10) + - Firebase/Database (5.15.0): + - Firebase/CoreOnly + - FirebaseDatabase (= 5.0.4) + - Firebase/Messaging (5.15.0): + - Firebase/CoreOnly + - FirebaseMessaging (= 3.2.2) + - Firebase/Storage (5.15.0): + - Firebase/CoreOnly + - FirebaseStorage (= 3.0.3) + - FirebaseAnalytics (5.4.0): + - FirebaseCore (~> 5.1) + - FirebaseInstanceID (~> 3.3) + - GoogleAppMeasurement (= 5.4.0) + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - FirebaseAnalyticsInterop (1.1.0) + - FirebaseAuth (5.2.0): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - GoogleUtilities/Environment (~> 5.2) + - GTMSessionFetcher/Core (~> 1.1) + - FirebaseAuthInterop (1.0.0) + - FirebaseCore (5.1.10): + - GoogleUtilities/Logger (~> 5.2) + - FirebaseDatabase (5.0.4): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - leveldb-library (~> 1.18) + - FirebaseInstanceID (3.3.0): + - FirebaseCore (~> 5.1) + - GoogleUtilities/Environment (~> 5.3) + - GoogleUtilities/UserDefaults (~> 5.3) + - FirebaseMessaging (3.2.2): + - FirebaseAnalyticsInterop (~> 1.1) + - FirebaseCore (~> 5.1) + - FirebaseInstanceID (~> 3.0) + - GoogleUtilities/Environment (~> 5.2) + - GoogleUtilities/Reachability (~> 5.2) + - Protobuf (~> 3.1) + - FirebaseStorage (3.0.3): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - GTMSessionFetcher/Core (~> 1.1) + - GoogleAppMeasurement (5.4.0): + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - GoogleUtilities/AppDelegateSwizzler (5.3.6): + - GoogleUtilities/Environment + - GoogleUtilities/Logger + - GoogleUtilities/Network + - GoogleUtilities/Environment (5.3.6) + - GoogleUtilities/Logger (5.3.6): + - GoogleUtilities/Environment + - GoogleUtilities/MethodSwizzler (5.3.6): + - GoogleUtilities/Logger + - GoogleUtilities/Network (5.3.6): + - GoogleUtilities/Logger + - "GoogleUtilities/NSData+zlib" + - GoogleUtilities/Reachability + - "GoogleUtilities/NSData+zlib (5.3.6)" + - GoogleUtilities/Reachability (5.3.6): + - GoogleUtilities/Logger + - GoogleUtilities/UserDefaults (5.3.6): + - GoogleUtilities/Logger + - GTMSessionFetcher/Core (1.2.1) + - leveldb-library (1.20) + - nanopb (0.3.901): + - nanopb/decode (= 0.3.901) + - nanopb/encode (= 0.3.901) + - nanopb/decode (0.3.901) + - nanopb/encode (0.3.901) + - Protobuf (3.6.1) + - SwiftForms (1.8.2) + +DEPENDENCIES: + - Firebase/Auth + - Firebase/Core + - Firebase/Database + - Firebase/Messaging + - Firebase/Storage + - SwiftForms + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Firebase + - FirebaseAnalytics + - FirebaseAnalyticsInterop + - FirebaseAuth + - FirebaseAuthInterop + - FirebaseCore + - FirebaseDatabase + - FirebaseInstanceID + - FirebaseMessaging + - FirebaseStorage + - GoogleAppMeasurement + - GoogleUtilities + - GTMSessionFetcher + - leveldb-library + - nanopb + - Protobuf + - SwiftForms + +SPEC CHECKSUMS: + Firebase: 8bb9268bff82374f2cbaaabb143e725743c316ae + FirebaseAnalytics: c06f9d70577d79074214700a71fd5d39de5550fb + FirebaseAnalyticsInterop: e5f21be9af6548372e2f0815834ff909bff395a2 + FirebaseAuth: 02e969ff430e156d99d4cb842d77b806b71ad7bb + FirebaseAuthInterop: 0ffa57668be100582bb7643d4fcb7615496c41fc + FirebaseCore: 35747502d9e8c6ee217385ad04446c7c2aaf9c5c + FirebaseDatabase: 0621689f77528d62b47e1c06ca737c4c19275d1a + FirebaseInstanceID: e2fa4cb35ef5558c200f7f0ad8a53e212215f93e + FirebaseMessaging: b412996f6a09337d232bb3a6676ce4d1f353d024 + FirebaseStorage: 3d22c041370593e639fba013d1eb698a8dae2881 + GoogleAppMeasurement: 98b71f5e04142793729a5ef23e5b96651ff4b70f + GoogleUtilities: 95996bea7c7d9b8fb811b7507669a4a8762f80c7 + GTMSessionFetcher: 32aeca0aa144acea523e1c8e053089dec2cb98ca + leveldb-library: 08cba283675b7ed2d99629a4bc5fd052cd2bb6a5 + nanopb: 2901f78ea1b7b4015c860c2fdd1ea2fee1a18d48 + Protobuf: 1eb9700044745f00181c136ef21b8ff3ad5a0fd5 + SwiftForms: f0d4d30401e21de87d9b7b63a4691a3d4e22bab5 + +PODFILE CHECKSUM: 78cec12473e63e23a4acf6cbc3ba860b858ca314 + +COCOAPODS: 1.5.3 diff --git a/My Mind/Pods/Firebase/CoreOnly/Sources/Firebase.h b/My Mind/Pods/Firebase/CoreOnly/Sources/Firebase.h new file mode 100755 index 0000000..6461547 --- /dev/null +++ b/My Mind/Pods/Firebase/CoreOnly/Sources/Firebase.h @@ -0,0 +1,105 @@ +#import + +#if !defined(__has_include) + #error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \ + import the headers individually." +#else + #if __has_include() + #import + #else + #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING + #warning "FirebaseAnalytics.framework is not included in your target. Please add \ +`Firebase/Core` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \ +Firebase services work as intended." + #endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + + #if __has_include() + #import + #endif + +#endif // defined(__has_include) diff --git a/My Mind/Pods/Firebase/CoreOnly/Sources/module.modulemap b/My Mind/Pods/Firebase/CoreOnly/Sources/module.modulemap new file mode 100755 index 0000000..3685b54 --- /dev/null +++ b/My Mind/Pods/Firebase/CoreOnly/Sources/module.modulemap @@ -0,0 +1,4 @@ +module Firebase { + export * + header "Firebase.h" +} \ No newline at end of file diff --git a/My Mind/Pods/Firebase/README.md b/My Mind/Pods/Firebase/README.md new file mode 100755 index 0000000..49aa2ee --- /dev/null +++ b/My Mind/Pods/Firebase/README.md @@ -0,0 +1,87 @@ +# Firebase APIs for iOS + +Simplify your iOS development, grow your user base, and monetize more +effectively with Firebase services. + +Much more information can be found at [https://firebase.google.com](https://firebase.google.com). + +## Install a Firebase SDK using CocoaPods + +Firebase distributes several iOS specific APIs and SDKs via CocoaPods. +You can install the CocoaPods tool on OS X by running the following command from +the terminal. Detailed information is available in the [Getting Started +guide](https://guides.cocoapods.org/using/getting-started.html#getting-started). + +``` +$ sudo gem install cocoapods +``` + +## Try out an SDK + +You can try any of the SDKs with `pod try`. Run the following command and select +the SDK you are interested in when prompted: + +``` +$ pod try Firebase +``` + +Note that some SDKs may require credentials. More information is available in +the SDK-specific documentation at [https://firebase.google.com/docs/](https://firebase.google.com/docs/). + +## Add a Firebase SDK to your iOS app + +CocoaPods is used to install and manage dependencies in existing Xcode projects. + +1. Create an Xcode project, and save it to your local machine. +2. Create a file named `Podfile` in your project directory. This file defines + your project's dependencies, and is commonly referred to as a Podspec. +3. Open `Podfile`, and add your dependencies. A simple Podspec is shown here: + + ``` + platform :ios, '8.0' + pod 'Firebase' + ``` + +4. Save the file. + +5. Open a terminal and `cd` to the directory containing the Podfile. + + ``` + $ cd /project/ + ``` + +6. Run the `pod install` command. This will install the SDKs specified in the + Podspec, along with any dependencies they may have. + + ``` + $ pod install + ``` + +7. Open your app's `.xcworkspace` file to launch Xcode. Use this file for all + development on your app. + +8. You can also install other Firebase SDKs by adding the subspecs in the + Podfile. + + ``` + pod 'Firebase/AdMob' + pod 'Firebase/Analytics' + pod 'Firebase/Auth' + pod 'Firebase/Crash' + pod 'Firebase/Database' + pod 'Firebase/DynamicLinks' + pod 'Firebase/Firestore' + pod 'Firebase/Functions' + pod 'Firebase/Invites' + pod 'Firebase/Messaging' + pod 'Firebase/MLCommon' + pod 'Firebase/MLModelInterpreter' + pod 'Firebase/MLVision' + pod 'Firebase/MLVisionBarcodeModel' + pod 'Firebase/MLVisionFaceModel' + pod 'Firebase/MLVisionLabelModel' + pod 'Firebase/MLVisionTextModel' + pod 'Firebase/Performance' + pod 'Firebase/RemoteConfig' + pod 'Firebase/Storage' + ``` diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector b/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector new file mode 100755 index 0000000..f1cf59a Binary files /dev/null and b/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/FIRAnalyticsConnector differ diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap b/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap new file mode 100755 index 0000000..73fb1d7 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FIRAnalyticsConnector.framework/Modules/module.modulemap @@ -0,0 +1,5 @@ +framework module FIRAnalyticsConnector { + export * + module * { export *} + link framework "Security" + link framework "SystemConfiguration"} diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics new file mode 100755 index 0000000..fed9cbd Binary files /dev/null and b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics differ diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h new file mode 100755 index 0000000..d499af6 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h @@ -0,0 +1,62 @@ +#import + +#import "FIRAnalytics.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Provides App Delegate handlers to be used in your App Delegate. + * + * To save time integrating Firebase Analytics in an application, Firebase Analytics does not + * require delegation implementation from the AppDelegate. Instead this is automatically done by + * Firebase Analytics. Should you choose instead to delegate manually, you can turn off the App + * Delegate Proxy by adding FirebaseAppDelegateProxyEnabled into your app's Info.plist and setting + * it to NO, and adding the methods in this category to corresponding delegation handlers. + * + * To handle Universal Links, you must return YES in + * [UIApplicationDelegate application:didFinishLaunchingWithOptions:]. + */ +@interface FIRAnalytics (AppDelegate) + +/** + * Handles events related to a URL session that are waiting to be processed. + * + * For optimal use of Firebase Analytics, call this method from the + * [UIApplicationDelegate application:handleEventsForBackgroundURLSession:completionHandler] + * method of the app delegate in your app. + * + * @param identifier The identifier of the URL session requiring attention. + * @param completionHandler The completion handler to call when you finish processing the events. + * Calling this completion handler lets the system know that your app's user interface is + * updated and a new snapshot can be taken. + */ ++ (void)handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(nullable void (^)(void))completionHandler; + +/** + * Handles the event when the app is launched by a URL. + * + * Call this method from [UIApplicationDelegate application:openURL:options:] (on iOS 9.0 and + * above), or [UIApplicationDelegate application:openURL:sourceApplication:annotation:] (on + * iOS 8.x and below) in your app. + * + * @param url The URL resource to open. This resource can be a network resource or a file. + */ ++ (void)handleOpenURL:(NSURL *)url; + +/** + * Handles the event when the app receives data associated with user activity that includes a + * Universal Link (on iOS 9.0 and above). + * + * Call this method from [UIApplication continueUserActivity:restorationHandler:] in your app + * delegate (on iOS 9.0 and above). + * + * @param userActivity The activity object containing the data associated with the task the user + * was performing. + */ ++ (void)handleUserActivity:(id)userActivity; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h new file mode 100755 index 0000000..39d23f1 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h @@ -0,0 +1,119 @@ +#import + +#import "FIREventNames.h" +#import "FIRParameterNames.h" +#import "FIRUserPropertyNames.h" + +NS_ASSUME_NONNULL_BEGIN + +/// The top level Firebase Analytics singleton that provides methods for logging events and setting +/// user properties. See the developer guides for general +/// information on using Firebase Analytics in your apps. +NS_SWIFT_NAME(Analytics) +@interface FIRAnalytics : NSObject + +/// Logs an app event. The event can have up to 25 parameters. Events with the same name must have +/// the same parameters. Up to 500 event names are supported. Using predefined events and/or +/// parameters is recommended for optimal reporting. +/// +/// The following event names are reserved and cannot be used: +///
    +///
  • ad_activeview
  • +///
  • ad_click
  • +///
  • ad_exposure
  • +///
  • ad_impression
  • +///
  • ad_query
  • +///
  • adunit_exposure
  • +///
  • app_clear_data
  • +///
  • app_remove
  • +///
  • app_update
  • +///
  • error
  • +///
  • first_open
  • +///
  • in_app_purchase
  • +///
  • notification_dismiss
  • +///
  • notification_foreground
  • +///
  • notification_open
  • +///
  • notification_receive
  • +///
  • os_update
  • +///
  • screen_view
  • +///
  • session_start
  • +///
  • user_engagement
  • +///
+/// +/// @param name The name of the event. Should contain 1 to 40 alphanumeric characters or +/// underscores. The name must start with an alphabetic character. Some event names are +/// reserved. See FIREventNames.h for the list of reserved event names. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used. Note that event names are +/// case-sensitive and that logging two events whose names differ only in case will result in +/// two distinct events. +/// @param parameters The dictionary of event parameters. Passing nil indicates that the event has +/// no parameters. Parameter names can be up to 40 characters long and must start with an +/// alphabetic character and contain only alphanumeric characters and underscores. Only NSString +/// and NSNumber (signed 64-bit integer and 64-bit floating-point number) parameter types are +/// supported. NSString parameter values can be up to 100 characters long. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used for parameter names. ++ (void)logEventWithName:(NSString *)name + parameters:(nullable NSDictionary *)parameters + NS_SWIFT_NAME(logEvent(_:parameters:)); + +/// Sets a user property to a given value. Up to 25 user property names are supported. Once set, +/// user property values persist throughout the app lifecycle and across sessions. +/// +/// The following user property names are reserved and cannot be used: +///
    +///
  • first_open_time
  • +///
  • last_deep_link_referrer
  • +///
  • user_id
  • +///
+/// +/// @param value The value of the user property. Values can be up to 36 characters long. Setting the +/// value to nil removes the user property. +/// @param name The name of the user property to set. Should contain 1 to 24 alphanumeric characters +/// or underscores and must start with an alphabetic character. The "firebase_", "google_", and +/// "ga_" prefixes are reserved and should not be used for user property names. ++ (void)setUserPropertyString:(nullable NSString *)value forName:(NSString *)name + NS_SWIFT_NAME(setUserProperty(_:forName:)); + +/// Sets the user ID property. This feature must be used in accordance with +/// Google's Privacy Policy +/// +/// @param userID The user ID to ascribe to the user of this app on this device, which must be +/// non-empty and no more than 256 characters long. Setting userID to nil removes the user ID. ++ (void)setUserID:(nullable NSString *)userID; + +/// Sets the current screen name, which specifies the current visual context in your app. This helps +/// identify the areas in your app where users spend their time and how they interact with your app. +/// Must be called on the main thread. +/// +/// Note that screen reporting is enabled automatically and records the class name of the current +/// UIViewController for you without requiring you to call this method. If you implement +/// viewDidAppear in your UIViewController but do not call [super viewDidAppear:], that screen class +/// will not be automatically tracked. The class name can optionally be overridden by calling this +/// method in the viewDidAppear callback of your UIViewController and specifying the +/// screenClassOverride parameter. setScreenName:screenClass: must be called after +/// [super viewDidAppear:]. +/// +/// If your app does not use a distinct UIViewController for each screen, you should call this +/// method and specify a distinct screenName each time a new screen is presented to the user. +/// +/// The screen name and screen class remain in effect until the current UIViewController changes or +/// a new call to setScreenName:screenClass: is made. +/// +/// @param screenName The name of the current screen. Should contain 1 to 100 characters. Set to nil +/// to clear the current screen name. +/// @param screenClassOverride The name of the screen class. Should contain 1 to 100 characters. By +/// default this is the class name of the current UIViewController. Set to nil to revert to the +/// default class name. ++ (void)setScreenName:(nullable NSString *)screenName + screenClass:(nullable NSString *)screenClassOverride; + +/// The unique ID for this instance of the application. ++ (NSString *)appInstanceID; + +/// Clears all analytics data for this instance from the device and resets the app instance ID. +/// FIRAnalyticsConfiguration values will be reset to the default values. ++ (void)resetAnalyticsData; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h new file mode 100755 index 0000000..c70c53e --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h @@ -0,0 +1,407 @@ +/// @file FIREventNames.h +/// +/// Predefined event names. +/// +/// An Event is an important occurrence in your app that you want to measure. You can report up to +/// 500 different types of Events per app and you can associate up to 25 unique parameters with each +/// Event type. Some common events are suggested below, but you may also choose to specify custom +/// Event types that are associated with your specific app. Each event type is identified by a +/// unique name. Event names can be up to 40 characters long, may only contain alphanumeric +/// characters and underscores ("_"), and must start with an alphabetic character. The "firebase_", +/// "google_", and "ga_" prefixes are reserved and should not be used. + +#import + +/// Add Payment Info event. This event signifies that a user has submitted their payment information +/// to your app. +static NSString *const kFIREventAddPaymentInfo NS_SWIFT_NAME(AnalyticsEventAddPaymentInfo) = + @"add_payment_info"; + +/// E-Commerce Add To Cart event. This event signifies that an item was added to a cart for +/// purchase. Add this event to a funnel with kFIREventEcommercePurchase to gauge the effectiveness +/// of your checkout process. Note: If you supply the @c kFIRParameterValue parameter, you must +/// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
+static NSString *const kFIREventAddToCart NS_SWIFT_NAME(AnalyticsEventAddToCart) = @"add_to_cart"; + +/// E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. +/// Use this event to identify popular gift items in your app. Note: If you supply the +/// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventAddToWishlist NS_SWIFT_NAME(AnalyticsEventAddToWishlist) = + @"add_to_wishlist"; + +/// App Open event. By logging this event when an App becomes active, developers can understand how +/// often users leave and return during the course of a Session. Although Sessions are automatically +/// reported, this event can provide further clarification around the continuous engagement of +/// app-users. +static NSString *const kFIREventAppOpen NS_SWIFT_NAME(AnalyticsEventAppOpen) = @"app_open"; + +/// E-Commerce Begin Checkout event. This event signifies that a user has begun the process of +/// checking out. Add this event to a funnel with your kFIREventEcommercePurchase event to gauge the +/// effectiveness of your checkout process. Note: If you supply the @c kFIRParameterValue +/// parameter, you must also supply the @c kFIRParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventBeginCheckout NS_SWIFT_NAME(AnalyticsEventBeginCheckout) = + @"begin_checkout"; + +/// Campaign Detail event. Log this event to supply the referral details of a re-engagement +/// campaign. Note: you must supply at least one of the required parameters kFIRParameterSource, +/// kFIRParameterMedium or kFIRParameterCampaign. Params: +/// +///
    +///
  • @c kFIRParameterSource (NSString)
  • +///
  • @c kFIRParameterMedium (NSString)
  • +///
  • @c kFIRParameterCampaign (NSString)
  • +///
  • @c kFIRParameterTerm (NSString) (optional)
  • +///
  • @c kFIRParameterContent (NSString) (optional)
  • +///
  • @c kFIRParameterAdNetworkClickID (NSString) (optional)
  • +///
  • @c kFIRParameterCP1 (NSString) (optional)
  • +///
+static NSString *const kFIREventCampaignDetails NS_SWIFT_NAME(AnalyticsEventCampaignDetails) = + @"campaign_details"; + +/// Checkout progress. Params: +/// +///
    +///
  • @c kFIRParameterCheckoutStep (unsigned 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCheckoutOption (NSString) (optional)
  • +///
+static NSString *const kFIREventCheckoutProgress NS_SWIFT_NAME(AnalyticsEventCheckoutProgress) = + @"checkout_progress"; + +/// Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log +/// this along with @c kFIREventSpendVirtualCurrency to better understand your virtual economy. +/// Params: +/// +///
    +///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • +///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • +///
+static NSString *const kFIREventEarnVirtualCurrency + NS_SWIFT_NAME(AnalyticsEventEarnVirtualCurrency) = @"earn_virtual_currency"; + +/// E-Commerce Purchase event. This event signifies that an item was purchased by a user. Note: +/// This is different from the in-app purchase event, which is reported automatically for App +/// Store-based apps. Note: If you supply the @c kFIRParameterValue parameter, you must also +/// supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
  • @c kFIRParameterTax (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterShipping (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCoupon (NSString) (optional)
  • +///
  • @c kFIRParameterLocation (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventEcommercePurchase NS_SWIFT_NAME(AnalyticsEventEcommercePurchase) = + @"ecommerce_purchase"; + +/// Generate Lead event. Log this event when a lead has been generated in the app to understand the +/// efficacy of your install and re-engagement campaigns. Note: If you supply the +/// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventGenerateLead NS_SWIFT_NAME(AnalyticsEventGenerateLead) = + @"generate_lead"; + +/// Join Group event. Log this event when a user joins a group such as a guild, team or family. Use +/// this event to analyze how popular certain groups or social features are in your app. Params: +/// +///
    +///
  • @c kFIRParameterGroupID (NSString)
  • +///
+static NSString *const kFIREventJoinGroup NS_SWIFT_NAME(AnalyticsEventJoinGroup) = @"join_group"; + +/// Level Up event. This event signifies that a player has leveled up in your gaming app. It can +/// help you gauge the level distribution of your userbase and help you identify certain levels that +/// are difficult to pass. Params: +/// +///
    +///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCharacter (NSString) (optional)
  • +///
+static NSString *const kFIREventLevelUp NS_SWIFT_NAME(AnalyticsEventLevelUp) = @"level_up"; + +/// Login event. Apps with a login feature can report this event to signify that a user has logged +/// in. +static NSString *const kFIREventLogin NS_SWIFT_NAME(AnalyticsEventLogin) = @"login"; + +/// Post Score event. Log this event when the user posts a score in your gaming app. This event can +/// help you understand how users are actually performing in your game and it can help you correlate +/// high scores with certain audiences or behaviors. Params: +/// +///
    +///
  • @c kFIRParameterScore (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber) (optional)
  • +///
  • @c kFIRParameterCharacter (NSString) (optional)
  • +///
+static NSString *const kFIREventPostScore NS_SWIFT_NAME(AnalyticsEventPostScore) = @"post_score"; + +/// Present Offer event. This event signifies that the app has presented a purchase offer to a user. +/// Add this event to a funnel with the kFIREventAddToCart and kFIREventEcommercePurchase to gauge +/// your conversion process. Note: If you supply the @c kFIRParameterValue parameter, you must +/// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed +/// accurately. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
+static NSString *const kFIREventPresentOffer NS_SWIFT_NAME(AnalyticsEventPresentOffer) = + @"present_offer"; + +/// E-Commerce Purchase Refund event. This event signifies that an item purchase was refunded. +/// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the +/// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. +/// Params: +/// +///
    +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • +///
+static NSString *const kFIREventPurchaseRefund NS_SWIFT_NAME(AnalyticsEventPurchaseRefund) = + @"purchase_refund"; + +/// Remove from cart event. Params: +/// +///
    +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
+static NSString *const kFIREventRemoveFromCart NS_SWIFT_NAME(AnalyticsEventRemoveFromCart) = + @"remove_from_cart"; + +/// Search event. Apps that support search features can use this event to contextualize search +/// operations by supplying the appropriate, corresponding parameters. This event can help you +/// identify the most popular content in your app. Params: +/// +///
    +///
  • @c kFIRParameterSearchTerm (NSString)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// hotel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventSearch NS_SWIFT_NAME(AnalyticsEventSearch) = @"search"; + +/// Select Content event. This general purpose event signifies that a user has selected some content +/// of a certain type in an app. The content can be any object in your app. This event can help you +/// identify popular content and categories of content in your app. Params: +/// +///
    +///
  • @c kFIRParameterContentType (NSString)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
+static NSString *const kFIREventSelectContent NS_SWIFT_NAME(AnalyticsEventSelectContent) = + @"select_content"; + +/// Set checkout option. Params: +/// +///
    +///
  • @c kFIRParameterCheckoutStep (unsigned 64-bit integer as NSNumber)
  • +///
  • @c kFIRParameterCheckoutOption (NSString)
  • +///
+static NSString *const kFIREventSetCheckoutOption NS_SWIFT_NAME(AnalyticsEventSetCheckoutOption) = + @"set_checkout_option"; + +/// Share event. Apps with social features can log the Share event to identify the most viral +/// content. Params: +/// +///
    +///
  • @c kFIRParameterContentType (NSString)
  • +///
  • @c kFIRParameterItemID (NSString)
  • +///
+static NSString *const kFIREventShare NS_SWIFT_NAME(AnalyticsEventShare) = @"share"; + +/// Sign Up event. This event indicates that a user has signed up for an account in your app. The +/// parameter signifies the method by which the user signed up. Use this event to understand the +/// different behaviors between logged in and logged out users. Params: +/// +///
    +///
  • @c kFIRParameterSignUpMethod (NSString)
  • +///
+static NSString *const kFIREventSignUp NS_SWIFT_NAME(AnalyticsEventSignUp) = @"sign_up"; + +/// Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can +/// help you identify which virtual goods are the most popular objects of purchase. Params: +/// +///
    +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • +///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • +///
+static NSString *const kFIREventSpendVirtualCurrency + NS_SWIFT_NAME(AnalyticsEventSpendVirtualCurrency) = @"spend_virtual_currency"; + +/// Tutorial Begin event. This event signifies the start of the on-boarding process in your app. Use +/// this in a funnel with kFIREventTutorialComplete to understand how many users complete this +/// process and move on to the full app experience. +static NSString *const kFIREventTutorialBegin NS_SWIFT_NAME(AnalyticsEventTutorialBegin) = + @"tutorial_begin"; + +/// Tutorial End event. Use this event to signify the user's completion of your app's on-boarding +/// process. Add this to a funnel with kFIREventTutorialBegin to gauge the completion rate of your +/// on-boarding process. +static NSString *const kFIREventTutorialComplete NS_SWIFT_NAME(AnalyticsEventTutorialComplete) = + @"tutorial_complete"; + +/// Unlock Achievement event. Log this event when the user has unlocked an achievement in your +/// game. Since achievements generally represent the breadth of a gaming experience, this event can +/// help you understand how many users are experiencing all that your game has to offer. Params: +/// +///
    +///
  • @c kFIRParameterAchievementID (NSString)
  • +///
+static NSString *const kFIREventUnlockAchievement NS_SWIFT_NAME(AnalyticsEventUnlockAchievement) = + @"unlock_achievement"; + +/// View Item event. This event signifies that some content was shown to the user. This content may +/// be a product, a webpage or just a simple image or text. Use the appropriate parameters to +/// contextualize the event. Use this event to discover the most popular items viewed in your app. +/// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the +/// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. +/// Params: +/// +///
    +///
  • @c kFIRParameterItemID (NSString)
  • +///
  • @c kFIRParameterItemName (NSString)
  • +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • +///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber) (optional)
  • +///
  • @c kFIRParameterCurrency (NSString) (optional)
  • +///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • +///
  • @c kFIRParameterStartDate (NSString) (optional)
  • +///
  • @c kFIRParameterEndDate (NSString) (optional)
  • +///
  • @c kFIRParameterFlightNumber (NSString) (optional) for travel bookings
  • +///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) +/// for travel bookings
  • +///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for +/// travel bookings
  • +///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for +/// travel bookings
  • +///
  • @c kFIRParameterOrigin (NSString) (optional)
  • +///
  • @c kFIRParameterDestination (NSString) (optional)
  • +///
  • @c kFIRParameterSearchTerm (NSString) (optional) for travel bookings
  • +///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • +///
+static NSString *const kFIREventViewItem NS_SWIFT_NAME(AnalyticsEventViewItem) = @"view_item"; + +/// View Item List event. Log this event when the user has been presented with a list of items of a +/// certain category. Params: +/// +///
    +///
  • @c kFIRParameterItemCategory (NSString)
  • +///
+static NSString *const kFIREventViewItemList NS_SWIFT_NAME(AnalyticsEventViewItemList) = + @"view_item_list"; + +/// View Search Results event. Log this event when the user has been presented with the results of a +/// search. Params: +/// +///
    +///
  • @c kFIRParameterSearchTerm (NSString)
  • +///
+static NSString *const kFIREventViewSearchResults NS_SWIFT_NAME(AnalyticsEventViewSearchResults) = + @"view_search_results"; + +/// Level Start event. Log this event when the user starts a new level. Params: +/// +///
    +///
  • @c kFIRParameterLevelName (NSString)
  • +///
+static NSString *const kFIREventLevelStart NS_SWIFT_NAME(AnalyticsEventLevelStart) = + @"level_start"; + +/// Level End event. Log this event when the user finishes a level. Params: +/// +///
    +///
  • @c kFIRParameterLevelName (NSString)
  • +///
  • @c kFIRParameterSuccess (NSString)
  • +///
+static NSString *const kFIREventLevelEnd NS_SWIFT_NAME(AnalyticsEventLevelEnd) = @"level_end"; diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h new file mode 100755 index 0000000..e8920e8 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h @@ -0,0 +1,519 @@ +/// @file FIRParameterNames.h +/// +/// Predefined event parameter names. +/// +/// Params supply information that contextualize Events. You can associate up to 25 unique Params +/// with each Event type. Some Params are suggested below for certain common Events, but you are +/// not limited to these. You may supply extra Params for suggested Events or custom Params for +/// Custom events. Param names can be up to 40 characters long, may only contain alphanumeric +/// characters and underscores ("_"), and must start with an alphabetic character. Param values can +/// be up to 100 characters long. The "firebase_", "google_", and "ga_" prefixes are reserved and +/// should not be used. + +#import + +/// Game achievement ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterAchievementID : @"10_matches_won",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAchievementID NS_SWIFT_NAME(AnalyticsParameterAchievementID) = + @"achievement_id"; + +/// Ad Network Click ID (NSString). Used for network-specific click IDs which vary in format. +///
+///     NSDictionary *params = @{
+///       kFIRParameterAdNetworkClickID : @"1234567",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAdNetworkClickID + NS_SWIFT_NAME(AnalyticsParameterAdNetworkClickID) = @"aclid"; + +/// The store or affiliation from which this transaction occurred (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterAffiliation : @"Google Store",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterAffiliation NS_SWIFT_NAME(AnalyticsParameterAffiliation) = + @"affiliation"; + +/// The individual campaign name, slogan, promo code, etc. Some networks have pre-defined macro to +/// capture campaign information, otherwise can be populated by developer. Highly Recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCampaign : @"winter_promotion",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCampaign NS_SWIFT_NAME(AnalyticsParameterCampaign) = + @"campaign"; + +/// Character used in game (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCharacter : @"beat_boss",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCharacter NS_SWIFT_NAME(AnalyticsParameterCharacter) = + @"character"; + +/// The checkout step (1..N) (unsigned 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCheckoutStep : @"1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCheckoutStep NS_SWIFT_NAME(AnalyticsParameterCheckoutStep) = + @"checkout_step"; + +/// Some option on a step in an ecommerce flow (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCheckoutOption : @"Visa",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCheckoutOption + NS_SWIFT_NAME(AnalyticsParameterCheckoutOption) = @"checkout_option"; + +/// Campaign content (NSString). +static NSString *const kFIRParameterContent NS_SWIFT_NAME(AnalyticsParameterContent) = @"content"; + +/// Type of content selected (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterContentType : @"news article",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterContentType NS_SWIFT_NAME(AnalyticsParameterContentType) = + @"content_type"; + +/// Coupon code for a purchasable item (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCoupon : @"zz123",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCoupon NS_SWIFT_NAME(AnalyticsParameterCoupon) = @"coupon"; + +/// Campaign custom parameter (NSString). Used as a method of capturing custom data in a campaign. +/// Use varies by network. +///
+///     NSDictionary *params = @{
+///       kFIRParameterCP1 : @"custom_data",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCP1 NS_SWIFT_NAME(AnalyticsParameterCP1) = @"cp1"; + +/// The name of a creative used in a promotional spot (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCreativeName : @"Summer Sale",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCreativeName NS_SWIFT_NAME(AnalyticsParameterCreativeName) = + @"creative_name"; + +/// The name of a creative slot (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCreativeSlot : @"summer_banner2",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCreativeSlot NS_SWIFT_NAME(AnalyticsParameterCreativeSlot) = + @"creative_slot"; + +/// Purchase currency in 3-letter +/// ISO_4217 format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCurrency : @"USD",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterCurrency NS_SWIFT_NAME(AnalyticsParameterCurrency) = + @"currency"; + +/// Flight or Travel destination (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterDestination : @"Mountain View, CA",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterDestination NS_SWIFT_NAME(AnalyticsParameterDestination) = + @"destination"; + +/// The arrival date, check-out date or rental end date for the item. This should be in +/// YYYY-MM-DD format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterEndDate : @"2015-09-14",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterEndDate NS_SWIFT_NAME(AnalyticsParameterEndDate) = @"end_date"; + +/// Flight number for travel events (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterFlightNumber : @"ZZ800",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterFlightNumber NS_SWIFT_NAME(AnalyticsParameterFlightNumber) = + @"flight_number"; + +/// Group/clan/guild ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterGroupID : @"g1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterGroupID NS_SWIFT_NAME(AnalyticsParameterGroupID) = @"group_id"; + +/// Index of an item in a list (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterIndex : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterIndex NS_SWIFT_NAME(AnalyticsParameterIndex) = @"index"; + +/// Item brand (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemBrand : @"Google",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemBrand NS_SWIFT_NAME(AnalyticsParameterItemBrand) = + @"item_brand"; + +/// Item category (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemCategory : @"t-shirts",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemCategory NS_SWIFT_NAME(AnalyticsParameterItemCategory) = + @"item_category"; + +/// Item ID (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemID : @"p7654",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemID NS_SWIFT_NAME(AnalyticsParameterItemID) = @"item_id"; + +/// The Google Place ID (NSString) that +/// corresponds to the associated item. Alternatively, you can supply your own custom Location ID. +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemLocationID : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemLocationID + NS_SWIFT_NAME(AnalyticsParameterItemLocationID) = @"item_location_id"; + +/// Item name (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemName : @"abc",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemName NS_SWIFT_NAME(AnalyticsParameterItemName) = + @"item_name"; + +/// The list in which the item was presented to the user (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemList : @"Search Results",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemList NS_SWIFT_NAME(AnalyticsParameterItemList) = + @"item_list"; + +/// Item variant (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterItemVariant : @"Red",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterItemVariant NS_SWIFT_NAME(AnalyticsParameterItemVariant) = + @"item_variant"; + +/// Level in game (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterLevel : @(42),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLevel NS_SWIFT_NAME(AnalyticsParameterLevel) = @"level"; + +/// Location (NSString). The Google Place ID +/// that corresponds to the associated event. Alternatively, you can supply your own custom +/// Location ID. +///
+///     NSDictionary *params = @{
+///       kFIRParameterLocation : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLocation NS_SWIFT_NAME(AnalyticsParameterLocation) = + @"location"; + +/// The advertising or marketing medium, for example: cpc, banner, email, push. Highly recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterMedium : @"email",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterMedium NS_SWIFT_NAME(AnalyticsParameterMedium) = @"medium"; + +/// Number of nights staying at hotel (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfNights : @(3),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfNights + NS_SWIFT_NAME(AnalyticsParameterNumberOfNights) = @"number_of_nights"; + +/// Number of passengers traveling (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfPassengers : @(11),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfPassengers + NS_SWIFT_NAME(AnalyticsParameterNumberOfPassengers) = @"number_of_passengers"; + +/// Number of rooms for travel events (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterNumberOfRooms : @(2),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterNumberOfRooms NS_SWIFT_NAME(AnalyticsParameterNumberOfRooms) = + @"number_of_rooms"; + +/// Flight or Travel origin (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterOrigin : @"Mountain View, CA",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterOrigin NS_SWIFT_NAME(AnalyticsParameterOrigin) = @"origin"; + +/// Purchase price (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterPrice : @(1.0),
+///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterPrice NS_SWIFT_NAME(AnalyticsParameterPrice) = @"price"; + +/// Purchase quantity (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterQuantity : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterQuantity NS_SWIFT_NAME(AnalyticsParameterQuantity) = + @"quantity"; + +/// Score in game (signed 64-bit integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterScore : @(4200),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterScore NS_SWIFT_NAME(AnalyticsParameterScore) = @"score"; + +/// The search string/keywords used (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSearchTerm : @"periodic table",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSearchTerm NS_SWIFT_NAME(AnalyticsParameterSearchTerm) = + @"search_term"; + +/// Shipping cost (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterShipping : @(9.50),
+///       kFIRParameterCurrency : @"USD",  // e.g. $9.50 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterShipping NS_SWIFT_NAME(AnalyticsParameterShipping) = + @"shipping"; + +/// Sign up method (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSignUpMethod : @"google",
+///       // ...
+///     };
+/// 
+/// +/// This constant has been deprecated. Use Method constant instead. +static NSString *const kFIRParameterSignUpMethod NS_SWIFT_NAME(AnalyticsParameterSignUpMethod) = + @"sign_up_method"; + +/// A particular approach used in an operation; for example, "facebook" or "email" in the context +/// of a sign_up or login event. (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterMethod : @"google",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterMethod NS_SWIFT_NAME(AnalyticsParameterMethod) = @"method"; + +/// The origin of your traffic, such as an Ad network (for example, google) or partner (urban +/// airship). Identify the advertiser, site, publication, etc. that is sending traffic to your +/// property. Highly recommended (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSource : @"InMobi",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSource NS_SWIFT_NAME(AnalyticsParameterSource) = @"source"; + +/// The departure date, check-in date or rental start date for the item. This should be in +/// YYYY-MM-DD format (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterStartDate : @"2015-09-14",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterStartDate NS_SWIFT_NAME(AnalyticsParameterStartDate) = + @"start_date"; + +/// Tax amount (double as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTax : @(1.0),
+///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTax NS_SWIFT_NAME(AnalyticsParameterTax) = @"tax"; + +/// If you're manually tagging keyword campaigns, you should use utm_term to specify the keyword +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTerm : @"game",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTerm NS_SWIFT_NAME(AnalyticsParameterTerm) = @"term"; + +/// A single ID for a ecommerce group transaction (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTransactionID : @"ab7236dd9823",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTransactionID NS_SWIFT_NAME(AnalyticsParameterTransactionID) = + @"transaction_id"; + +/// Travel class (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterTravelClass : @"business",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterTravelClass NS_SWIFT_NAME(AnalyticsParameterTravelClass) = + @"travel_class"; + +/// A context-specific numeric value which is accumulated automatically for each event type. This is +/// a general purpose parameter that is useful for accumulating a key metric that pertains to an +/// event. Examples include revenue, distance, time and points. Value should be specified as signed +/// 64-bit integer or double as NSNumber. Notes: Values for pre-defined currency-related events +/// (such as @c kFIREventAddToCart) should be supplied using double as NSNumber and must be +/// accompanied by a @c kFIRParameterCurrency parameter. The valid range of accumulated values is +/// [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a non-numeric value, omitting the +/// corresponding @c kFIRParameterCurrency parameter, or supplying an invalid +/// currency code for conversion events will cause that +/// conversion to be omitted from reporting. +///
+///     NSDictionary *params = @{
+///       kFIRParameterValue : @(3.99),
+///       kFIRParameterCurrency : @"USD",  // e.g. $3.99 USD
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterValue NS_SWIFT_NAME(AnalyticsParameterValue) = @"value"; + +/// Name of virtual currency type (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterVirtualCurrencyName : @"virtual_currency_name",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterVirtualCurrencyName + NS_SWIFT_NAME(AnalyticsParameterVirtualCurrencyName) = @"virtual_currency_name"; + +/// The name of a level in a game (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterLevelName : @"room_1",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterLevelName NS_SWIFT_NAME(AnalyticsParameterLevelName) = + @"level_name"; + +/// The result of an operation. Specify 1 to indicate success and 0 to indicate failure (unsigned +/// integer as NSNumber). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSuccess : @(1),
+///       // ...
+///     };
+/// 
+static NSString *const kFIRParameterSuccess NS_SWIFT_NAME(AnalyticsParameterSuccess) = @"success"; diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h new file mode 100755 index 0000000..f50707f --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h @@ -0,0 +1,17 @@ +/// @file FIRUserPropertyNames.h +/// +/// Predefined user property names. +/// +/// A UserProperty is an attribute that describes the app-user. By supplying UserProperties, you can +/// later analyze different behaviors of various segments of your userbase. You may supply up to 25 +/// unique UserProperties per app, and you can use the name and value of your choosing for each one. +/// UserProperty names can be up to 24 characters long, may only contain alphanumeric characters and +/// underscores ("_"), and must start with an alphabetic character. UserProperty values can be up to +/// 36 characters long. The "firebase_", "google_", and "ga_" prefixes are reserved and should not +/// be used. + +#import + +/// The method used to sign in. For example, "google", "facebook" or "twitter". +static NSString *const kFIRUserPropertySignUpMethod + NS_SWIFT_NAME(AnalyticsUserPropertySignUpMethod) = @"sign_up_method"; diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h new file mode 100755 index 0000000..ed7588a --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h @@ -0,0 +1,5 @@ +#import "FIRAnalytics+AppDelegate.h" +#import "FIRAnalytics.h" +#import "FIREventNames.h" +#import "FIRParameterNames.h" +#import "FIRUserPropertyNames.h" diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap new file mode 100755 index 0000000..ef80595 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap @@ -0,0 +1,10 @@ +framework module FirebaseAnalytics { + umbrella header "FirebaseAnalytics.h" + export * + module * { export *} + link "sqlite3" + link "z" + link framework "Security" + link framework "StoreKit" + link framework "SystemConfiguration" + link framework "UIKit"} diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics new file mode 100755 index 0000000..9144957 Binary files /dev/null and b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/FirebaseCoreDiagnostics differ diff --git a/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap new file mode 100755 index 0000000..bbcb94e --- /dev/null +++ b/My Mind/Pods/FirebaseAnalytics/Frameworks/FirebaseCoreDiagnostics.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseCoreDiagnostics { + export * + module * { export *} + link "z" + link framework "Security" + link framework "SystemConfiguration"} diff --git a/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRAnalyticsInterop.h b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRAnalyticsInterop.h new file mode 100644 index 0000000..5e30168 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRAnalyticsInterop.h @@ -0,0 +1,52 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAConditionalUserProperty; + +NS_ASSUME_NONNULL_BEGIN + +/// Connector for bridging communication between Firebase SDKs and FirebaseAnalytics API. +@protocol FIRAnalyticsInterop + +/// Sets user property when trigger event is logged. This API is only available in the SDK. +- (void)setConditionalUserProperty:(FIRAConditionalUserProperty *)conditionalUserProperty; + +/// Clears user property if set. +- (void)clearConditionalUserProperty:(NSString *)userPropertyName + clearEventName:(NSString *)clearEventName + clearEventParameters:(NSDictionary *)clearEventParameters; + +/// Returns currently set user properties. +- (NSArray *)conditionalUserProperties:(NSString *)origin + propertyNamePrefix: + (NSString *)propertyNamePrefix; + +/// Returns the maximum number of user properties. +- (NSInteger)maxUserProperties:(NSString *)origin; + +/// Logs events. +- (void)logEventWithOrigin:(NSString *)origin + name:(NSString *)name + parameters:(nullable NSDictionary *)parameters; + +/// Sets user property. +- (void)setUserPropertyWithOrigin:(NSString *)origin name:(NSString *)name value:(id)value; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropEventNames.h b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropEventNames.h new file mode 100644 index 0000000..dc04226 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropEventNames.h @@ -0,0 +1,26 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// @file FIRInteropEventNames.h + +/// Notification open event name. +static NSString *const kFIRIEventNotificationOpen = @"_no"; + +/// Notification foreground event name. +static NSString *const kFIRIEventNotificationForeground = @"_nf"; + +/// Campaign event name. +static NSString *const kFIRIEventFirebaseCampaign = @"_cmp"; diff --git a/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropParameterNames.h b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropParameterNames.h new file mode 100644 index 0000000..9cd9623 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropParameterNames.h @@ -0,0 +1,71 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// @file FIRInteropParameterNames.h +/// +/// Predefined event parameter names used by Firebase. This file is a subset of the +/// FirebaseAnalytics FIRParameterNames.h public header. +/// +/// The origin of your traffic, such as an Ad network (for example, google) or partner (urban +/// airship). Identify the advertiser, site, publication, etc. that is sending traffic to your +/// property. Highly recommended (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterSource : @"InMobi",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRIParameterSource NS_SWIFT_NAME(AnalyticsParameterSource) = @"source"; + +/// The advertising or marketing medium, for example: cpc, banner, email, push. Highly recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterMedium : @"email",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRIParameterMedium NS_SWIFT_NAME(AnalyticsParameterMedium) = @"medium"; + +/// The individual campaign name, slogan, promo code, etc. Some networks have pre-defined macro to +/// capture campaign information, otherwise can be populated by developer. Highly Recommended +/// (NSString). +///
+///     NSDictionary *params = @{
+///       kFIRParameterCampaign : @"winter_promotion",
+///       // ...
+///     };
+/// 
+static NSString *const kFIRIParameterCampaign NS_SWIFT_NAME(AnalyticsParameterCampaign) = + @"campaign"; + +/// Message identifier. +static NSString *const kFIRIParameterMessageIdentifier = @"_nmid"; + +/// Message name. +static NSString *const kFIRIParameterMessageName = @"_nmn"; + +/// Message send time. +static NSString *const kFIRIParameterMessageTime = @"_nmt"; + +/// Message device time. +static NSString *const kFIRIParameterMessageDeviceTime = @"_ndt"; + +/// Topic message. +static NSString *const kFIRIParameterTopic = @"_nt"; + +/// Stores the message_id of the last notification opened by the app. +static NSString *const kFIRIUserPropertyLastNotification = @"_ln"; diff --git a/My Mind/Pods/FirebaseAnalyticsInterop/LICENSE b/My Mind/Pods/FirebaseAnalyticsInterop/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalyticsInterop/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseAnalyticsInterop/README.md b/My Mind/Pods/FirebaseAnalyticsInterop/README.md new file mode 100644 index 0000000..eb6ea33 --- /dev/null +++ b/My Mind/Pods/FirebaseAnalyticsInterop/README.md @@ -0,0 +1,180 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +An experimental Carthage distribution is now available. See +[Carthage](Carthage.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/CHANGELOG.md b/My Mind/Pods/FirebaseAuth/Firebase/Auth/CHANGELOG.md new file mode 100644 index 0000000..ac4e3ef --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/CHANGELOG.md @@ -0,0 +1,178 @@ +# v5.2.0 +- Add support of Game Center sign in (#2127). + +# v5.1.0 +- Add support of custom FDL domain link (#2121). + +# v5.0.5 +- Restore SafariServices framework dependency (#2002). + +# v5.0.4 +- Fix analyzer issues (#1740). + +# v5.0.3 +- Add `FIRAuthErrorCodeMalformedJWT`, which is raised on JWT token parsing. + failures during auth operations (#1436). +- Migrate to use FirebaseAuthInterop interfaces to access FirebaseAuth (#1501). + +# v5.0.2 +- Fix an issue where JWT date timestamps weren't parsed correctly. (#1319) +- Fix an issue where anonymous accounts weren't correctly promoted to + non-anonymous when linked with passwordless email auth accounts. (#1383) +- Fix an exception from using an invalidated NSURLSession. (#1261) +- Fix a data race issue caught by the sanitizer. (#1446) + +# v5.0.1 +- Restore 4.x level of support for extensions (#1357). + +# v5.0.0 +- Adds APIs for phone Auth testing to bypass the verification flow (#1192). +- Changes the callback block signature for sign in and create user methods + to provide an AuthDataResult that includes the user and user info (#1123, #1186). +- Removes GoogleToolboxForMac dependency (#1175). +- Removes miscellaneous deprecated APIs (#1188, #1200). + +# v4.6.1 +- Fixes crash which occurred when certain Firebase IDTokens were being parsed (#1076). + +# v4.6.0 +- Adds `getIDTokenResultWithCompletion:` and `getIDTokenResultForcingRefresh:completion:` APIs which + call back with an AuthTokenResult object. The Auth token result object contains the ID token JWT string and other properties associated with the token including the decoded available payload claims (#1004). + +- Adds the `updateCurrentUser:completion:` API which sets the currentUser on the calling Auth instance to the provided user object (#1018). + +- Adds client-side validation to prevent setting `handleCodeInApp` to false when performing + email-link authentication. If `handleCodeInApp` is set to false an invalid argument exception + is thrown (#931). + +- Adds support for passing the deep link (which is embedded in the sign-in link sent via email) to the + `signInWithEmail:link:completion:` and `isSignInWithEmailLink:` methods during an + email/link sign-in flow (#1023). + +# v4.5.0 +- Adds new API which provides a way to determine the sign-in methods associated with an + email address. +- Adds new API which allows authentication using only an email link (Passwordless Authentication + with email link). + +# v4.4.4 +- Addresses CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF warnings that surface in newer versions of + Xcode and CocoaPods. +- Improves FIRUser documentation with clear message explaining when Firebase Auth attempts to validate + users and what happens when an invalidated user is detected (#694) . + +# v4.4.3 +- Adds an explicit dependency on CoreGraphics from Firebase Auth. + +# v4.4.2 +- Fixes bug where the FIRAuthResult object returned following a Phone Number authentication + always contained a nil FIRAdditionalUserInfo object. Now the FIRAdditionalUserInfo object is + never nil and its newUser field is populated correctly. + +# v4.4.0 +- Adds new APIs which return an AuthDataResult object after successfully creating an + Email/Password user, signing in anonymously, signing in with Email/Password and signing + in with Custom Token. The AuthDataResult object contains the new user and additional + information pertaining to the new user. + +# v4.3.2 +- Improves error handling for the phone number sign-in reCAPTCHA flow. +- Improves error handling for phone number linking flow. +- Fixes issue where after linking an anonymous user to a phone number the user remained + anonymous. + +# v4.3.1 +- Internal clean up. + +# v4.3.0 +- Provides account creation and last sign-in dates as metadata to the user + object. +- Returns more descriptive errors for some error cases of the phone number + sign-in reCAPTCHA flow. +- Fixes an issue that invalid users were not automatically signed out earlier. +- Fixes an issue that ID token listeners were not fired in some cases. + +# v4.2.1 +- Fixes a threading issue in phone number auth that completion block was not + executed on the main thread in some error cases. + +# v4.2.0 +- Adds new phone number verification API which makes use of an intelligent reCAPTCHA to verify the application. + +# v4.1.1 +- Improves some method documentation in headers. + +# v4.1.0 +- Allows the app to handle continue URL natively, e.g., from password reset + email. +- Allows the app to set language code, e.g., for sending password reset email. +- Fixes an issue that user's phone number did not persist on client. +- Fixes an issue that recover email action code type was reported as unknown. +- Improves app start-up time by moving initialization off from the main + thread. +- Better reports missing email error when creating a new password user. +- Changes console message logging levels to be more consistent with other + Firebase products on the iOS platform. + +# 2017-05-17 -- v4.0.0 +- Adds Phone Number Authentication. +- Adds support for generic OAuth2 identity providers. +- Adds methods that return additional user data from identity providers if + available when authenticating users. +- Improves session management by automatically refreshing tokens if possible + and signing out users if the session is detected invalidated, for example, + after the user changed password or deleted account from another device. +- Fixes an issue that reauthentication creates new user account if the user + credential is valid but does not match the currently signed in user. +- Fixes an issue that the "password" provider is not immediately listed on the + client side after adding a password to an account. +- Changes factory methods to return non-null FIRAuth instances or raises an + exception, instead of returning nullable instances. +- Changes auth state change listener to only be triggered when the user changes. +- Adds a new listener which is triggered whenever the ID token is changed. +- Switches ERROR_EMAIL_ALREADY_IN_USE to + ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL when the email used in the + signInWithCredential: call is already in use by another account. +- Deprecates FIREmailPasswordAuthProvider in favor of FIREmailAuthProvider. +- Deprecates getTokenWithCompletion in favor of getIDTokenWithCompletion on + FIRUser. +- Changes Swift API names to better align with Swift convention. + +# 2017-02-06 -- v3.1.1 +- Allows handling of additional errors when sending OOB action emails. The + server can respond with the following new error messages: + INVALID_MESSAGE_PAYLOAD,INVALID_SENDER and INVALID_RECIPIENT_EMAIL. +- Removes incorrect reference to FIRAuthErrorCodeCredentialTooOld in FIRUser.h. +- Provides additional error information from server if available. + +# 2016-12-13 -- v3.1.0 +- Adds FIRAuth methods that enable the app to follow up with user actions + delivered by email, such as verifying email address or reset password. +- No longer applies the keychain workaround introduced in v3.0.5 on iOS 10.2 + simulator or above since the issue has been fixed. +- Fixes nullability compilation warnings when used in Swift. +- Better reports missing password error. + +# 2016-10-24 -- v3.0.6 +- Switches to depend on open sourced GoogleToolboxForMac and GTMSessionFetcher. +- Improves logging of keychain error when initializing. + +# 2016-09-14 -- v3.0.5 +- Works around a keychain issue in iOS 10 simulator. +- Reports the correct error for invalid email when signing in with email and + password. + +# 2016-07-18 -- v3.0.4 +- Fixes a race condition bug that could crash the app with an exception from + NSURLSession on iOS 9. + +# 2016-06-20 -- v3.0.3 +- Adds documentation for all possible errors returned by each method. +- Improves error handling and messages for a variety of error conditions. +- Whether or not an user is considered anonymous is now consistent with other + platforms. +- A saved signed in user is now siloed between different Firebase projects + within the same app. + +# 2016-05-18 -- v3.0.2 +- Initial public release. diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/README.md b/My Mind/Pods/FirebaseAuth/Firebase/Auth/README.md new file mode 100644 index 0000000..f6e123e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/README.md @@ -0,0 +1,17 @@ +# Firebase Auth for iOS + +Firebase Auth enables apps to easily support multiple authentication options +for their end users. + +Please visit [our developer site](https://firebase.google.com/docs/auth/) for +integration instructions, documentation, support information, and terms of +service. + +# Firebase Auth Development + +Example/Auth contains a set of samples and tests that integrate with +FirebaseAuth. + +The unit tests run without any additional configuration along with the rest of +Firebase. See [Example/Auth/README.md](../../Example/Auth/README.md) for +information about setting up, running, and testing the samples. diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailAuthProvider.m new file mode 100644 index 0000000..7a871e2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailAuthProvider.m @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIREmailAuthProvider.h" + +#import "FIREmailPasswordAuthCredential.h" + +// FIREmailPasswordAuthProviderID is defined in FIRAuthProvider.m. + +@implementation FIREmailAuthProvider + +- (instancetype)init { + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." + reason:@"This class is not meant to be initialized." + userInfo:nil]; +} + ++ (FIRAuthCredential *)credentialWithEmail:(NSString *)email password:(NSString *)password { + return [[FIREmailPasswordAuthCredential alloc] initWithEmail:email password:password]; +} + ++ (FIRAuthCredential *)credentialWithEmail:(NSString *)email link:(NSString *)link { + return [[FIREmailPasswordAuthCredential alloc] initWithEmail:email link:link]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h new file mode 100644 index 0000000..7625685 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIREmailPasswordAuthCredential + @brief Internal implementation of FIRAuthCredential for Email/Password credentials. + */ +@interface FIREmailPasswordAuthCredential : FIRAuthCredential + +/** @property email + @brief The user's email address. + */ +@property(nonatomic, readonly) NSString *email; + +/** @property password + @brief The user's password. + */ +@property(nonatomic, readonly) NSString *password; + +/** @property link + @brief The email sign-in link. + */ +@property(nonatomic, readonly) NSString *link; + +/** @fn initWithEmail:password: + @brief Designated initializer. + @param email The user's email address. + @param password The user's password. + */ +- (nullable instancetype)initWithEmail:(NSString *)email password:(NSString *)password + NS_DESIGNATED_INITIALIZER; + +/** @fn initWithEmail:link: + @brief Designated initializer. + @param email The user's email address. + @param link The email sign-in link. + */ +- (nullable instancetype)initWithEmail:(NSString *)email link:(NSString *)link + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.m new file mode 100644 index 0000000..71cc330 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.m @@ -0,0 +1,60 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIREmailPasswordAuthCredential.h" + +#import "FIREmailAuthProvider.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +@interface FIREmailPasswordAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIREmailPasswordAuthCredential + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithEmail:(NSString *)email password:(NSString *)password { + self = [super initWithProvider:FIREmailAuthProviderID]; + if (self) { + _email = [email copy]; + _password = [password copy]; + } + return self; +} + +- (nullable instancetype)initWithEmail:(NSString *)email link:(NSString *)link { + self = [super initWithProvider:FIREmailAuthProviderID]; + if (self) { + _email = [email copy]; + _link = [link copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Attempt to call prepareVerifyAssertionRequest: on a FIREmailPasswordAuthCredential."]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.h new file mode 100644 index 0000000..47ab18a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRFacebookAuthCredential + @brief Internal implementation of FIRAuthCredential for the Facebook IdP. + */ +@interface FIRFacebookAuthCredential : FIRAuthCredential + +/** @fn initWithAccessToken: + @brief Designated initializer. + @param accessToken The Access Token obtained from Facebook. + */ +- (nullable instancetype)initWithAccessToken:(NSString *)accessToken NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.m new file mode 100644 index 0000000..1c3576a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.m @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRFacebookAuthCredential.h" + +#import "FIRFacebookAuthProvider.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +@interface FIRFacebookAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIRFacebookAuthCredential { + NSString *_accessToken; +} + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithAccessToken:(NSString *)accessToken { + self = [super initWithProvider:FIRFacebookAuthProviderID]; + if (self) { + _accessToken = [accessToken copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + request.providerAccessToken = _accessToken; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthProvider.m new file mode 100644 index 0000000..d2759ae --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthProvider.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRFacebookAuthProvider.h" + +#import "FIRFacebookAuthCredential.h" +#import "FIRAuthExceptionUtils.h" + +// FIRFacebookAuthProviderID is defined in FIRAuthProvider.m. + +@implementation FIRFacebookAuthProvider + +- (instancetype)init { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"This class is not meant to be initialized."]; + return nil; +} + ++ (FIRAuthCredential *)credentialWithAccessToken:(NSString *)accessToken { + return [[FIRFacebookAuthCredential alloc] initWithAccessToken:accessToken]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.h new file mode 100644 index 0000000..a99b96e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.h @@ -0,0 +1,80 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGameCenterAuthCredential + @brief Internal implementation of FIRAuthCredential for Game Center credentials. + */ +@interface FIRGameCenterAuthCredential : FIRAuthCredential + +/** @property playerID + @brief The ID of the Game Center local player. + */ +@property(nonatomic, readonly) NSString *playerID; + +/** @property publicKeyURL + @brief The URL for the public encryption key. + */ +@property(nonatomic, readonly) NSURL *publicKeyURL; + +/** @property signature + @brief The verification signature data generated. + */ +@property(nonatomic, readonly) NSData *signature; + +/** @property salt + @brief A random string used to compute the hash and keep it randomized. + */ +@property(nonatomic, readonly) NSData *salt; + +/** @property timestamp + @brief The date and time that the signature was created. + */ +@property(nonatomic, readonly) uint64_t timestamp; + +/** @property displayName + @brief The date and time that the signature was created. + */ +@property(nonatomic, readonly) NSString *displayName; + +/** @fn initWithPlayerID:publicKeyURL:signature:salt:timestamp:displayName: + @brief Designated initializer. + @param publicKeyURL The URL for the public encryption key. + @param signature The verification signature generated. + @param salt A random string used to compute the hash and keep it randomized. + @param timestamp The date and time that the signature was created. + */ +- (nullable instancetype)initWithPlayerID:(NSString *)playerID + publicKeyURL:(NSURL *)publicKeyURL + signature:(NSData *)signature + salt:(NSData *)salt + timestamp:(uint64_t)timestamp + displayName:(NSString *)displayName NS_DESIGNATED_INITIALIZER; + +/** @fn initWithProvider: + @brief Initializer with a provider name. + @param provider The provider name. + */ +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.m new file mode 100644 index 0000000..4ccd408 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.m @@ -0,0 +1,55 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGameCenterAuthCredential.h" + +#import "FIRAuthExceptionUtils.h" +#import "FIRAuthCredential_Internal.h" +#import "FIRGameCenterAuthProvider.h" +#import "FIRVerifyAssertionRequest.h" + +@implementation FIRGameCenterAuthCredential + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithPlayerID:(NSString *)playerID + publicKeyURL:(NSURL *)publicKeyURL + signature:(NSData *)signature + salt:(NSData *)salt + timestamp:(uint64_t)timestamp + displayName:(NSString *)displayName { + self = [super initWithProvider:FIRGameCenterAuthProviderID]; + if (self) { + _playerID = [playerID copy]; + _publicKeyURL = [publicKeyURL copy]; + _signature = [signature copy]; + _salt = [salt copy]; + _timestamp = timestamp; + _displayName = [displayName copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Attempt to call prepareVerifyAssertionRequest: on a FIRGameCenterAuthCredential."]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthProvider.m new file mode 100644 index 0000000..65f79a8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthProvider.m @@ -0,0 +1,69 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGameCenterAuthProvider.h" + +#import + +#import "FIRAuthErrorUtils.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRGameCenterAuthCredential.h" + +@implementation FIRGameCenterAuthProvider + +- (instancetype)init { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"This class is not meant to be initialized."]; + return nil; +} + ++ (void)getCredentialWithCompletion:(FIRGameCenterCredentialCallback)completion { + __weak GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer]; + if (!localPlayer.isAuthenticated) { + if (completion) { + completion(nil, [FIRAuthErrorUtils localPlayerNotAuthenticatedError]); + } + return; + } + + [localPlayer generateIdentityVerificationSignatureWithCompletionHandler: + ^(NSURL *publicKeyURL, NSData *signature, NSData *salt, uint64_t timestamp, NSError *error) { + if (error) { + if (completion) { + completion(nil, error); + } + } else { + if (completion) { + /** + @c `localPlayer.alias` is actually the displayname needed, instead of + `localPlayer.displayname`. For more information, check + https://developer.apple.com/documentation/gamekit/gkplayer + **/ + NSString *displayName = localPlayer.alias; + FIRGameCenterAuthCredential *credential = + [[FIRGameCenterAuthCredential alloc] initWithPlayerID:localPlayer.playerID + publicKeyURL:publicKeyURL + signature:signature + salt:salt + timestamp:timestamp + displayName:displayName]; + completion(credential, nil); + } + } + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.h new file mode 100644 index 0000000..bfb5479 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGitHubAuthCredential + @brief Internal implementation of FIRAuthCredential for GitHub credentials. + */ +@interface FIRGitHubAuthCredential : FIRAuthCredential + +/** @property token + @brief The GitHub OAuth access token. + */ +@property(nonatomic, readonly) NSString *token; + +/** @fn initWithToken: + @brief Designated initializer. + @param token The GitHub OAuth access token. + */ +- (nullable instancetype)initWithToken:(NSString *)token NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.m new file mode 100644 index 0000000..a0185eb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.m @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGitHubAuthCredential.h" + +#import "FIRGitHubAuthProvider.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +@interface FIRGitHubAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIRGitHubAuthCredential + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithToken:(NSString *)token { + self = [super initWithProvider:FIRGitHubAuthProviderID]; + if (self) { + _token = [token copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + request.providerAccessToken = _token; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthProvider.m new file mode 100644 index 0000000..8e0ff76 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthProvider.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGitHubAuthProvider.h" + +#import "FIRGitHubAuthCredential.h" +#import "FIRAuthExceptionUtils.h" + +// FIRGitHubAuthProviderID is defined in FIRAuthProvider.m. + +@implementation FIRGitHubAuthProvider + +- (instancetype)init { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"This class is not meant to be initialized."]; + return nil; +} + ++ (FIRAuthCredential *)credentialWithToken:(NSString *)token { + return [[FIRGitHubAuthCredential alloc] initWithToken:token]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.h new file mode 100644 index 0000000..bacab63 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGoogleAuthCredential + @brief Internal implementation of FIRAuthCredential for the Google IdP. + */ +@interface FIRGoogleAuthCredential : FIRAuthCredential + +/** @fn initWithIDToken:accessToken: + @brief Designated initializer. + @param IDToken The ID Token obtained from Google. + @param accessToken The Access Token obtained from Google. + */ +- (nullable instancetype)initWithIDToken:(NSString *)IDToken accessToken:(NSString *)accessToken + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.m new file mode 100644 index 0000000..d66b2e2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.m @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGoogleAuthCredential.h" + +#import "FIRGoogleAuthProvider.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +@interface FIRGoogleAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIRGoogleAuthCredential { + NSString *_IDToken; + NSString *_accessToken; +} + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithIDToken:(NSString *)IDToken accessToken:(NSString *)accessToken { + self = [super initWithProvider:FIRGoogleAuthProviderID]; + if (self) { + _IDToken = [IDToken copy]; + _accessToken = [accessToken copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + request.providerIDToken = _IDToken; + request.providerAccessToken = _accessToken; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthProvider.m new file mode 100644 index 0000000..a2f4c79 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthProvider.m @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGoogleAuthProvider.h" + +#import "FIRGoogleAuthCredential.h" +#import "FIRAuthExceptionUtils.h" + +// FIRGoogleAuthProviderID is defined in FIRAuthProvider.m. + +@implementation FIRGoogleAuthProvider + +- (instancetype)init { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"This class is not meant to be initialized."]; + return nil; +} + ++ (FIRAuthCredential *)credentialWithIDToken:(NSString *)IDToken + accessToken:(NSString *)accessToken { + return [[FIRGoogleAuthCredential alloc] initWithIDToken:IDToken accessToken:accessToken]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.h new file mode 100644 index 0000000..c7241a1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIROAuthCredential + @brief Internal implementation of FIRAuthCredential for generic credentials. + */ +@interface FIROAuthCredential : FIRAuthCredential + +/** @property IDToken + @brief The ID Token associated with this credential. + */ +@property(nonatomic, readonly, nullable) NSString *IDToken; + +/** @property accessToken + @brief The access token associated with this credential. + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/** @fn initWithProviderId:IDToken:accessToken: + @brief Designated initializer. + @param providerID The provider ID associated with the credential being created. + @param IDToken The ID Token associated with the credential being created. + @param accessToken The access token associated with the credential being created. + */ +- (nullable instancetype)initWithProviderID:(NSString *)providerID + IDToken:(nullable NSString*)IDToken + accessToken:(nullable NSString *)accessToken; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.m new file mode 100644 index 0000000..67633d8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.m @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIROAuthCredential.h" + +#import "FIRVerifyAssertionRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIROAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIROAuthCredential + +- (nullable instancetype)initWithProviderID:(NSString *)providerID + IDToken:(nullable NSString *)IDToken + accessToken:(nullable NSString *)accessToken { + self = [super initWithProvider:providerID]; + if (self) { + _IDToken = IDToken; + _accessToken = accessToken; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + request.providerIDToken = _IDToken; + request.providerAccessToken = _accessToken; +} + +NS_ASSUME_NONNULL_END + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthProvider.m new file mode 100644 index 0000000..0561703 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthProvider.m @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIROAuthProvider.h" + +#import "FIROAuthCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIROAuthProvider + ++ (FIRAuthCredential *)credentialWithProviderID:(NSString *)providerID + IDToken:(NSString *)IDToken + accessToken:(nullable NSString *)accessToken { + return [[FIROAuthCredential alloc] initWithProviderID:providerID + IDToken:IDToken + accessToken:accessToken]; +} + ++ (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID + accessToken:(NSString *)accessToken { + return [[FIROAuthCredential alloc] initWithProviderID:providerID + IDToken:nil + accessToken:accessToken]; +} + +NS_ASSUME_NONNULL_END + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential.m new file mode 100644 index 0000000..c7e8bb1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential.m @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRPhoneAuthCredential.h" + +#import "FIRPhoneAuthCredential_Internal.h" +#import "FIRAuthCredential_Internal.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRPhoneAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIRPhoneAuthCredential + +- (instancetype)initWithTemporaryProof:(NSString *)temporaryProof + phoneNumber:(NSString *)phoneNumber + providerID:(NSString *)providerID { + self = [super initWithProvider:providerID]; + if (self) { + _temporaryProof = [temporaryProof copy]; + _phoneNumber = [phoneNumber copy]; + } + return self; +} + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (instancetype)initWithProviderID:(NSString *)providerID + verificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode { + self = [super initWithProvider:providerID]; + if (self) { + _verificationID = [verificationID copy]; + _verificationCode = [verificationCode copy]; + } + return self; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h new file mode 100644 index 0000000..f260b89 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#import + +#import "FIRPhoneAuthCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @extension FIRPhoneAuthCredential + @brief Internal implementation of FIRAuthCredential for Phone Auth credentials. + */ +@interface FIRPhoneAuthCredential () + +/** @var verificationID + @brief The verification ID obtained from invoking @c verifyPhoneNumber:completion: + */ +@property(nonatomic, readonly, nonnull) NSString *verificationID; + +/** @var verificationCode + @brief The verification code provided by the user. + */ +@property(nonatomic, readonly, nonnull) NSString *verificationCode; + +/** @var temporaryProof + @brief The a temporary proof code perftaining to this credential, returned from the backend. + */ +@property(nonatomic, readonly, nonnull) NSString *temporaryProof; + +/** @var phoneNumber + @brief The a phone number pertaining to this credential, returned from the backend. + */ +@property(nonatomic, readonly, nonnull) NSString *phoneNumber; + +/** @var initWithTemporaryProof:phoneNumber: + @brief Designated Initializer. + @param providerID The provider ID associated with the phone auth credential being created. + */ +- (instancetype)initWithTemporaryProof:(NSString *)temporaryProof + phoneNumber:(NSString *)phoneNumber + providerID:(NSString *)providerID NS_DESIGNATED_INITIALIZER; + +/** @var initWithProviderID:verificationID:verificationCode: + @brief Designated Initializer. + @param providerID The provider ID associated with the phone auth credential being created. + @param verificationID The verification ID associated witht Phone Auth credential being created. + @param verificationCode The verification code associated witht Phone Auth credential being + created. + */ +- (instancetype)initWithProviderID:(NSString *)providerID + verificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthProvider.m new file mode 100644 index 0000000..e2fd990 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthProvider.m @@ -0,0 +1,519 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRPhoneAuthProvider.h" + +#import +#import "FIRPhoneAuthCredential_Internal.h" +#import +#import "FIRAuthAPNSToken.h" +#import "FIRAuthAPNSTokenManager.h" +#import "FIRAuthAppCredential.h" +#import "FIRAuthAppCredentialManager.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FIRAuth_Internal.h" +#import "FIRAuthURLPresenter.h" +#import "FIRAuthNotificationManager.h" +#import "FIRAuthErrorUtils.h" +#import "FIRAuthBackend.h" +#import "FIRAuthSettings.h" +#import "FIRAuthWebUtils.h" +#import "FirebaseAuthVersion.h" +#import +#import "FIRGetProjectConfigRequest.h" +#import "FIRGetProjectConfigResponse.h" +#import "FIRSendVerificationCodeRequest.h" +#import "FIRSendVerificationCodeResponse.h" +#import "FIRVerifyClientRequest.h" +#import "FIRVerifyClientResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRReCAPTCHAURLCallBack + @brief The callback invoked at the end of the flow to fetch a reCAPTCHA URL. + @param reCAPTCHAURL The reCAPTCHA URL. + @param error The error that occurred while fetching the reCAPTCHAURL, if any. + */ +typedef void (^FIRReCAPTCHAURLCallBack)(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error); + +/** @typedef FIRVerifyClientCallback + @brief The callback invoked at the end of a client verification flow. + @param appCredential credential that proves the identity of the app during a phone + authentication flow. + @param error The error that occurred while verifying the app, if any. + */ +typedef void (^FIRVerifyClientCallback)(FIRAuthAppCredential *_Nullable appCredential, + NSError *_Nullable error); + +/** @typedef FIRFetchAuthDomainCallback + @brief The callback invoked at the end of the flow to fetch the Auth domain. + @param authDomain The Auth domain. + @param error The error that occurred while fetching the auth domain, if any. + */ +typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain, + NSError *_Nullable error); +/** @var kAuthDomainSuffix + @brief The suffix of the auth domain pertiaining to a given Firebase project. + */ +static NSString *const kAuthDomainSuffix = @"firebaseapp.com"; + +/** @var kauthTypeVerifyApp + @brief The auth type to be specified in the app verification request. + */ +static NSString *const kAuthTypeVerifyApp = @"verifyApp"; + +/** @var kReCAPTCHAURLStringFormat + @brief The format of the URL used to open the reCAPTCHA page during app verification. + */ +NSString *const kReCAPTCHAURLStringFormat = @"https://%@/__/auth/handler?"; + +@implementation FIRPhoneAuthProvider { + + /** @var _auth + @brief The auth instance used for verifying the phone number. + */ + FIRAuth *_auth; + + /** @var _callbackScheme + @brief The callback URL scheme used for reCAPTCHA fallback. + */ + NSString *_callbackScheme; +} + +/** @fn initWithAuth: + @brief returns an instance of @c FIRPhoneAuthProvider associated with the provided auth + instance. + @return An Instance of @c FIRPhoneAuthProvider. + */ +- (nullable instancetype)initWithAuth:(FIRAuth *)auth { + self = [super init]; + if (self) { + _auth = auth; + _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."] + reverseObjectEnumerator].allObjects componentsJoinedByString:@"."]; + } + return self; +} + +- (void)verifyPhoneNumber:(NSString *)phoneNumber + UIDelegate:(nullable id)UIDelegate + completion:(nullable FIRVerificationResultCallback)completion { + if (![self isCallbackSchemeRegistered]) { + [NSException raise:NSInternalInconsistencyException + format:@"Please register custom URL scheme '%@' in the app's Info.plist file.", + _callbackScheme]; + } + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRVerificationResultCallback callBackOnMainThread = ^(NSString *_Nullable verificationID, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(verificationID, error); + }); + } + }; + [self internalVerifyPhoneNumber:phoneNumber completion:^(NSString *_Nullable verificationID, + NSError *_Nullable error) { + if (!error) { + callBackOnMainThread(verificationID, nil); + return; + } + NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey]; + BOOL isInvalidAppCredential = error.code == FIRAuthErrorCodeInternalError && + underlyingError.code == FIRAuthErrorCodeInvalidAppCredential; + if (error.code != FIRAuthErrorCodeMissingAppToken && !isInvalidAppCredential) { + callBackOnMainThread(nil, error); + return; + } + NSMutableString *eventID = [[NSMutableString alloc] init]; + for (int i=0; i<10; i++) { + [eventID appendString: + [NSString stringWithFormat:@"%c", 'a' + arc4random_uniform('z' - 'a' + 1)]]; + } + [self reCAPTCHAURLWithEventID:eventID completion:^(NSURL *_Nullable reCAPTCHAURL, + NSError *_Nullable error) { + if (error) { + callBackOnMainThread(nil, error); + return; + } + FIRAuthURLCallbackMatcher callbackMatcher = ^BOOL(NSURL *_Nullable callbackURL) { + return [self isVerifyAppURL:callbackURL eventID:eventID]; + }; + [self->_auth.authURLPresenter presentURL:reCAPTCHAURL + UIDelegate:UIDelegate + callbackMatcher:callbackMatcher + completion:^(NSURL *_Nullable callbackURL, + NSError *_Nullable error) { + if (error) { + callBackOnMainThread(nil, error); + return; + } + NSError *reCAPTCHAError; + NSString *reCAPTCHAToken = [self reCAPTCHATokenForURL:callbackURL error:&reCAPTCHAError]; + if (!reCAPTCHAToken) { + callBackOnMainThread(nil, reCAPTCHAError); + return; + } + FIRSendVerificationCodeRequest *request = + [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber + appCredential:nil + reCAPTCHAToken:reCAPTCHAToken + requestConfiguration: + self->_auth.requestConfiguration]; + [FIRAuthBackend sendVerificationCode:request + callback:^(FIRSendVerificationCodeResponse + *_Nullable response, NSError *_Nullable error) { + if (error) { + callBackOnMainThread(nil, error); + return; + } + callBackOnMainThread(response.verificationID, nil); + }]; + }]; + }]; + }]; + }); +} + +- (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode { + return [[FIRPhoneAuthCredential alloc] initWithProviderID:FIRPhoneAuthProviderID + verificationID:verificationID + verificationCode:verificationCode]; +} + ++ (instancetype)provider { + return [[self alloc]initWithAuth:[FIRAuth auth]]; +} + ++ (instancetype)providerWithAuth:(FIRAuth *)auth { + return [[self alloc]initWithAuth:auth]; +} + +#pragma mark - Internal Methods + +/** @fn isCallbackSchemeRegistered + @brief Checks whether or not the expected callback scheme has been registered by the app. + @remarks This method is thread-safe. + */ +- (BOOL)isCallbackSchemeRegistered { + NSString *expectedCustomScheme = [_callbackScheme lowercaseString]; + NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"]; + for (NSDictionary *urlType in urlTypes) { + NSArray *urlTypeSchemes = urlType[@"CFBundleURLSchemes"]; + for (NSString *urlTypeScheme in urlTypeSchemes) { + if ([urlTypeScheme.lowercaseString isEqualToString:expectedCustomScheme]) { + return YES; + } + } + } + return NO; +} + +/** @fn reCAPTCHATokenForURL:error: + @brief Parses the reCAPTCHA URL and returns. + @param URL The url to be parsed for a reCAPTCHA token. + @param error The error that occurred if any. + @return The reCAPTCHA token if successful. + */ +- (NSString *)reCAPTCHATokenForURL:(NSURL *)URL error:(NSError **)error { + NSURLComponents *actualURLComponents = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + NSArray *queryItems = [actualURLComponents queryItems]; + NSString *deepLinkURL = [FIRAuthWebUtils queryItemValue:@"deep_link_id" from:queryItems]; + NSData *errorData; + if (deepLinkURL) { + actualURLComponents = [NSURLComponents componentsWithString:deepLinkURL]; + queryItems = [actualURLComponents queryItems]; + NSString *recaptchaToken = [FIRAuthWebUtils queryItemValue:@"recaptchaToken" from:queryItems]; + if (recaptchaToken) { + return recaptchaToken; + } + NSString *firebaseError = [FIRAuthWebUtils queryItemValue:@"firebaseError" from:queryItems]; + errorData = [firebaseError dataUsingEncoding:NSUTF8StringEncoding]; + } else { + errorData = nil; + } + NSError *jsonError; + NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData + options:0 + error:&jsonError]; + if (jsonError) { + *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError]; + return nil; + } + *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"] + message:errorDict[@"message"]]; + if (!*error) { + NSString *reason; + if(errorDict[@"code"] && errorDict[@"message"]) { + reason = [NSString stringWithFormat:@"[%@] - %@",errorDict[@"code"], errorDict[@"message"]]; + } else { + reason = [NSString stringWithFormat:@"An unknown error occurred with the following " + "response: %@", deepLinkURL]; + } + *error = [FIRAuthErrorUtils appVerificationUserInteractionFailureWithReason:reason]; + } + return nil; +} + +/** @fn isVerifyAppURL: + @brief Parses a URL into all available query items. + @param URL The url to be checked against the authType string. + @return Whether or not the URL matches authType. + */ +- (BOOL)isVerifyAppURL:(nullable NSURL *)URL eventID:(NSString *)eventID { + if (!URL) { + return NO; + } + NSURLComponents *actualURLComponents = + [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + actualURLComponents.query = nil; + actualURLComponents.fragment = nil; + + NSURLComponents *expectedURLComponents = [NSURLComponents new]; + expectedURLComponents.scheme = _callbackScheme; + expectedURLComponents.host = @"firebaseauth"; + expectedURLComponents.path = @"/link"; + + if (!([[expectedURLComponents URL] isEqual:[actualURLComponents URL]])) { + return NO; + } + actualURLComponents = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + NSArray *queryItems = [actualURLComponents queryItems]; + NSString *deepLinkURL = [FIRAuthWebUtils queryItemValue:@"deep_link_id" from:queryItems]; + if (deepLinkURL == nil) { + return NO; + } + NSURLComponents *deepLinkURLComponents = [NSURLComponents componentsWithString:deepLinkURL]; + NSArray *deepLinkQueryItems = [deepLinkURLComponents queryItems]; + + NSString *deepLinkAuthType = [FIRAuthWebUtils queryItemValue:@"authType" from:deepLinkQueryItems]; + NSString *deepLinkEventID = [FIRAuthWebUtils queryItemValue:@"eventId" from:deepLinkQueryItems]; + if ([deepLinkAuthType isEqualToString:kAuthTypeVerifyApp] && + [deepLinkEventID isEqualToString:eventID]) { + return YES; + } + return NO; +} + +/** @fn internalVerifyPhoneNumber:completion: + @brief Starts the phone number authentication flow by sending a verifcation code to the + specified phone number. + @param phoneNumber The phone number to be verified. + @param completion The callback to be invoked when the verification flow is finished. + */ + +- (void)internalVerifyPhoneNumber:(NSString *)phoneNumber + completion:(nullable FIRVerificationResultCallback)completion { + if (!phoneNumber.length) { + completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]); + return; + } + [_auth.notificationManager checkNotificationForwardingWithCallback: + ^(BOOL isNotificationBeingForwarded) { + if (!isNotificationBeingForwarded) { + completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]); + return; + } + FIRVerificationResultCallback callback = ^(NSString *_Nullable verificationID, + NSError *_Nullable error) { + if (completion) { + completion(verificationID, error); + } + }; + [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber + retryOnInvalidAppCredential:YES + callback:callback]; + }]; +} + +/** @fn verifyClientAndSendVerificationCodeToPhoneNumber:retryOnInvalidAppCredential:callback: + @brief Starts the flow to verify the client via silent push notification. + @param retryOnInvalidAppCredential Whether of not the flow should be retried if an + FIRAuthErrorCodeInvalidAppCredential error is returned from the backend. + @param phoneNumber The phone number to be verified. + @param callback The callback to be invoked on the global work queue when the flow is + finished. + */ +- (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber + retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential + callback:(FIRVerificationResultCallback)callback { + if (_auth.settings.isAppVerificationDisabledForTesting) { + FIRSendVerificationCodeRequest *request = + [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber + appCredential:nil + reCAPTCHAToken:nil + requestConfiguration: + _auth.requestConfiguration]; + [FIRAuthBackend sendVerificationCode:request + callback:^(FIRSendVerificationCodeResponse *_Nullable response, + NSError *_Nullable error) { + callback(response.verificationID, error); + }]; + return; + } + [self verifyClientWithCompletion:^(FIRAuthAppCredential *_Nullable appCredential, + NSError *_Nullable error) { + if (error) { + callback(nil, error); + return; + } + FIRSendVerificationCodeRequest *request = + [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber + appCredential:appCredential + reCAPTCHAToken:nil + requestConfiguration: + self->_auth.requestConfiguration]; + [FIRAuthBackend sendVerificationCode:request + callback:^(FIRSendVerificationCodeResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + if (error.code == FIRAuthErrorCodeInvalidAppCredential) { + if (retryOnInvalidAppCredential) { + [self->_auth.appCredentialManager clearCredential]; + [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber + retryOnInvalidAppCredential:NO + callback:callback]; + return; + } + callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:nil + underlyingError:error]); + return; + } + callback(nil, error); + return; + } + callback(response.verificationID, nil); + }]; + }]; +} + +/** @fn verifyClientWithCompletion:completion: + @brief Continues the flow to verify the client via silent push notification. + @param completion The callback to be invoked when the client verification flow is finished. + */ +- (void)verifyClientWithCompletion:(FIRVerifyClientCallback)completion { + if (_auth.appCredentialManager.credential) { + completion(_auth.appCredentialManager.credential, nil); + return; + } + [_auth.tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token, + NSError *_Nullable error) { + if (!token) { + completion(nil, [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:error]); + return; + } + FIRVerifyClientRequest *request = + [[FIRVerifyClientRequest alloc] initWithAppToken:token.string + isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox + requestConfiguration:self->_auth.requestConfiguration]; + [FIRAuthBackend verifyClient:request callback:^(FIRVerifyClientResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + completion(nil, error); + return; + } + NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow]; + [self->_auth.appCredentialManager + didStartVerificationWithReceipt:response.receipt + timeout:timeout + callback:^(FIRAuthAppCredential *credential) { + if (!credential.secret) { + FIRLogWarning(kFIRLoggerAuth, @"I-AUT000014", + @"Failed to receive remote notification to verify app identity within " + @"%.0f second(s)", timeout); + } + completion(credential, nil); + }]; + }]; + }]; +} + +/** @fn reCAPTCHAURLWithEventID:completion: + @brief Constructs a URL used for opening a reCAPTCHA app verification flow using a given event + ID. + @param eventID The event ID used for this purpose. + @param completion The callback invoked after the URL has been constructed or an error + has been encountered. + */ +- (void)reCAPTCHAURLWithEventID:(NSString *)eventID completion:(FIRReCAPTCHAURLCallBack)completion { + [self fetchAuthDomainWithCompletion:^(NSString *_Nullable authDomain, + NSError *_Nullable error) { + if (error) { + completion(nil, error); + return; + } + NSString *bundleID = [NSBundle mainBundle].bundleIdentifier; + NSString *clientID = self->_auth.app.options.clientID; + NSString *apiKey = self->_auth.requestConfiguration.APIKey; + NSMutableArray *queryItems = [@[ + [NSURLQueryItem queryItemWithName:@"apiKey" value:apiKey], + [NSURLQueryItem queryItemWithName:@"authType" value:kAuthTypeVerifyApp], + [NSURLQueryItem queryItemWithName:@"ibi" value:bundleID ?: @""], + [NSURLQueryItem queryItemWithName:@"clientId" value:clientID], + [NSURLQueryItem queryItemWithName:@"v" value:[FIRAuthBackend authUserAgent]], + [NSURLQueryItem queryItemWithName:@"eventId" value:eventID] + ] mutableCopy + ]; + + if (self->_auth.requestConfiguration.languageCode) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:@"hl"value: + self->_auth.requestConfiguration.languageCode]]; + } + NSURLComponents *components = [[NSURLComponents alloc] initWithString: + [NSString stringWithFormat:kReCAPTCHAURLStringFormat, authDomain]]; + [components setQueryItems:queryItems]; + completion([components URL], nil); + }]; +} + +/** @fn fetchAuthDomainWithCompletion:completion: + @brief Fetches the auth domain associated with the Firebase Project. + @param completion The callback invoked after the auth domain has been constructed or an error + has been encountered. + */ +- (void)fetchAuthDomainWithCompletion:(FIRFetchAuthDomainCallback)completion { + FIRGetProjectConfigRequest *request = + [[FIRGetProjectConfigRequest alloc] initWithRequestConfiguration:_auth.requestConfiguration]; + + [FIRAuthBackend getProjectConfig:request + callback:^(FIRGetProjectConfigResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + completion(nil, error); + return; + } + NSString *authDomain; + for (NSString *domain in response.authorizedDomains) { + NSInteger index = domain.length - kAuthDomainSuffix.length; + if (index >= 2) { + if ([domain hasSuffix:kAuthDomainSuffix] && domain.length >= kAuthDomainSuffix.length + 2) { + authDomain = domain; + break; + } + } + } + if (!authDomain.length) { + completion(nil, [FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:response]); + return; + } + completion(authDomain, nil); + }]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.h new file mode 100644 index 0000000..0ff44fa --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.h @@ -0,0 +1,48 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRTwitterAuthCredential + @brief Internal implementation of FIRAuthCredential for Twitter credentials. + */ +@interface FIRTwitterAuthCredential : FIRAuthCredential + +/** @property token + @brief The Twitter OAuth token. + */ +@property(nonatomic, readonly) NSString *token; + +/** @property secret + @brief The Twitter OAuth secret. + */ +@property(nonatomic, readonly) NSString *secret; + +/** @fn initWithToken:secret: + @brief Designated initializer. + @param token The Twitter OAuth token. + @param secret The Twitter OAuth secret. + */ +- (nullable instancetype)initWithToken:(NSString *)token secret:(NSString *)secret + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.m new file mode 100644 index 0000000..6772d6f --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.m @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRTwitterAuthCredential.h" + +#import "FIRTwitterAuthProvider.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRVerifyAssertionRequest.h" + +@interface FIRTwitterAuthCredential () + +- (nullable instancetype)initWithProvider:(NSString *)provider NS_UNAVAILABLE; + +@end + +@implementation FIRTwitterAuthCredential + +- (nullable instancetype)initWithProvider:(NSString *)provider { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"Please call the designated initializer."]; + return nil; +} + +- (nullable instancetype)initWithToken:(NSString *)token secret:(NSString *)secret { + self = [super initWithProvider:FIRTwitterAuthProviderID]; + if (self) { + _token = [token copy]; + _secret = [secret copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + request.providerAccessToken = _token; + request.providerOAuthTokenSecret = _secret; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthProvider.m new file mode 100644 index 0000000..5d738ce --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthProvider.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRTwitterAuthProvider.h" + +#import "FIRTwitterAuthCredential.h" +#import "FIRAuthExceptionUtils.h" + +// FIRTwitterAuthProviderID is defined in FIRAuthProvider.m. + +@implementation FIRTwitterAuthProvider + +- (instancetype)init { + [FIRAuthExceptionUtils raiseMethodNotImplementedExceptionWithReason: + @"This class is not meant to be initialized."]; + return nil; +} + ++ (FIRAuthCredential *)credentialWithToken:(NSString *)token secret:(NSString *)secret { + return [[FIRTwitterAuthCredential alloc] initWithToken:token secret:secret]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRActionCodeSettings.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRActionCodeSettings.m new file mode 100644 index 0000000..02807ff --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRActionCodeSettings.m @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "FIRActionCodeSettings.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRActionCodeSettings + +- (instancetype)init { + self = [super init]; + if (self) { + _iOSBundleID = [NSBundle mainBundle].bundleIdentifier; + } + return self; +} + +- (void)setIOSBundleID:(NSString *)iOSBundleID { + _iOSBundleID = [iOSBundleID copy]; + } + +- (void)setAndroidPackageName:(NSString *)androidPackageName + installIfNotAvailable:(BOOL)installIfNotAvailable + minimumVersion:(nullable NSString *)minimumVersion { + _androidPackageName = [androidPackageName copy]; + _androidInstallIfNotAvailable = installIfNotAvailable; + _androidMinimumVersion = [minimumVersion copy]; + } + + @end + + NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo.m new file mode 100644 index 0000000..c6ba37c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo.m @@ -0,0 +1,98 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAdditionalUserInfo_Internal.h" + +#import "FIRVerifyAssertionResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAdditionalUserInfo + +/** @var kProviderIDCodingKey + @brief The key used to encode the providerID property for NSSecureCoding. + */ +static NSString *const kProviderIDCodingKey = @"providerID"; + +/** @var kProfileCodingKey + @brief The key used to encode the profile property for NSSecureCoding. + */ +static NSString *const kProfileCodingKey = @"profile"; + +/** @var kUsernameCodingKey + @brief The key used to encode the username property for NSSecureCoding. + */ +static NSString *const kUsernameCodingKey = @"username"; + +/** @var kNewUserKey + @brief The key used to encode the newUser property for NSSecureCoding. + */ +static NSString *const kNewUserKey = @"newUser"; + ++ (nullable instancetype)userInfoWithVerifyAssertionResponse: + (FIRVerifyAssertionResponse *)verifyAssertionResponse { + return [[self alloc] initWithProviderID:verifyAssertionResponse.providerID + profile:verifyAssertionResponse.profile + username:verifyAssertionResponse.username + isNewUser:verifyAssertionResponse.isNewUser]; +} + +- (nullable instancetype)initWithProviderID:(nullable NSString *)providerID + profile:(nullable NSDictionary *)profile + username:(nullable NSString *)username + isNewUser:(BOOL)isNewUser { + self = [super init]; + if (self) { + _providerID = [providerID copy]; + if (profile) { + _profile = [[NSDictionary alloc] initWithDictionary:profile copyItems:YES]; + } + _username = [username copy]; + _newUser = isNewUser; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *providerID = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kProviderIDCodingKey]; + NSDictionary *profile = + [aDecoder decodeObjectOfClass:[NSDictionary class] forKey:kProfileCodingKey]; + NSString *username = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUsernameCodingKey]; + NSNumber *isNewUser = [aDecoder decodeObjectOfClass:[NSNumber class] forKey:kNewUserKey]; + + return [self initWithProviderID:providerID + profile:profile + username:username + isNewUser:isNewUser.boolValue]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_providerID forKey:kProviderIDCodingKey]; + [aCoder encodeObject:_profile forKey:kProfileCodingKey]; + [aCoder encodeObject:_username forKey:kUsernameCodingKey]; + [aCoder encodeObject:[NSNumber numberWithBool:_newUser] forKey:kNewUserKey]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo_Internal.h new file mode 100644 index 0000000..c8e345d --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAdditionalUserInfo_Internal.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAdditionalUserInfo.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAdditionalUserInfo () + +/** @fn userInfoWithVerifyAssertionResponse: + @brief A convenience factory method for constructing a @c FIRAdditionalUserInfo instance from + data returned by the verifyAssertion endpoint. + @param verifyAssertionResponse Data returned by the verifyAssertion endpoint. + @return A new instance of @c FIRAdditionalUserInfo using data from the verifyAssertion endpoint. + */ ++ (nullable instancetype)userInfoWithVerifyAssertionResponse: + (FIRVerifyAssertionResponse *)verifyAssertionResponse; + +/** @fn initWithProviderID:profile:username: + @brief Designated initializer. + @param providerID The provider identifier. + @param profile Dictionary containing the additional IdP specific information. + @param username The name of the user. + @param isNewUser Indicates whether or not the current user was signed in for the first time. + */ +- (nullable instancetype)initWithProviderID:(nullable NSString *)providerID + profile:(nullable NSDictionary *)profile + username:(nullable NSString *)username + isNewUser:(BOOL)isNewUser NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth.m new file mode 100644 index 0000000..0697026 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth.m @@ -0,0 +1,1953 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuth_Internal.h" + +#if __has_include() +#import +#endif + +#import +#import +#import +#import +#import +#import +#import +#import +#import + +#import "AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h" +#import "FIRAdditionalUserInfo_Internal.h" +#import "FIRAuthCredential_Internal.h" +#import "FIRAuthDataResult_Internal.h" +#import "FIRAuthDispatcher.h" +#import "FIRAuthErrorUtils.h" +#import "FIRAuthExceptionUtils.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FIRAuthKeychain.h" +#import "FIRAuthOperationType.h" +#import "FIRAuthSettings.h" +#import "FIRUser_Internal.h" +#import "FirebaseAuth.h" +#import "FIRAuthBackend.h" +#import "FIRAuthRequestConfiguration.h" +#import "FIRCreateAuthURIRequest.h" +#import "FIRCreateAuthURIResponse.h" +#import "FIREmailLinkSignInRequest.h" +#import "FIREmailLinkSignInResponse.h" +#import "FIRGameCenterAuthCredential.h" +#import "FIRGetOOBConfirmationCodeRequest.h" +#import "FIRGetOOBConfirmationCodeResponse.h" +#import "FIRResetPasswordRequest.h" +#import "FIRResetPasswordResponse.h" +#import "FIRSendVerificationCodeRequest.h" +#import "FIRSendVerificationCodeResponse.h" +#import "FIRSetAccountInfoRequest.h" +#import "FIRSetAccountInfoResponse.h" +#import "FIRSignInWithGameCenterRequest.h" +#import "FIRSignInWithGameCenterResponse.h" +#import "FIRSignUpNewUserRequest.h" +#import "FIRSignUpNewUserResponse.h" +#import "FIRVerifyAssertionRequest.h" +#import "FIRVerifyAssertionResponse.h" +#import "FIRVerifyCustomTokenRequest.h" +#import "FIRVerifyCustomTokenResponse.h" +#import "FIRVerifyPasswordRequest.h" +#import "FIRVerifyPasswordResponse.h" +#import "FIRVerifyPhoneNumberRequest.h" +#import "FIRVerifyPhoneNumberResponse.h" + +#if TARGET_OS_IOS +#import "FIRAuthAPNSToken.h" +#import "FIRAuthAPNSTokenManager.h" +#import "FIRAuthAppCredentialManager.h" +#import "FIRAuthAppDelegateProxy.h" +#import "AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h" +#import "FIRAuthNotificationManager.h" +#import "FIRAuthURLPresenter.h" +#endif + +#pragma mark - Constants + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +const NSNotificationName FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification"; +#else +NSString *const FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification"; +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +/** @var kMaxWaitTimeForBackoff + @brief The maximum wait time before attempting to retry auto refreshing tokens after a failed + attempt. + @remarks This is the upper limit (in seconds) of the exponential backoff used for retrying + token refresh. + */ +static NSTimeInterval kMaxWaitTimeForBackoff = 16 * 60; + +/** @var kTokenRefreshHeadStart + @brief The amount of time before the token expires that proactive refresh should be attempted. + */ +NSTimeInterval kTokenRefreshHeadStart = 5 * 60; + +/** @var kUserKey + @brief Key of user stored in the keychain. Prefixed with a Firebase app name. + */ +static NSString *const kUserKey = @"%@_firebase_user"; + +/** @var kMissingEmailInvalidParameterExceptionReason + @brief The reason for @c invalidParameterException when the email used to initiate password + reset is nil. + */ +static NSString *const kMissingEmailInvalidParameterExceptionReason = + @"The email used to initiate password reset cannot be nil."; + +/** @var kHandleCodeInAppFalseExceptionReason + @brief The reason for @c invalidParameterException when the handleCodeInApp parameter is false + on the ActionCodeSettings object used to send the link for Email-link Authentication. + */ +static NSString *const kHandleCodeInAppFalseExceptionReason = + @"You must set handleCodeInApp in your ActionCodeSettings to true for Email-link " + "Authentication."; + +static NSString *const kInvalidEmailSignInLinkExceptionMessage = + @"The link provided is not valid for email/link sign-in. Please check the link by calling " + "isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in."; + +/** @var kPasswordResetRequestType + @brief The action code type value for resetting password in the check action code response. + */ +static NSString *const kPasswordResetRequestType = @"PASSWORD_RESET"; + +/** @var kVerifyEmailRequestType + @brief The action code type value for verifying email in the check action code response. + */ +static NSString *const kVerifyEmailRequestType = @"VERIFY_EMAIL"; + +/** @var kRecoverEmailRequestType + @brief The action code type value for recovering email in the check action code response. + */ +static NSString *const kRecoverEmailRequestType = @"RECOVER_EMAIL"; + +/** @var kEmailLinkSignInRequestType + @brief The action code type value for an email sign-in link in the check action code response. +*/ +static NSString *const kEmailLinkSignInRequestType = @"EMAIL_SIGNIN"; + +/** @var kMissingPasswordReason + @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown. + @remarks This error message will be localized in the future. + */ +static NSString *const kMissingPasswordReason = @"Missing Password"; + +/** @var gKeychainServiceNameForAppName + @brief A map from Firebase app name to keychain service names. + @remarks This map is needed for looking up the keychain service name after the FIRApp instance + is deleted, to remove the associated keychain item. Accessing should occur within a + @syncronized([FIRAuth class]) context. + */ +static NSMutableDictionary *gKeychainServiceNameForAppName; + +#pragma mark - FIRActionCodeInfo + +@implementation FIRActionCodeInfo { + /** @var _email + @brief The email address to which the code was sent. The new email address in the case of + FIRActionCodeOperationRecoverEmail. + */ + NSString *_email; + + /** @var _fromEmail + @brief The current email address in the case of FIRActionCodeOperationRecoverEmail. + */ + NSString *_fromEmail; +} + +- (NSString *)dataForKey:(FIRActionDataKey)key{ + switch (key) { + case FIRActionCodeEmailKey: + return _email; + case FIRActionCodeFromEmailKey: + return _fromEmail; + } +} + +- (instancetype)initWithOperation:(FIRActionCodeOperation)operation + email:(NSString *)email + newEmail:(nullable NSString *)newEmail { + self = [super init]; + if (self) { + _operation = operation; + if (newEmail) { + _email = [newEmail copy]; + _fromEmail = [email copy]; + } else { + _email = [email copy]; + } + } + return self; +} + +/** @fn actionCodeOperationForRequestType: + @brief Returns the corresponding operation type per provided request type string. + @param requestType Request type returned in in the server response. + @return The corresponding FIRActionCodeOperation for the supplied request type. + */ ++ (FIRActionCodeOperation)actionCodeOperationForRequestType:(NSString *)requestType { + if ([requestType isEqualToString:kPasswordResetRequestType]) { + return FIRActionCodeOperationPasswordReset; + } + if ([requestType isEqualToString:kVerifyEmailRequestType]) { + return FIRActionCodeOperationVerifyEmail; + } + if ([requestType isEqualToString:kRecoverEmailRequestType]) { + return FIRActionCodeOperationRecoverEmail; + } + if ([requestType isEqualToString:kEmailLinkSignInRequestType]) { + return FIRActionCodeOperationEmailLink; + } + return FIRActionCodeOperationUnknown; +} + +@end + +#pragma mark - FIRAuth + +#if TARGET_OS_IOS +@interface FIRAuth () +#else +@interface FIRAuth () +#endif + +/** @property firebaseAppId + @brief The Firebase app ID. + */ +@property(nonatomic, copy, readonly) NSString *firebaseAppId; + +/** @property additionalFrameworkMarker + @brief Additional framework marker that will be added as part of the header of every request. + */ +@property(nonatomic, copy, nullable) NSString *additionalFrameworkMarker; + +/** @fn initWithApp: + @brief Creates a @c FIRAuth instance associated with the provided @c FIRApp instance. + @param app The application to associate the auth instance with. + */ +- (instancetype)initWithApp:(FIRApp *)app; + +@end + +@implementation FIRAuth { + /** @var _currentUser + @brief The current user. + */ + FIRUser *_currentUser; + + /** @var _firebaseAppName + @brief The Firebase app name. + */ + NSString *_firebaseAppName; + + /** @var _listenerHandles + @brief Handles returned from @c NSNotificationCenter for blocks which are "auth state did + change" notification listeners. + @remarks Mutations should occur within a @syncronized(self) context. + */ + NSMutableArray *_listenerHandles; + + /** @var _keychain + @brief The keychain service. + */ + FIRAuthKeychain *_keychain; + + /** @var _lastNotifiedUserToken + @brief The user access (ID) token used last time for posting auth state changed notification. + */ + NSString *_lastNotifiedUserToken; + + /** @var _autoRefreshTokens + @brief This flag denotes whether or not tokens should be automatically refreshed. + @remarks Will only be set to @YES if the another Firebase service is included (additionally to + Firebase Auth). + */ + BOOL _autoRefreshTokens; + + /** @var _autoRefreshScheduled + @brief Whether or not token auto-refresh is currently scheduled. + */ + BOOL _autoRefreshScheduled; + + /** @var _isAppInBackground + @brief A flag that is set to YES if the app is put in the background and no when the app is + returned to the foreground. + */ + BOOL _isAppInBackground; + + /** @var _applicationDidBecomeActiveObserver + @brief An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification. + */ + id _applicationDidBecomeActiveObserver; + + /** @var _applicationDidBecomeActiveObserver + @brief An opaque object to act as the observer for + UIApplicationDidEnterBackgroundNotification. + */ + id _applicationDidEnterBackgroundObserver; +} + ++ (void)load { + [FIRComponentContainer registerAsComponentRegistrant:self]; + [FIRApp registerAsConfigurable:self]; +} + ++ (void)initialize { + gKeychainServiceNameForAppName = [[NSMutableDictionary alloc] init]; +} + ++ (FIRAuth *)auth { + FIRApp *defaultApp = [FIRApp defaultApp]; + if (!defaultApp) { + [NSException raise:NSInternalInconsistencyException + format:@"The default FIRApp instance must be configured before the default FIRAuth" + @"instance can be initialized. One way to ensure that is to call " + @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App " + @"Delegate's `application:didFinishLaunchingWithOptions:` " + @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."]; + } + return [self authWithApp:defaultApp]; +} + ++ (FIRAuth *)authWithApp:(FIRApp *)app { + // Get the instance of Auth from the container, which will create or return the cached instance + // associated with this app. + id auth = FIR_COMPONENT(FIRAuthInterop, app.container); + return (FIRAuth *)auth; +} + +- (instancetype)initWithApp:(FIRApp *)app { + [FIRAuth setKeychainServiceNameForApp:app]; + self = [self initWithAPIKey:app.options.APIKey appName:app.name]; + if (self) { + _app = app; + #if TARGET_OS_IOS + _authURLPresenter = [[FIRAuthURLPresenter alloc] init]; + #endif + } + return self; +} + +- (instancetype)initWithAPIKey:(NSString *)APIKey appName:(NSString *)appName { + self = [super init]; + if (self) { + _listenerHandles = [NSMutableArray array]; + _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey]; + _settings = [[FIRAuthSettings alloc] init]; + _firebaseAppName = [appName copy]; + #if TARGET_OS_IOS + + static Class applicationClass = nil; + // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication + // responds to it. + if (![GULAppEnvironmentUtil isAppExtension]) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + UIApplication *application = [applicationClass sharedApplication]; + + // Initialize the shared FIRAuthAppDelegateProxy instance in the main thread if not already. + [FIRAuthAppDelegateProxy sharedInstance]; + #endif + + // Continue with the rest of initialization in the work thread. + __weak FIRAuth *weakSelf = self; + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + // Load current user from Keychain. + FIRAuth *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + NSString *keychainServiceName = + [FIRAuth keychainServiceNameForAppName:strongSelf->_firebaseAppName]; + if (keychainServiceName) { + strongSelf->_keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName]; + } + FIRUser *user; + NSError *error; + if ([strongSelf getUser:&user error:&error]) { + [strongSelf updateCurrentUser:user byForce:NO savingToDisk:NO error:&error]; + self->_lastNotifiedUserToken = user.rawAccessToken; + } else { + FIRLogError(kFIRLoggerAuth, @"I-AUT000001", + @"Error loading saved user when starting up: %@", error); + } + + #if TARGET_OS_IOS + // Initialize for phone number auth. + strongSelf->_tokenManager = + [[FIRAuthAPNSTokenManager alloc] initWithApplication:application]; + + strongSelf->_appCredentialManager = + [[FIRAuthAppCredentialManager alloc] initWithKeychain:strongSelf->_keychain]; + + strongSelf->_notificationManager = [[FIRAuthNotificationManager alloc] + initWithApplication:application + appCredentialManager:strongSelf->_appCredentialManager]; + + [[FIRAuthAppDelegateProxy sharedInstance] addHandler:strongSelf]; + #endif + }); + } + return self; +} + +- (void)dealloc { + @synchronized (self) { + NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; + while (_listenerHandles.count != 0) { + FIRAuthStateDidChangeListenerHandle handleToRemove = _listenerHandles.lastObject; + [defaultCenter removeObserver:handleToRemove]; + [_listenerHandles removeLastObject]; + } + + #if TARGET_OS_IOS + [defaultCenter removeObserver:_applicationDidBecomeActiveObserver + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [defaultCenter removeObserver:_applicationDidEnterBackgroundObserver + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + #endif + } +} + +#pragma mark - Public API + +- (FIRUser *)currentUser { + __block FIRUser *result; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = self->_currentUser; + }); + return result; +} + +- (void)fetchProvidersForEmail:(NSString *)email + completion:(FIRProviderQueryCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRCreateAuthURIRequest *request = + [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email + continueURI:@"http://www.google.com/" + requestConfiguration:self->_requestConfiguration]; + [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(response.allProviders, error); + }); + } + }]; + }); +} + +- (void)fetchSignInMethodsForEmail:(nonnull NSString *)email + completion:(nullable FIRSignInMethodQueryCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRCreateAuthURIRequest *request = + [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email + continueURI:@"http://www.google.com/" + requestConfiguration:self->_requestConfiguration]; + [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(response.signinMethods, error); + }); + } + }]; + }); +} + +- (void)signInWithEmail:(NSString *)email + password:(NSString *)password + completion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalSignInAndRetrieveDataWithEmail:email + password:password + completion:^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + decoratedCallback(authResult, error); + }]; + }); +} + +- (void)signInWithEmail:(NSString *)email + link:(NSString *)link + completion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + FIREmailPasswordAuthCredential *credential = + [[FIREmailPasswordAuthCredential alloc] initWithEmail:email link:link]; + [self internalSignInAndRetrieveDataWithCredential:credential + isReauthentication:NO + callback:^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + decoratedCallback(authResult, error); + }]; + }); +} + +/** @fn signInWithEmail:password:callback: + @brief Signs in using an email address and password. + @param email The user's email address. + @param password The user's password. + @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked + asynchronously on the global auth work queue in the future. + @remarks This is the internal counterpart of this method, which uses a callback that does not + update the current user. + */ +- (void)signInWithEmail:(NSString *)email + password:(NSString *)password + callback:(FIRAuthResultCallback)callback { + + FIRVerifyPasswordRequest *request = + [[FIRVerifyPasswordRequest alloc] initWithEmail:email + password:password + requestConfiguration:_requestConfiguration]; + + if (![request.password length]) { + callback(nil, [FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]); + return; + } + [FIRAuthBackend verifyPassword:request + callback:^(FIRVerifyPasswordResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + callback(nil, error); + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:callback]; + }]; +} + +- (void)signInAndRetrieveDataWithEmail:(NSString *)email + password:(NSString *)password + completion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalSignInAndRetrieveDataWithEmail:email + password:password + completion:decoratedCallback]; + }); +} + +/** @fn internalSignInAndRetrieveDataWithEmail:password:callback: + @brief Signs in using an email address and password. + @param email The user's email address. + @param password The user's password. + @param completion A block which is invoked when the sign in finishes (or is cancelled.) Invoked + asynchronously on the global auth work queue in the future. + @remarks This is the internal counterpart of this method, which uses a callback that does not + update the current user. + */ +- (void)internalSignInAndRetrieveDataWithEmail:(NSString *)email + password:(NSString *)password + completion:(FIRAuthDataResultCallback)completion { + FIREmailPasswordAuthCredential *credentail = + [[FIREmailPasswordAuthCredential alloc] initWithEmail:email password:password]; + [self internalSignInAndRetrieveDataWithCredential:credentail + isReauthentication:NO + callback:completion]; +} + +/** @fn signInWithGameCenterCredential:callback: + @brief Signs in using a game center credential. + @param credential The Game Center Auth Credential used to sign in. + @param callback A block which is invoked when the sign in finished (or is cancelled). Invoked + asynchronously on the global auth work queue in the future. + */ +- (void)signInWithGameCenterCredential:(FIRGameCenterAuthCredential *)credential + callback:(FIRAuthResultCallback)callback { + FIRSignInWithGameCenterRequest *request = + [[FIRSignInWithGameCenterRequest alloc] initWithPlayerID:credential.playerID + publicKeyURL:credential.publicKeyURL + signature:credential.signature + salt:credential.salt + timestamp:credential.timestamp + displayName:credential.displayName + requestConfiguration:_requestConfiguration]; + [FIRAuthBackend signInWithGameCenter:request + callback:^(FIRSignInWithGameCenterResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + if (callback) { + callback(nil, error); + } + return; + } + + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:callback]; + }]; +} + +/** @fn internalSignInWithEmail:link:completion: + @brief Signs in using an email and email sign-in link. + @param email The user's email address. + @param link The email sign-in link. + @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked + asynchronously on the global auth work queue in the future. + */ +- (void)internalSignInWithEmail:(nonnull NSString *)email + link:(nonnull NSString *)link + callback:(nullable FIRAuthResultCallback)callback { + if (![self isSignInWithEmailLink:link]) { + [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason: + kInvalidEmailSignInLinkExceptionMessage]; + return; + } + NSDictionary *queryItems = FIRAuthParseURL(link); + if (![queryItems count]) { + NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link]; + queryItems = FIRAuthParseURL(urlComponents.query); + } + NSString *actionCode = queryItems[@"oobCode"]; + + FIREmailLinkSignInRequest *request = + [[FIREmailLinkSignInRequest alloc] initWithEmail:email + oobCode:actionCode + requestConfiguration:_requestConfiguration]; + + [FIRAuthBackend emailLinkSignin:request + callback:^(FIREmailLinkSignInResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + callback(nil, error); + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:callback]; + }]; +} + +- (void)signInWithCredential:(FIRAuthCredential *)credential + completion:(FIRAuthResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthResultCallback callback = + [self signInFlowAuthResultCallbackByDecoratingCallback:completion]; + [self internalSignInWithCredential:credential callback:callback]; + }); +} + +- (void)signInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback callback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalSignInAndRetrieveDataWithCredential:credential + isReauthentication:NO + callback:callback]; + }); +} + +- (void)internalSignInWithCredential:(FIRAuthCredential *)credential + callback:(FIRAuthResultCallback)callback { + [self internalSignInAndRetrieveDataWithCredential:credential + isReauthentication:NO + callback:^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + callback(authResult.user, error); + }]; +} + +- (void)internalSignInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential + isReauthentication:(BOOL)isReauthentication + callback:(nullable FIRAuthDataResultCallback)callback { + if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) { + // Special case for email/password credentials + FIREmailPasswordAuthCredential *emailPasswordCredential = + (FIREmailPasswordAuthCredential *)credential; + FIRAuthResultCallback completeEmailSignIn = ^(FIRUser *user, NSError *error) { + if (callback) { + if (error) { + callback(nil, error); + return; + } + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID + profile:nil + username:nil + isNewUser:NO]; + FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo]; + callback(result, error); + } + }; + if (emailPasswordCredential.link) { + [self internalSignInWithEmail:emailPasswordCredential.email + link:emailPasswordCredential.link + callback:completeEmailSignIn]; + } else { + [self signInWithEmail:emailPasswordCredential.email + password:emailPasswordCredential.password + callback:completeEmailSignIn]; + } + return; + } + + if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) { + // Special case for Game Center credentials. + [self signInWithGameCenterCredential:(FIRGameCenterAuthCredential *)credential + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + if (callback) { + FIRAuthDataResult *result; + if (user) { + result = [[FIRAuthDataResult alloc] initWithUser:user additionalUserInfo:nil]; + } + callback(result, error); + } + }]; + return; + } + + #if TARGET_OS_IOS + if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) { + // Special case for phone auth credentials + FIRPhoneAuthCredential *phoneCredential = (FIRPhoneAuthCredential *)credential; + FIRAuthOperationType operation = + isReauthentication ? FIRAuthOperationTypeReauth : FIRAuthOperationTypeSignUpOrSignIn; + [self signInWithPhoneCredential:phoneCredential + operation:operation + callback:^(FIRVerifyPhoneNumberResponse *_Nullable response, + NSError *_Nullable error) { + if (callback) { + if (error) { + callback(nil, error); + return; + } + + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:FIRPhoneAuthProviderID + profile:nil + username:nil + isNewUser:response.isNewUser]; + FIRAuthDataResult *result = user ? + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo] : nil; + callback(result, error); + }]; + } + }]; + return; + } + #endif + FIRVerifyAssertionRequest *request = + [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider + requestConfiguration:_requestConfiguration]; + request.autoCreate = !isReauthentication; + [credential prepareVerifyAssertionRequest:request]; + [FIRAuthBackend verifyAssertion:request + callback:^(FIRVerifyAssertionResponse *response, NSError *error) { + if (error) { + if (callback) { + callback(nil, error); + } + return; + } + + if (response.needConfirmation) { + if (callback) { + NSString *email = response.email; + callback(nil, [FIRAuthErrorUtils accountExistsWithDifferentCredentialErrorWithEmail:email]); + } + return; + } + + if (!response.providerID.length) { + if (callback) { + callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:response]); + } + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + if (callback) { + FIRAdditionalUserInfo *additionalUserInfo = + [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response]; + FIRAuthDataResult *result = user ? + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo] : nil; + callback(result, error); + } + }]; + }]; +} + +- (void)signInWithCredential:(FIRAuthCredential *)credential + callback:(FIRAuthResultCallback)callback { + [self signInAndRetrieveDataWithCredential:credential + completion:^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + callback(authResult.user, error); + }]; +} + +- (void)signInAnonymouslyAndRetrieveDataWithCompletion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + if (self->_currentUser.anonymous) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:nil + profile:nil + username:nil + isNewUser:NO]; + FIRAuthDataResult *authDataResult = + [[FIRAuthDataResult alloc] initWithUser:self->_currentUser + additionalUserInfo:additionalUserInfo]; + decoratedCallback(authDataResult, nil); + return; + } + [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + decoratedCallback(nil, error); + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:YES + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:nil + profile:nil + username:nil + isNewUser:YES]; + FIRAuthDataResult *authDataResult = + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo]; + decoratedCallback(authDataResult, nil); + }]; + }]; + }); +} + +- (void)signInAnonymouslyWithCompletion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + if (self->_currentUser.anonymous) { + FIRAuthDataResult *result = + [[FIRAuthDataResult alloc] initWithUser:self->_currentUser additionalUserInfo:nil]; + decoratedCallback(result, nil); + return; + } + [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + decoratedCallback(nil, error); + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:YES + callback:^(FIRUser * _Nullable user, NSError * _Nullable error) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID + profile:nil + username:nil + isNewUser:YES]; + FIRAuthDataResult *authDataResult = + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo]; + decoratedCallback(authDataResult, nil); + }]; + }]; + }); +} + +- (void)signInWithCustomToken:(NSString *)token + completion:(nullable FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalSignInAndRetrieveDataWithCustomToken:token + completion:^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + decoratedCallback(authResult, error); + }]; + }); +} + +- (void)signInAndRetrieveDataWithCustomToken:(NSString *)token + completion:(nullable FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalSignInAndRetrieveDataWithCustomToken:token completion:decoratedCallback]; + }); +} + +- (void)createUserWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalCreateUserWithEmail:email + password:password + completion:^(FIRSignUpNewUserResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + decoratedCallback(nil, error); + return; + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID + profile:nil + username:nil + isNewUser:YES]; + FIRAuthDataResult *authDataResult = + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo]; + decoratedCallback(authDataResult, nil); + }]; + }]; + }); +} + +- (void)createUserAndRetrieveDataWithEmail:(NSString *)email + password:(NSString *)password + completion:(FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuthDataResultCallback decoratedCallback = + [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion]; + [self internalCreateUserWithEmail:email + password:password + completion:^(FIRSignUpNewUserResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + decoratedCallback(nil, error); + return; + } + + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:^(FIRUser *_Nullable user, NSError *_Nullable error) { + FIRAdditionalUserInfo *additionalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID + profile:nil + username:nil + isNewUser:YES]; + FIRAuthDataResult *authDataResult = + [[FIRAuthDataResult alloc] initWithUser:user + additionalUserInfo:additionalUserInfo]; + decoratedCallback(authDataResult, nil); + }]; + }]; + }); +} + +- (void)confirmPasswordResetWithCode:(NSString *)code + newPassword:(NSString *)newPassword + completion:(FIRConfirmPasswordResetCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRResetPasswordRequest *request = + [[FIRResetPasswordRequest alloc] initWithOobCode:code + newPassword:newPassword + requestConfiguration:self->_requestConfiguration]; + [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + if (error) { + completion(error); + return; + } + completion(nil); + }); + } + }]; + }); +} + +- (void)checkActionCode:(NSString *)code completion:(FIRCheckActionCodeCallBack)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^ { + FIRResetPasswordRequest *request = + [[FIRResetPasswordRequest alloc] initWithOobCode:code + newPassword:nil + requestConfiguration:self->_requestConfiguration]; + [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + if (error) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + FIRActionCodeOperation operation = + [FIRActionCodeInfo actionCodeOperationForRequestType:response.requestType]; + FIRActionCodeInfo *actionCodeInfo = + [[FIRActionCodeInfo alloc] initWithOperation:operation + email:response.email + newEmail:response.verifiedEmail]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(actionCodeInfo, nil); + }); + } + }]; + }); +} + +- (void)verifyPasswordResetCode:(NSString *)code + completion:(FIRVerifyPasswordResetCodeCallback)completion { + [self checkActionCode:code completion:^(FIRActionCodeInfo *_Nullable info, + NSError *_Nullable error) { + if (completion) { + if (error) { + completion(nil, error); + return; + } + completion([info dataForKey:FIRActionCodeEmailKey], nil); + } + }]; +} + +- (void)applyActionCode:(NSString *)code completion:(FIRApplyActionCodeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^ { + FIRSetAccountInfoRequest *request = + [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:self->_requestConfiguration]; + request.OOBCode = code; + [FIRAuthBackend setAccountInfo:request callback:^(FIRSetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + }]; + }); +} + +- (void)sendPasswordResetWithEmail:(NSString *)email + completion:(nullable FIRSendPasswordResetCallback)completion { + [self sendPasswordResetWithNullableActionCodeSettings:nil email:email completion:completion]; +} + +- (void)sendPasswordResetWithEmail:(NSString *)email + actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendPasswordResetCallback)completion { + [self sendPasswordResetWithNullableActionCodeSettings:actionCodeSettings + email:email + completion:completion]; +} + +/** @fn sendPasswordResetWithNullableActionCodeSettings:actionCodeSetting:email:completion: + @brief Initiates a password reset for the given email address and @FIRActionCodeSettings object. + + @param actionCodeSettings Optionally, An @c FIRActionCodeSettings object containing settings + related to the handling action codes. + @param email The email address of the user. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + */ +- (void)sendPasswordResetWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *) + actionCodeSettings + email:(NSString *)email + completion:(nullable FIRSendPasswordResetCallback) + completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + if (!email) { + [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason: + kMissingEmailInvalidParameterExceptionReason]; + return; + } + FIRGetOOBConfirmationCodeRequest *request = + [FIRGetOOBConfirmationCodeRequest passwordResetRequestWithEmail:email + actionCodeSettings:actionCodeSettings + requestConfiguration:self->_requestConfiguration + ]; + [FIRAuthBackend getOOBConfirmationCode:request + callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + }]; + }); +} + +- (void)sendSignInLinkToEmail:(nonnull NSString *)email + actionCodeSettings:(nonnull FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendSignInLinkToEmailCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + if (!email) { + [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason: + kMissingEmailInvalidParameterExceptionReason]; + } + + if (!actionCodeSettings.handleCodeInApp) { + [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason: + kHandleCodeInAppFalseExceptionReason]; + } + FIRGetOOBConfirmationCodeRequest *request = + [FIRGetOOBConfirmationCodeRequest signInWithEmailLinkRequest:email + actionCodeSettings:actionCodeSettings + requestConfiguration:self->_requestConfiguration]; + [FIRAuthBackend getOOBConfirmationCode:request + callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + }]; + }); +} + +- (void)updateCurrentUser:(FIRUser *)user completion:(nullable FIRUserUpdateCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + if (!user) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion([FIRAuthErrorUtils nullUserErrorWithMessage:nil]); + }); + } + return; + } + void (^updateUserBlock)(FIRUser *user) = ^(FIRUser *user) { + NSError *error; + [self updateCurrentUser:user byForce:YES savingToDisk:YES error:(&error)]; + if (error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + return; + } if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil); + }); + } + }; + if (![user.requestConfiguration.APIKey isEqualToString:self->_requestConfiguration.APIKey]) { + // If the API keys are different, then we need to confirm that the user belongs to the same + // project before proceeding. + user.requestConfiguration = self->_requestConfiguration; + [user reloadWithCompletion:^(NSError *_Nullable error) { + if (error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(error); + }); + } + return; + } + updateUserBlock(user); + }]; + } else { + updateUserBlock(user); + } + }); +} + +- (BOOL)signOut:(NSError *_Nullable __autoreleasing *_Nullable)error { + __block BOOL result = YES; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + if (!self->_currentUser) { + return; + } + result = [self updateCurrentUser:nil byForce:NO savingToDisk:YES error:error]; + }); + return result; +} + +- (BOOL)signOutByForceWithUserID:(NSString *)userID error:(NSError *_Nullable *_Nullable)error { + if (_currentUser.uid != userID) { + return YES; + } + return [self updateCurrentUser:nil byForce:YES savingToDisk:YES error:error]; +} + +- (BOOL)isSignInWithEmailLink:(NSString *)link { + if (link.length == 0) { + return NO; + } + NSDictionary *queryItems = FIRAuthParseURL(link); + if (![queryItems count]) { + NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link]; + if (!urlComponents.query) { + return NO; + } + queryItems = FIRAuthParseURL(urlComponents.query); + } + + if (![queryItems count]) { + return NO; + } + + NSString *actionCode = queryItems[@"oobCode"]; + NSString *mode = queryItems[@"mode"]; + + if (actionCode && [mode isEqualToString:@"signIn"]) { + return YES; + } + return NO; +} + +/** @fn FIRAuthParseURL:NSString + @brief Parses an incoming URL into all available query items. + @param urlString The url to be parsed. + @return A dictionary of available query items in the target URL. + */ +static NSDictionary *FIRAuthParseURL(NSString *urlString) { + NSString *linkURL = [NSURLComponents componentsWithString:urlString].query; + if (!linkURL) { + return @{}; + } + NSArray *URLComponents = [linkURL componentsSeparatedByString:@"&"]; + NSMutableDictionary *queryItems = + [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count]; + for (NSString *component in URLComponents) { + NSRange equalRange = [component rangeOfString:@"="]; + if (equalRange.location != NSNotFound) { + NSString *queryItemKey = + [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding]; + NSString *queryItemValue = + [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding]; + if (queryItemKey && queryItemValue) { + queryItems[queryItemKey] = queryItemValue; + } + } + } + return queryItems; +} + +- (FIRAuthStateDidChangeListenerHandle)addAuthStateDidChangeListener: + (FIRAuthStateDidChangeListenerBlock)listener { + __block BOOL firstInvocation = YES; + __block NSString *previousUserID; + return [self addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) { + BOOL shouldCallListener = firstInvocation || + !(previousUserID == user.uid || [previousUserID isEqualToString:user.uid]); + firstInvocation = NO; + previousUserID = [user.uid copy]; + if (shouldCallListener) { + listener(auth, user); + } + }]; +} + +- (void)removeAuthStateDidChangeListener:(FIRAuthStateDidChangeListenerHandle)listenerHandle { + [self removeIDTokenDidChangeListener:listenerHandle]; +} + +- (FIRIDTokenDidChangeListenerHandle)addIDTokenDidChangeListener: + (FIRIDTokenDidChangeListenerBlock)listener { + if (!listener) { + [NSException raise:NSInvalidArgumentException format:@"listener must not be nil."]; + return nil; + } + FIRAuthStateDidChangeListenerHandle handle; + NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter]; + handle = [notifications addObserverForName:FIRAuthStateDidChangeNotification + object:self + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *_Nonnull notification) { + FIRAuth *auth = notification.object; + listener(auth, auth.currentUser); + }]; + @synchronized (self) { + [_listenerHandles addObject:handle]; + } + dispatch_async(dispatch_get_main_queue(), ^{ + listener(self, self->_currentUser); + }); + return handle; +} + +- (void)removeIDTokenDidChangeListener:(FIRIDTokenDidChangeListenerHandle)listenerHandle { + [[NSNotificationCenter defaultCenter] removeObserver:listenerHandle]; + @synchronized (self) { + [_listenerHandles removeObject:listenerHandle]; + } +} + +- (void)useAppLanguage { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + self->_requestConfiguration.languageCode = + [NSBundle mainBundle].preferredLocalizations.firstObject; + }); +} + +- (nullable NSString *)languageCode { + return _requestConfiguration.languageCode; +} + +- (void)setLanguageCode:(nullable NSString *)languageCode { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + self->_requestConfiguration.languageCode = [languageCode copy]; + }); +} + +- (NSString *)additionalFrameworkMarker { + return self->_requestConfiguration.additionalFrameworkMarker; +} + +- (void)setAdditionalFrameworkMarker:(NSString *)additionalFrameworkMarker { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + self->_requestConfiguration.additionalFrameworkMarker = [additionalFrameworkMarker copy]; + }); +} + +#if TARGET_OS_IOS +- (NSData *)APNSToken { + __block NSData *result = nil; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = self->_tokenManager.token.data; + }); + return result; +} + +- (void)setAPNSToken:(NSData *)APNSToken { + [self setAPNSToken:APNSToken type:FIRAuthAPNSTokenTypeUnknown]; +} + +- (void)setAPNSToken:(NSData *)token type:(FIRAuthAPNSTokenType)type { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + self->_tokenManager.token = [[FIRAuthAPNSToken alloc] initWithData:token type:type]; + }); +} + +- (void)handleAPNSTokenError:(NSError *)error { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + [self->_tokenManager cancelWithError:error]; + }); +} + +- (BOOL)canHandleNotification:(NSDictionary *)userInfo { + __block BOOL result = NO; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = [self->_notificationManager canHandleNotification:userInfo]; + }); + return result; +} + +- (BOOL)canHandleURL:(NSURL *)URL { + __block BOOL result = NO; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = [self->_authURLPresenter canHandleURL:URL]; + }); + return result; +} +#endif + +#pragma mark - Internal Methods + +#if TARGET_OS_IOS +/** @fn signInWithPhoneCredential:callback: + @brief Signs in using a phone credential. + @param credential The Phone Auth credential used to sign in. + @param operation The type of operation for which this sign-in attempt is initiated. + @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked + asynchronously on the global auth work queue in the future. + */ +- (void)signInWithPhoneCredential:(FIRPhoneAuthCredential *)credential + operation:(FIRAuthOperationType)operation + callback:(FIRVerifyPhoneNumberResponseCallback)callback { + if (credential.temporaryProof.length && credential.phoneNumber.length) { + FIRVerifyPhoneNumberRequest *request = + [[FIRVerifyPhoneNumberRequest alloc] initWithTemporaryProof:credential.temporaryProof + phoneNumber:credential.phoneNumber + operation:operation + requestConfiguration:_requestConfiguration]; + [FIRAuthBackend verifyPhoneNumber:request callback:callback]; + return; + } + + if (!credential.verificationID.length) { + callback(nil, [FIRAuthErrorUtils missingVerificationIDErrorWithMessage:nil]); + return; + } + if (!credential.verificationCode.length) { + callback(nil, [FIRAuthErrorUtils missingVerificationCodeErrorWithMessage:nil]); + return; + } + FIRVerifyPhoneNumberRequest *request = + [[FIRVerifyPhoneNumberRequest alloc]initWithVerificationID:credential.verificationID + verificationCode:credential.verificationCode + operation:operation + requestConfiguration:_requestConfiguration]; + [FIRAuthBackend verifyPhoneNumber:request callback:callback]; +} + +#endif + +/** @fn internalSignInAndRetrieveDataWithCustomToken:completion: + @brief Signs in a Firebase user given a custom token. + @param token A self-signed custom auth token. + @param completion A block which is invoked when the custom token sign in request completes. + */ +- (void)internalSignInAndRetrieveDataWithCustomToken:(NSString *)token + completion:(nullable FIRAuthDataResultCallback) + completion { + FIRVerifyCustomTokenRequest *request = + [[FIRVerifyCustomTokenRequest alloc] initWithToken:token + requestConfiguration:_requestConfiguration]; + [FIRAuthBackend verifyCustomToken:request + callback:^(FIRVerifyCustomTokenResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + if (completion) { + completion(nil, error); + return; + } + } + [self completeSignInWithAccessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken + anonymous:NO + callback:^(FIRUser *_Nullable user, + NSError *_Nullable error) { + if (error) { + if (completion) { + completion(nil, error); + } + return; + } + FIRAdditionalUserInfo *additonalUserInfo = + [[FIRAdditionalUserInfo alloc] initWithProviderID:nil + profile:nil + username:nil + isNewUser:response.isNewUser]; + FIRAuthDataResult *result = + [[FIRAuthDataResult alloc] initWithUser:user additionalUserInfo:additonalUserInfo]; + if (completion) { + completion(result, nil); + } + }]; + }]; +} + +/** @fn internalCreateUserWithEmail:password:completion: + @brief Makes a backend request attempting to create a new Firebase user given an email address + and password. + @param email The email address used to create the new Firebase user. + @param password The password used to create the new Firebase user. + @param completion Optionally; a block which is invoked when the request finishes. + */ +- (void)internalCreateUserWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRSignupNewUserCallback)completion { + FIRSignUpNewUserRequest *request = + [[FIRSignUpNewUserRequest alloc] initWithEmail:email + password:password + displayName:nil + requestConfiguration:_requestConfiguration]; + if (![request.password length]) { + completion(nil, [FIRAuthErrorUtils + weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]); + return; + } + if (![request.email length]) { + completion(nil, [FIRAuthErrorUtils missingEmailErrorWithMessage:nil]); + return; + } + [FIRAuthBackend signUpNewUser:request callback:completion]; +} + +/** @fn internalSignInAnonymouslyWithCompletion: + @param completion A block which is invoked when the anonymous sign in request completes. + */ +- (void)internalSignInAnonymouslyWithCompletion:(FIRSignupNewUserCallback)completion { + FIRSignUpNewUserRequest *request = + [[FIRSignUpNewUserRequest alloc]initWithRequestConfiguration:_requestConfiguration]; + [FIRAuthBackend signUpNewUser:request + callback:completion]; +} + +/** @fn possiblyPostAuthStateChangeNotification + @brief Posts the auth state change notificaton if current user's token has been changed. + */ +- (void)possiblyPostAuthStateChangeNotification { + NSString *token = _currentUser.rawAccessToken; + if (_lastNotifiedUserToken == token || + (token != nil && [_lastNotifiedUserToken isEqualToString:token])) { + return; + } + _lastNotifiedUserToken = token; + if (_autoRefreshTokens) { + // Shedule new refresh task after successful attempt. + [self scheduleAutoTokenRefresh]; + } + NSMutableDictionary *internalNotificationParameters = [NSMutableDictionary dictionary]; + if (self.app) { + internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = self.app; + } + if (token.length) { + internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token; + } + internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] = _currentUser.uid; + NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter]; + dispatch_async(dispatch_get_main_queue(), ^{ + [notifications postNotificationName:FIRAuthStateDidChangeInternalNotification + object:self + userInfo:internalNotificationParameters]; + [notifications postNotificationName:FIRAuthStateDidChangeNotification + object:self]; + }); +} + +- (BOOL)updateKeychainWithUser:(FIRUser *)user error:(NSError *_Nullable *_Nullable)error { + if (user != _currentUser) { + // No-op if the user is no longer signed in. This is not considered an error as we don't check + // whether the user is still current on other callbacks of user operations either. + return YES; + } + if ([self saveUser:user error:error]) { + [self possiblyPostAuthStateChangeNotification]; + return YES; + } + return NO; +} + +/** @fn setKeychainServiceNameForApp + @brief Sets the keychain service name global data for the particular app. + @param app The Firebase app to set keychain service name for. + */ ++ (void)setKeychainServiceNameForApp:(FIRApp *)app { + @synchronized (self) { + gKeychainServiceNameForAppName[app.name] = + [@"firebase_auth_" stringByAppendingString:app.options.googleAppID]; + } +} + +/** @fn keychainServiceNameForAppName: + @brief Gets the keychain service name global data for the particular app by name. + @param appName The name of the Firebase app to get keychain service name for. + */ ++ (NSString *)keychainServiceNameForAppName:(NSString *)appName { + @synchronized (self) { + return gKeychainServiceNameForAppName[appName]; + } +} + +/** @fn deleteKeychainServiceNameForAppName: + @brief Deletes the keychain service name global data for the particular app by name. + @param appName The name of the Firebase app to delete keychain service name for. + */ ++ (void)deleteKeychainServiceNameForAppName:(NSString *)appName { + @synchronized (self) { + [gKeychainServiceNameForAppName removeObjectForKey:appName]; + } +} + +/** @fn scheduleAutoTokenRefreshWithDelay: + @brief Schedules a task to automatically refresh tokens on the current user. The token refresh + is scheduled 5 minutes before the scheduled expiration time. + @remarks If the token expires in less than 5 minutes, schedule the token refresh immediately. + */ +- (void)scheduleAutoTokenRefresh { + NSTimeInterval tokenExpirationInterval = + [_currentUser.accessTokenExpirationDate timeIntervalSinceNow] - kTokenRefreshHeadStart; + [self scheduleAutoTokenRefreshWithDelay:MAX(tokenExpirationInterval, 0) retry:NO]; +} + +/** @fn scheduleAutoTokenRefreshWithDelay: + @brief Schedules a task to automatically refresh tokens on the current user. + @param delay The delay in seconds after which the token refresh task should be scheduled to be + executed. + @param retry Flag to determine whether the invocation is a retry attempt or not. + */ +- (void)scheduleAutoTokenRefreshWithDelay:(NSTimeInterval)delay retry:(BOOL)retry { + NSString *accessToken = _currentUser.rawAccessToken; + if (!accessToken) { + return; + } + if (retry) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000003", + @"Token auto-refresh re-scheduled in %02d:%02d " + @"because of error on previous refresh attempt.", + (int)ceil(delay) / 60, (int)ceil(delay) % 60); + } else { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000004", + @"Token auto-refresh scheduled in %02d:%02d for the new token.", + (int)ceil(delay) / 60, (int)ceil(delay) % 60); + } + _autoRefreshScheduled = YES; + __weak FIRAuth *weakSelf = self; + [[FIRAuthDispatcher sharedInstance] dispatchAfterDelay:delay + queue:FIRAuthGlobalWorkQueue() + task:^(void) { + FIRAuth *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + if (![strongSelf->_currentUser.rawAccessToken isEqualToString:accessToken]) { + // Another auto refresh must have been scheduled, so keep _autoRefreshScheduled unchanged. + return; + } + strongSelf->_autoRefreshScheduled = NO; + if (strongSelf->_isAppInBackground) { + return; + } + NSString *uid = strongSelf->_currentUser.uid; + [strongSelf->_currentUser internalGetTokenForcingRefresh:YES + callback:^(NSString *_Nullable token, + NSError *_Nullable error) { + if (![strongSelf->_currentUser.uid isEqualToString:uid]) { + return; + } + if (error) { + // Kicks off exponential back off logic to retry failed attempt. Starts with one minute + // delay (60 seconds) if this is the first failed attempt. + NSTimeInterval rescheduleDelay; + if (retry) { + rescheduleDelay = MIN(delay * 2, kMaxWaitTimeForBackoff); + } else { + rescheduleDelay = 60; + } + [strongSelf scheduleAutoTokenRefreshWithDelay:rescheduleDelay retry:YES]; + } + }]; + }]; +} + +#pragma mark - + +/** @fn completeSignInWithTokenService:callback: + @brief Completes a sign-in flow once we have access and refresh tokens for the user. + @param accessToken The STS access token. + @param accessTokenExpirationDate The approximate expiration date of the access token. + @param refreshToken The STS refresh token. + @param anonymous Whether or not the user is anonymous. + @param callback Called when the user has been signed in or when an error occurred. Invoked + asynchronously on the global auth work queue in the future. + */ +- (void)completeSignInWithAccessToken:(NSString *)accessToken + accessTokenExpirationDate:(NSDate *)accessTokenExpirationDate + refreshToken:(NSString *)refreshToken + anonymous:(BOOL)anonymous + callback:(FIRAuthResultCallback)callback { + [FIRUser retrieveUserWithAuth:self + accessToken:accessToken + accessTokenExpirationDate:accessTokenExpirationDate + refreshToken:refreshToken + anonymous:anonymous + callback:callback]; +} + +/** @fn signInFlowAuthResultCallbackByDecoratingCallback: + @brief Creates a FIRAuthResultCallback block which wraps another FIRAuthResultCallback; trying + to update the current user before forwarding it's invocations along to a subject block + @param callback Called when the user has been updated or when an error has occurred. Invoked + asynchronously on the main thread in the future. + @return Returns a block that updates the current user. + @remarks Typically invoked as part of the complete sign-in flow. For any other uses please + consider alternative ways of updating the current user. +*/ +- (FIRAuthResultCallback)signInFlowAuthResultCallbackByDecoratingCallback: + (nullable FIRAuthResultCallback)callback { + return ^(FIRUser *_Nullable user, NSError *_Nullable error) { + if (error) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, error); + }); + } + return; + } + if (![self updateCurrentUser:user byForce:NO savingToDisk:YES error:&error]) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, error); + }); + } + return; + } + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(user, nil); + }); + } + }; +} + +/** @fn signInFlowAuthDataResultCallbackByDecoratingCallback: + @brief Creates a FIRAuthDataResultCallback block which wraps another FIRAuthDataResultCallback; + trying to update the current user before forwarding it's invocations along to a subject + block. + @param callback Called when the user has been updated or when an error has occurred. Invoked + asynchronously on the main thread in the future. + @return Returns a block that updates the current user. + @remarks Typically invoked as part of the complete sign-in flow. For any other uses please + consider alternative ways of updating the current user. +*/ +- (FIRAuthDataResultCallback)signInFlowAuthDataResultCallbackByDecoratingCallback: + (nullable FIRAuthDataResultCallback)callback { + return ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { + if (error) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, error); + }); + } + return; + } + if (![self updateCurrentUser:authResult.user byForce:NO savingToDisk:YES error:&error]) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, error); + }); + } + return; + } + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(authResult, nil); + }); + } + }; +} + +#pragma mark - User-Related Methods + +/** @fn updateCurrentUser:savingToDisk: + @brief Update the current user; initializing the user's internal properties correctly, and + optionally saving the user to disk. + @remarks This method is called during: sign in and sign out events, as well as during class + initialization time. The only time the saveToDisk parameter should be set to NO is during + class initialization time because the user was just read from disk. + @param user The user to use as the current user (including nil, which is passed at sign out + time.) + @param saveToDisk Indicates the method should persist the user data to disk. + */ +- (BOOL)updateCurrentUser:(FIRUser *)user + byForce:(BOOL)force + savingToDisk:(BOOL)saveToDisk + error:(NSError *_Nullable *_Nullable)error { + if (user == _currentUser) { + [self possiblyPostAuthStateChangeNotification]; + return YES; + } + BOOL success = YES; + if (saveToDisk) { + success = [self saveUser:user error:error]; + } + if (success || force) { + _currentUser = user; + [self possiblyPostAuthStateChangeNotification]; + } + return success; +} + +/** @fn saveUser:error: + @brief Persists user. + @param user The user to save. + @param error Return value for any error which occurs. + @return @YES on success, @NO otherwise. + */ +- (BOOL)saveUser:(FIRUser *)user + error:(NSError *_Nullable *_Nullable)error { + BOOL success; + NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName]; + + if (!user) { + success = [_keychain removeDataForKey:userKey error:error]; + } else { + // Encode the user object. + NSMutableData *archiveData = [NSMutableData data]; + NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData]; + [archiver encodeObject:user forKey:userKey]; + [archiver finishEncoding]; + + // Save the user object's encoded value. + success = [_keychain setData:archiveData forKey:userKey error:error]; + } + return success; +} + +/** @fn getUser:error: + @brief Retrieves the saved user associated, if one exists, from the keychain. + @param outUser An out parameter which is populated with the saved user, if one exists. + @param error Return value for any error which occurs. + @return YES if the operation was a success (irrespective of whether or not a saved user existed + for the given @c firebaseAppId,) NO if an error occurred. + */ +- (BOOL)getUser:(FIRUser *_Nullable *)outUser + error:(NSError *_Nullable *_Nullable)error { + NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName]; + + NSError *keychainError; + NSData *encodedUserData = [_keychain dataForKey:userKey error:&keychainError]; + if (keychainError) { + if (error) { + *error = keychainError; + } + return NO; + } + if (!encodedUserData) { + *outUser = nil; + return YES; + } + NSKeyedUnarchiver *unarchiver = + [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedUserData]; + FIRUser *user = [unarchiver decodeObjectOfClass:[FIRUser class] forKey:userKey]; + user.auth = self; + *outUser = user; + return YES; +} + +#pragma mark - Interoperability + ++ (nonnull NSArray *)componentsToRegister { + FIRComponentCreationBlock authCreationBlock = + ^id _Nullable(FIRComponentContainer *_Nonnull container, BOOL *_Nonnull isCacheable) { + *isCacheable = YES; + return [[FIRAuth alloc] initWithApp:container.app]; + }; + FIRComponent *authInterop = [FIRComponent componentWithProtocol:@protocol(FIRAuthInterop) + creationBlock:authCreationBlock]; + return @[authInterop]; +} + +#pragma mark - FIRCoreConfigurable + ++ (void)configureWithApp:(nonnull FIRApp *)app { + // TODO: Evaluate what actually needs to be configured here instead of initializing a full + // instance. + // Ensures the @c FIRAuth instance for a given app gets loaded as soon as the app is ready. + [FIRAuth authWithApp:app]; +} + +#pragma mark - FIRComponentLifecycleMaintainer + +- (void)appWillBeDeleted:(nonnull FIRApp *)app { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + // This doesn't stop any request already issued, see b/27704535 . + NSString *keychainServiceName = [FIRAuth keychainServiceNameForAppName:app.name]; + if (keychainServiceName) { + [[self class] deleteKeychainServiceNameForAppName:app.name]; + FIRAuthKeychain *keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName]; + NSString *userKey = [NSString stringWithFormat:kUserKey, app.name]; + [keychain removeDataForKey:userKey error:NULL]; + } + dispatch_async(dispatch_get_main_queue(), ^{ + // TODO: Move over to fire an event instead, once ready. + [[NSNotificationCenter defaultCenter] postNotificationName:FIRAuthStateDidChangeNotification + object:nil]; + }); + }); +} + +#pragma mark - FIRAuthInterop + +- (void)getTokenForcingRefresh:(BOOL)forceRefresh withCallback:(FIRTokenCallback)callback { + __weak FIRAuth *weakSelf = self; + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + FIRAuth *strongSelf = weakSelf; + // Enable token auto-refresh if not aleady enabled. + if (strongSelf && !strongSelf->_autoRefreshTokens) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000002", @"Token auto-refresh enabled."); + strongSelf->_autoRefreshTokens = YES; + [strongSelf scheduleAutoTokenRefresh]; + +#if TARGET_OS_IOS || TARGET_OS_TV // TODO: Is a similar mechanism needed on macOS? + strongSelf->_applicationDidBecomeActiveObserver = [[NSNotificationCenter defaultCenter] + addObserverForName:UIApplicationDidBecomeActiveNotification + object:nil + queue:nil + usingBlock:^(NSNotification *notification) { + FIRAuth *strongSelf = weakSelf; + if (strongSelf) { + strongSelf->_isAppInBackground = NO; + if (!strongSelf->_autoRefreshScheduled) { + [weakSelf scheduleAutoTokenRefresh]; + } + } + }]; + strongSelf->_applicationDidEnterBackgroundObserver = [[NSNotificationCenter defaultCenter] + addObserverForName:UIApplicationDidEnterBackgroundNotification + object:nil + queue:nil + usingBlock:^(NSNotification *notification) { + FIRAuth *strongSelf = weakSelf; + if (strongSelf) { + strongSelf->_isAppInBackground = YES; + } + }]; +#endif + } + // Call back with 'nil' if there is no current user. + if (!strongSelf || !strongSelf->_currentUser) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, nil); + }); + return; + } + // Call back with current user token. + [strongSelf->_currentUser internalGetTokenForcingRefresh:forceRefresh + callback:^(NSString *_Nullable token, + NSError *_Nullable error) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(token, error); + }); + }]; + }); +} + +- (nullable NSString *)getUserID { + return _currentUser.uid; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.h new file mode 100644 index 0000000..dc07442 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.h @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthAPNSTokenType.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthAPNSToken + @brief A data structure for an APNs token. + */ +@interface FIRAuthAPNSToken : NSObject + +/** @property data + @brief The APNs token data. + */ +@property(nonatomic, strong, readonly) NSData *data; + +/** @property string + @brief The uppercase hexadecimal string form of the APNs token data. + */ +@property(nonatomic, strong, readonly) NSString *string; + +/** @property type + @brief The APNs token type. + */ +@property(nonatomic, assign, readonly) FIRAuthAPNSTokenType type; + +/** @fn initWithData:type: + @brief Initializes the instance. + @param data The APNs token data. + @param type The APNs token type. + @return The initialized instance. + */ +- (instancetype)initWithData:(NSData *)data type:(FIRAuthAPNSTokenType)type + NS_DESIGNATED_INITIALIZER; + +/** @fn init + @brief Call @c initWithData:type: to get an instance of this class. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.m new file mode 100644 index 0000000..db3f96d --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSToken.m @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthAPNSToken.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAuthAPNSToken { + /** @var _string + @brief The lazy-initialized string form of the token data. + */ + NSString *_string; +} + +- (instancetype)initWithData:(NSData *)data type:(FIRAuthAPNSTokenType)type { + self = [super init]; + if (self) { + _data = [data copy]; + _type = type; + } + return self; +} + +- (NSString *)string { + if (!_string) { + NSUInteger capacity = _data.length * 2; + NSMutableString *tokenString = [NSMutableString stringWithCapacity:capacity]; + const unsigned char *tokenData = _data.bytes; + for (int idx = 0; idx < _data.length; ++idx) { + [tokenString appendFormat:@"%02X", (int)tokenData[idx]]; + } + _string = tokenString; + } + return _string; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.h new file mode 100644 index 0000000..566780f --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.h @@ -0,0 +1,78 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +@class FIRAuthAPNSToken; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthAPNSTokenCallback + @brief The type of block to receive an APNs token. + @param token The APNs token if one is available. + @param error The error happened if any. + @remarks Both `token` and `error` being `nil` means the request timed-out. + */ +typedef void (^FIRAuthAPNSTokenCallback)(FIRAuthAPNSToken *_Nullable token, + NSError *_Nullable error); + +/** @class FIRAuthAPNSTokenManager + @brief A class to manage APNs token in memory. + */ +@interface FIRAuthAPNSTokenManager : NSObject + +/** @property token + @brief The APNs token, if one is available. + @remarks Setting a token with FIRAuthAPNSTokenTypeUnknown will automatically converts it to + a token with the automatically detected type. + */ +@property(nonatomic, strong, nullable) FIRAuthAPNSToken *token; + +/** @property timeout + @brief The timeout for registering for remote notification. + @remarks Only tests should access this property. + */ +@property(nonatomic, assign) NSTimeInterval timeout; + +/** @fn init + @brief Call @c initWithApplication: to initialize an instance of this class. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithApplication:bundle + @brief Initializes the instance. + @param application The @c UIApplication to request the token from. + @return The initialized instance. + */ +- (instancetype)initWithApplication:(UIApplication *)application NS_DESIGNATED_INITIALIZER; + +/** @fn getTokenWithCallback: + @brief Attempts to get the APNs token. + @param callback The block to be called either immediately or in future, either when a token + becomes available, or when timeout occurs, whichever happens earlier. + */ +- (void)getTokenWithCallback:(FIRAuthAPNSTokenCallback)callback; + +/** @fn cancelWithError: + @brief Cancels any pending `getTokenWithCallback:` request. + @param error The error to return. + */ +- (void)cancelWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.m new file mode 100644 index 0000000..3e8dd90 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAPNSTokenManager.m @@ -0,0 +1,247 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthAPNSTokenManager.h" + +#import +#import + +#import "FIRAuthAPNSToken.h" +#import "FIRAuthGlobalWorkQueue.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kRegistrationTimeout + @brief Timeout for registration for remote notification. + @remarks Once we start to handle `application:didFailToRegisterForRemoteNotificationsWithError:` + we probably don't have to use timeout at all. + */ +static const NSTimeInterval kRegistrationTimeout = 5; + +/** @var kLegacyRegistrationTimeout + @brief Timeout for registration for remote notification on iOS 7. + */ +static const NSTimeInterval kLegacyRegistrationTimeout = 30; + +@implementation FIRAuthAPNSTokenManager { + /** @var _application + @brief The @c UIApplication to request the token from. + */ + UIApplication *_application; + + /** @var _pendingCallbacks + @brief The list of all pending callbacks for the APNs token. + */ + NSMutableArray *_pendingCallbacks; +} + +- (instancetype)initWithApplication:(UIApplication *)application { + self = [super init]; + if (self) { + _application = application; + _timeout = [_application respondsToSelector:@selector(registerForRemoteNotifications)] ? + kRegistrationTimeout : kLegacyRegistrationTimeout; + } + return self; +} + +- (void)getTokenWithCallback:(FIRAuthAPNSTokenCallback)callback { + if (_token) { + callback(_token, nil); + return; + } + if (_pendingCallbacks) { + [_pendingCallbacks addObject:callback]; + return; + } + _pendingCallbacks = + [[NSMutableArray alloc] initWithObjects:callback, nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + if ([self->_application respondsToSelector:@selector(registerForRemoteNotifications)]) { + [self->_application registerForRemoteNotifications]; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#if TARGET_OS_IOS + [self->_application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert]; +#endif // TARGET_OS_IOS +#pragma clang diagnostic pop + } + }); + NSArray *applicableCallbacks = _pendingCallbacks; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_timeout * NSEC_PER_SEC)), + FIRAuthGlobalWorkQueue(), ^{ + // Only cancel if the pending callbacks remain the same, i.e., not triggered yet. + if (applicableCallbacks == self->_pendingCallbacks) { + [self callBackWithToken:nil error:nil]; + } + }); +} + +- (void)setToken:(nullable FIRAuthAPNSToken *)token { + if (!token) { + _token = nil; + return; + } + if (token.type == FIRAuthAPNSTokenTypeUnknown) { + static FIRAuthAPNSTokenType detectedTokenType = FIRAuthAPNSTokenTypeUnknown; + if (detectedTokenType == FIRAuthAPNSTokenTypeUnknown) { + detectedTokenType = + [[self class] isProductionApp] ? FIRAuthAPNSTokenTypeProd : FIRAuthAPNSTokenTypeSandbox; + } + token = [[FIRAuthAPNSToken alloc] initWithData:token.data type:detectedTokenType]; + } + _token = token; + [self callBackWithToken:token error:nil]; +} + +- (void)cancelWithError:(NSError *)error { + [self callBackWithToken:nil error:error]; +} + +#pragma mark - Internal methods + +/** @fn callBack + @brief Calls back all pending callbacks with APNs token or error. + @param token The APNs token if one is available. + @param error The error occurred, if any. + */ +- (void)callBackWithToken:(nullable FIRAuthAPNSToken *)token error:(nullable NSError *)error { + if (!_pendingCallbacks) { + return; + } + NSArray *allCallbacks = _pendingCallbacks; + _pendingCallbacks = nil; + for (FIRAuthAPNSTokenCallback callback in allCallbacks) { + callback(token, error); + } +}; + +/** @fn isProductionApp + @brief Whether or not the app has production (versus sandbox) provisioning profile. + @remarks This method is adapted from @c FIRInstanceID . + */ ++ (BOOL)isProductionApp { + const BOOL defaultAppTypeProd = YES; + + NSError *error = nil; + + if ([GULAppEnvironmentUtil isSimulator]) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000006", @"Assuming prod APNs token type on simulator."); + return defaultAppTypeProd; + } + + // Apps distributed via AppStore or TestFlight use the Production APNS certificates. + if ([GULAppEnvironmentUtil isFromAppStore]) { + return defaultAppTypeProd; + } + NSString *path = [[[NSBundle mainBundle] bundlePath] + stringByAppendingPathComponent:@"embedded.mobileprovision"]; + if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) { + // Distributed via TestFlight + return defaultAppTypeProd; + } + + NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error]; + + if (!profileData.length || error) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000007", + @"Error while reading embedded mobileprovision %@", error); + return defaultAppTypeProd; + } + + // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the + // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit + // ASCII. Replace any 0s or invalid characters in the input. + uint8_t *profileBytes = (uint8_t *)profileData.bytes; + for (int i = 0; i < profileData.length; i++) { + uint8_t currentByte = profileBytes[i]; + if (!currentByte || currentByte > 127) { + profileBytes[i] = '.'; + } + } + + NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes + length:profileData.length + encoding:NSASCIIStringEncoding + freeWhenDone:NO]; + + if (error || !embeddedProfile.length) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000008", + @"Error while reading embedded mobileprovision %@", error); + return defaultAppTypeProd; + } + + NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile]; + NSString *plistContents; + if ([scanner scanUpToString:@"" intoString:&plistContents]) { + plistContents = [plistContents stringByAppendingString:@""]; + } + } + + if (!plistContents.length) { + return defaultAppTypeProd; + } + + NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding]; + if (!data.length) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000009", + @"Couldn't read plist fetched from embedded mobileprovision"); + return defaultAppTypeProd; + } + + NSError *plistMapError; + id plistData = [NSPropertyListSerialization propertyListWithData:data + options:NSPropertyListImmutable + format:nil + error:&plistMapError]; + if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000010", + @"Error while converting assumed plist to dict %@", + plistMapError.localizedDescription); + return defaultAppTypeProd; + } + NSDictionary *plistMap = (NSDictionary *)plistData; + + if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000011", + @"Provisioning profile has specifically provisioned devices, " + @"most likely a Dev profile."); + } + + NSString *apsEnvironment = [plistMap valueForKeyPath:@"Entitlements.aps-environment"]; + FIRLogDebug(kFIRLoggerAuth, @"I-AUT000012", + @"APNS Environment in profile: %@", apsEnvironment); + + // No aps-environment in the profile. + if (!apsEnvironment.length) { + FIRLogInfo(kFIRLoggerAuth, @"I-AUT000013", + @"No aps-environment set. If testing on a device APNS is not " + @"correctly configured. Please recheck your provisioning profiles."); + return defaultAppTypeProd; + } + + if ([apsEnvironment isEqualToString:@"development"]) { + return NO; + } + + return defaultAppTypeProd; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.h new file mode 100644 index 0000000..57fa83a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthAppCredential + @brief A class represents a credential that proves the identity of the app. + */ +@interface FIRAuthAppCredential : NSObject + +/** @property receipt + @brief The server acknowledgement of receiving client's claim of identity. + */ +@property(nonatomic, strong, readonly) NSString *receipt; + +/** @property secret + @brief The secret that the client received from server via a trusted channel, if ever. + */ +@property(nonatomic, strong, readonly, nullable) NSString *secret; + +/** @fn initWithReceipt:secret: + @brief Initializes the instance. + @param receipt The server acknowledgement of receiving client's claim of identity. + @param secret The secret that the client received from server via a trusted channel, if ever. + @return The initialized instance. + */ +- (instancetype)initWithReceipt:(NSString *)receipt secret:(nullable NSString *)secret + NS_DESIGNATED_INITIALIZER; + +/** @fn init + @brief Call @c initWithReceipt:secret: to get an instance of this class. + */ +- (instancetype)init NS_UNAVAILABLE; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.m new file mode 100644 index 0000000..27d4ad2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredential.m @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthAppCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kReceiptKey + @brief The key used to encode the receipt property for NSSecureCoding. + */ +static NSString *const kReceiptKey = @"receipt"; + +/** @var kSecretKey + @brief The key used to encode the secret property for NSSecureCoding. + */ +static NSString *const kSecretKey = @"secret"; + +@implementation FIRAuthAppCredential + +- (instancetype)initWithReceipt:(NSString *)receipt secret:(nullable NSString *)secret { + self = [super init]; + if (self) { + _receipt = [receipt copy]; + _secret = [secret copy]; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *receipt = [aDecoder decodeObjectOfClass:[NSString class] forKey:kReceiptKey]; + if (!receipt) { + return nil; + } + NSString *secret = [aDecoder decodeObjectOfClass:[NSString class] forKey:kSecretKey]; + return [self initWithReceipt:receipt secret:secret]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_receipt forKey:kReceiptKey]; + [aCoder encodeObject:_secret forKey:kSecretKey]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.h new file mode 100644 index 0000000..21c1545 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.h @@ -0,0 +1,85 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthAppCredential; +@class FIRAuthKeychain; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthAppCredentialCallback + @brief The type of block to receive an app crdential. + @param credential The best available app credential at the time. + */ +typedef void (^FIRAuthAppCredentialCallback)(FIRAuthAppCredential *credential); + +/** @class FIRAuthAppCredentialManager + @brief A class to manage app credentials backed by iOS Keychain. + */ +@interface FIRAuthAppCredentialManager : NSObject + +/** @property credential + @brief The full credential (which has a secret) to be used by the app, if one is available. + */ +@property(nonatomic, strong, readonly, nullable) FIRAuthAppCredential *credential; + +/** @property maximumNumberOfPendingReceipts + @brief The maximum (but not necessarily the minimum) number of pending receipts to be kept. + @remarks Only tests should access this property. + */ +@property(nonatomic, assign, readonly) NSUInteger maximumNumberOfPendingReceipts; + +/** @fn init + @brief Call @c initWithKeychain: to initialize an instance of this class. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithKeychain: + @brief Initializes the instance. + @param keychain The iOS Keychain storage to back up the app credential with. + @return The initialized instance. + */ +- (instancetype)initWithKeychain:(FIRAuthKeychain *)keychain NS_DESIGNATED_INITIALIZER; + +/** @fn didStartVerificationWithReceipt:timeout:callback: + @brief Notifies that the app verification process has started. + @param receipt The receipt for verification. + @param timeout The timeout value for how long the callback is waited to be called. + @param callback The block to be called in future either when the verification finishes, or + when timeout occurs, whichever happens earlier. + */ +- (void)didStartVerificationWithReceipt:(NSString *)receipt + timeout:(NSTimeInterval)timeout + callback:(FIRAuthAppCredentialCallback)callback; + +/** @fn canFinishVerificationWithReceipt: + @brief Attempts to finish verification. + @param receipt The receipt to match the original receipt obtained when verification started. + @param secret The secret to complete the verification. + @return Whether or not the receipt matches a pending verification, and finishes verification + if it does. + */ +- (BOOL)canFinishVerificationWithReceipt:(NSString *)receipt secret:(NSString *)secret; + +/** @fn clearCredential + @brief Clears the saved credential, to be used in the case that it is rejected by the server. + */ +- (void)clearCredential; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.m new file mode 100644 index 0000000..0e251a7 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppCredentialManager.m @@ -0,0 +1,164 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthAppCredentialManager.h" + +#import "FIRAuthAppCredential.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FIRAuthKeychain.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kKeychainDataKey + @brief The keychain key for the data. + */ +static NSString *const kKeychainDataKey = @"app_credentials"; + +/** @var kFullCredentialKey + @brief The data key for the full app credential. + */ +static NSString *const kFullCredentialKey = @"full_credential"; + +/** @var kPendingReceiptsKey + @brief The data key for the array of pending receipts. + */ +static NSString *const kPendingReceiptsKey = @"pending_receipts"; + +/** @var kMaximumNumberOfPendingReceipts + @brief The maximum number of partial credentials kept by this class. + */ +static const NSUInteger kMaximumNumberOfPendingReceipts = 32; + +@implementation FIRAuthAppCredentialManager { + /** @var _keychain + @brief The keychain for app credentials to load from and to save to. + */ + FIRAuthKeychain *_keychain; + + /** @var _pendingReceipts + @brief A list of pending receipts sorted in the order they were recorded. + */ + NSMutableArray *_pendingReceipts; + + /** @var _callbacksByReceipt + @brief A map from pending receipts to callbacks. + */ + NSMutableDictionary *_callbacksByReceipt; +} + +- (instancetype)initWithKeychain:(FIRAuthKeychain *)keychain { + self = [super init]; + if (self) { + _keychain = keychain; + // Load the credentials from keychain if possible. + NSError *error; + NSData *encodedData = [_keychain dataForKey:kKeychainDataKey error:&error]; + if (!error && encodedData) { + NSKeyedUnarchiver *unarchiver = + [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedData]; + FIRAuthAppCredential *credential = + [unarchiver decodeObjectOfClass:[FIRAuthAppCredential class] + forKey:kFullCredentialKey]; + if ([credential isKindOfClass:[FIRAuthAppCredential class]]) { + _credential = credential; + } + NSSet *allowedClasses = + [NSSet setWithObjects:[NSArray class], [NSString class], nil]; + NSArray *pendingReceipts = + [unarchiver decodeObjectOfClasses:allowedClasses forKey:kPendingReceiptsKey]; + if ([pendingReceipts isKindOfClass:[NSArray class]]) { + _pendingReceipts = [pendingReceipts mutableCopy]; + } + } + if (!_pendingReceipts) { + _pendingReceipts = [[NSMutableArray alloc] init]; + } + _callbacksByReceipt = + [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (NSUInteger)maximumNumberOfPendingReceipts { + return kMaximumNumberOfPendingReceipts; +} + +- (void)didStartVerificationWithReceipt:(NSString *)receipt + timeout:(NSTimeInterval)timeout + callback:(FIRAuthAppCredentialCallback)callback { + [_pendingReceipts removeObject:receipt]; + if (_pendingReceipts.count >= kMaximumNumberOfPendingReceipts) { + [_pendingReceipts removeObjectAtIndex:0]; + } + [_pendingReceipts addObject:receipt]; + _callbacksByReceipt[receipt] = callback; + [self saveData]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)), + FIRAuthGlobalWorkQueue(), ^{ + [self callBackWithReceipt:receipt]; + }); +} + +- (BOOL)canFinishVerificationWithReceipt:(NSString *)receipt secret:(NSString *)secret { + if (![_pendingReceipts containsObject:receipt]) { + return NO; + } + [_pendingReceipts removeObject:receipt]; + _credential = [[FIRAuthAppCredential alloc] initWithReceipt:receipt secret:secret]; + [self saveData]; + [self callBackWithReceipt:receipt]; + return YES; +} + +- (void)clearCredential { + _credential = nil; + [self saveData]; +} + +#pragma mark - Internal methods + +/** @fn saveData + @brief Save the data in memory to the keychain ignoring any errors. + */ +- (void)saveData { + NSMutableData *archiveData = [NSMutableData data]; + NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData]; + [archiver encodeObject:_credential forKey:kFullCredentialKey]; + [archiver encodeObject:_pendingReceipts forKey:kPendingReceiptsKey]; + [archiver finishEncoding]; + [_keychain setData:archiveData forKey:kKeychainDataKey error:NULL]; +} + +/** @fn callBackWithReceipt: + @brief Calls the saved callback for the specifc receipt. + @param receipt The receipt associated with the callback. + */ +- (void)callBackWithReceipt:(NSString *)receipt { + FIRAuthAppCredentialCallback callback = _callbacksByReceipt[receipt]; + if (!callback) { + return; + } + [_callbacksByReceipt removeObjectForKey:receipt]; + if (_credential) { + callback(_credential); + } else { + callback([[FIRAuthAppCredential alloc] initWithReceipt:receipt secret:nil]); + } +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.h new file mode 100644 index 0000000..ccae93a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.h @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @protocol FIRAuthAppDelegateHandler + @brief The protocol to handle app delegate methods. + */ +@protocol FIRAuthAppDelegateHandler + +/** @fn setAPNSToken: + @brief Sets the APNs device token. + @param token The APNs device token. + */ +- (void)setAPNSToken:(NSData *)token; + +/** @fn handleAPNSTokenError: + @brief Handles APNs device token error. + @param error The APNs device token error. + */ +- (void)handleAPNSTokenError:(NSError *)error; + +/** @fn canHandleNotification: + @brief Checks whether the notification can be handled by the receiver, and handles it if so. + @param notification The notification in question, which will be consumed if returns @c YES. + @return Whether the notification can be (and already has been) handled by the receiver. + */ +- (BOOL)canHandleNotification:(nonnull NSDictionary *)notification; + +/** @fn canHandleURL: + @brief Checks whether the URL can be handled by the receiver, and handles it if so. + @param url The URL in question, which will be consumed if returns @c YES. + @return Whether the URL can be (and already has been) handled by the receiver. + */ +- (BOOL)canHandleURL:(nonnull NSURL *)url; + +@end + +/** @class FIRAuthAppDelegateProxy + @brief A manager for swizzling @c UIApplicationDelegate methods. + */ +@interface FIRAuthAppDelegateProxy : NSObject + +/** @fn initWithApplication + @brief Initialize the instance with the given @c UIApplication. + @returns An initialized instance, or @c nil if a proxy cannot be established. + @remarks This method should only be called from tests if called outside of this class. + */ +- (nullable instancetype)initWithApplication:(nullable UIApplication *)application + NS_DESIGNATED_INITIALIZER; + +/** @fn init + @brief Call @c sharedInstance to get an instance of this class. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn addHandler: + @brief Adds a handler for UIApplicationDelegate methods. + @param handler The handler to be added. + */ +- (void)addHandler:(__weak id)handler; + +/** @fn sharedInstance + @brief Gets the shared instance of this class. + @returns The shared instance of this class. + */ ++ (nullable instancetype)sharedInstance; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.m new file mode 100644 index 0000000..d97fedc --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthAppDelegateProxy.m @@ -0,0 +1,412 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthAppDelegateProxy.h" + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @var kProxyEnabledBundleKey + @brief The key in application's bundle plist for whether or not proxy should be enabled. + @remarks This key is a shared constant with Analytics and FCM. + */ +static NSString *const kProxyEnabledBundleKey = @"FirebaseAppDelegateProxyEnabled"; + +/** @fn noop + @brief A function that does nothing. + @remarks This is used as the placeholder for unimplemented UApplicationDelegate methods, + because once we added a method there is no way to remove it from the class. + */ +#if !OBJC_OLD_DISPATCH_PROTOTYPES +static void noop(void) { +} +#else +static id noop(id object, SEL cmd, ...) { + return nil; +} +#endif + +/** @fn isIOS9orLater + @brief Checks whether the iOS version is 9 or later. + @returns Whether the iOS version is 9 or later. + */ +static BOOL isIOS9orLater() { +#if defined(__IPHONE_11_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0) + if (@available(iOS 9.0, *)) { + return YES; + } + return NO; +#else + // UIApplicationOpenURLOptionsAnnotationKey is only available on iOS 9+. + return &UIApplicationOpenURLOptionsAnnotationKey != NULL; +#endif +} + +@implementation FIRAuthAppDelegateProxy { + /** @var _appDelegate + @brief The application delegate whose method is being swizzled. + */ + id _appDelegate; + + /** @var _orginalImplementationsBySelector + @brief A map from selectors to original implementations that have been swizzled. + */ + NSMutableDictionary *_originalImplementationsBySelector; + + /** @var _handlers + @brief The array of weak pointers of `id`. + */ + NSPointerArray *_handlers; +} + +- (nullable instancetype)initWithApplication:(nullable UIApplication *)application { + self = [super init]; + if (self) { + id proxyEnabled = [[NSBundle mainBundle] objectForInfoDictionaryKey:kProxyEnabledBundleKey]; + if ([proxyEnabled isKindOfClass:[NSNumber class]] && !((NSNumber *)proxyEnabled).boolValue) { + return nil; + } + _appDelegate = application.delegate; + if (![_appDelegate conformsToProtocol:@protocol(UIApplicationDelegate)]) { + return nil; + } + _originalImplementationsBySelector = [[NSMutableDictionary alloc] init]; + _handlers = [[NSPointerArray alloc] initWithOptions:NSPointerFunctionsWeakMemory]; + + // Swizzle the methods. + __weak FIRAuthAppDelegateProxy *weakSelf = self; + SEL registerDeviceTokenSelector = + @selector(application:didRegisterForRemoteNotificationsWithDeviceToken:); + [self replaceSelector:registerDeviceTokenSelector + withBlock:^(id object, UIApplication* application, NSData *deviceToken) { + [weakSelf object:object + selector:registerDeviceTokenSelector + application:application + didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; + }]; + SEL failToRegisterRemoteNotificationSelector = + @selector(application:didFailToRegisterForRemoteNotificationsWithError:); + [self replaceSelector:failToRegisterRemoteNotificationSelector + withBlock:^(id object, UIApplication* application, NSError *error) { + [weakSelf object:object + selector:failToRegisterRemoteNotificationSelector + application:application + didFailToRegisterForRemoteNotificationsWithError:error]; + }]; + SEL receiveNotificationSelector = @selector(application:didReceiveRemoteNotification:); + SEL receiveNotificationWithHandlerSelector = + @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:); + if ([_appDelegate respondsToSelector:receiveNotificationWithHandlerSelector] || + ![_appDelegate respondsToSelector:receiveNotificationSelector]) { + // Replace the modern selector which is available on iOS 7 and above. + [self replaceSelector:receiveNotificationWithHandlerSelector + withBlock:^(id object, UIApplication *application, NSDictionary *notification, + void (^completionHandler)(UIBackgroundFetchResult)) { + [weakSelf object:object + selector:receiveNotificationWithHandlerSelector + application:application + didReceiveRemoteNotification:notification + fetchCompletionHandler:completionHandler]; + }]; + } else { + // Replace the deprecated selector because this is the only one that the client app uses. + [self replaceSelector:receiveNotificationSelector + withBlock:^(id object, UIApplication *application, NSDictionary *notification) { + [weakSelf object:object + selector:receiveNotificationSelector + application:application + didReceiveRemoteNotification:notification]; + }]; + } + SEL openURLOptionsSelector = @selector(application:openURL:options:); + SEL openURLAnnotationSelector = @selector(application:openURL:sourceApplication:annotation:); + SEL handleOpenURLSelector = @selector(application:handleOpenURL:); + if (isIOS9orLater() && + ([_appDelegate respondsToSelector:openURLOptionsSelector] || + (![_appDelegate respondsToSelector:openURLAnnotationSelector] && + ![_appDelegate respondsToSelector:handleOpenURLSelector]))) { + // Replace the modern selector which is avaliable on iOS 9 and above because this is the one + // that the client app uses or the client app doesn't use any of them. + [self replaceSelector:openURLOptionsSelector + withBlock:^BOOL(id object, UIApplication *application, NSURL *url, + NSDictionary *options) { + return [weakSelf object:object + selector:openURLOptionsSelector + application:application + openURL:url + options:options]; + }]; + } else if ([_appDelegate respondsToSelector:openURLAnnotationSelector] || + ![_appDelegate respondsToSelector:handleOpenURLSelector]) { + // Replace the longer form of the deprecated selectors on iOS 8 and below because this is the + // one that the client app uses or the client app doesn't use either of the applicable ones. + [self replaceSelector:openURLAnnotationSelector + withBlock:^(id object, UIApplication *application, NSURL *url, + NSString *sourceApplication, id annotation) { + return [weakSelf object:object + selector:openURLAnnotationSelector + application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; + }]; + } else { + // Replace the shorter form of the deprecated selectors on iOS 8 and below because this is + // the only one that the client app uses. + [self replaceSelector:handleOpenURLSelector + withBlock:^(id object, UIApplication *application, NSURL *url) { + return [weakSelf object:object + selector:handleOpenURLSelector + application:application + handleOpenURL:url]; + }]; + } + // Reset the application delegate to clear the system cache that indicates whether each of the + // openURL: methods is implemented on the application delegate. + application.delegate = nil; + application.delegate = _appDelegate; + } + return self; +} + +- (void)dealloc { + for (NSValue *selector in _originalImplementationsBySelector) { + IMP implementation = _originalImplementationsBySelector[selector].pointerValue; + Method method = class_getInstanceMethod([_appDelegate class], selector.pointerValue); + imp_removeBlock(method_setImplementation(method, implementation)); + } +} + +- (void)addHandler:(__weak id)handler { + @synchronized (_handlers) { + [_handlers addPointer:(__bridge void *)handler]; + } +} + ++ (nullable instancetype)sharedInstance { + static dispatch_once_t onceToken; + static FIRAuthAppDelegateProxy *_Nullable sharedInstance; + // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication + // responds to it. + static Class applicationClass = nil; + dispatch_once(&onceToken, ^{ + if (![GULAppEnvironmentUtil isAppExtension]) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + UIApplication *application = [applicationClass sharedApplication]; + sharedInstance = [[self alloc] initWithApplication:application]; + }); + return sharedInstance; +} + +#pragma mark - UIApplicationDelegate proxy methods. + +- (void)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { + if (object == _appDelegate) { + for (id handler in [self handlers]) { + [handler setAPNSToken:deviceToken]; + } + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef void (*Implmentation)(id, SEL, UIApplication*, NSData *); + ((Implmentation)originalImplementation)(object, selector, application, deviceToken); + } +} + +- (void)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { + if (object == _appDelegate) { + for (id handler in [self handlers]) { + [handler handleAPNSTokenError:error]; + } + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef void (*Implmentation)(id, SEL, UIApplication *, NSError *); + ((Implmentation)originalImplementation)(object, selector, application, error); + } +} + +- (void)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + didReceiveRemoteNotification:(NSDictionary *)notification + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { + if (object == _appDelegate) { + for (id handler in [self handlers]) { + if ([handler canHandleNotification:notification]) { + completionHandler(UIBackgroundFetchResultNoData); + return; + }; + } + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef void (*Implmentation)(id, SEL, UIApplication*, NSDictionary *, + void (^)(UIBackgroundFetchResult)); + ((Implmentation)originalImplementation)(object, selector, application, notification, + completionHandler); + } +} + +- (void)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + didReceiveRemoteNotification:(NSDictionary *)notification { + if (object == _appDelegate) { + for (id handler in [self handlers]) { + if ([handler canHandleNotification:notification]) { + return; + }; + } + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef void (*Implmentation)(id, SEL, UIApplication*, NSDictionary *); + ((Implmentation)originalImplementation)(object, selector, application, notification); + } +} + +- (BOOL)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + openURL:(NSURL *)url + options:(NSDictionary *)options { + if (object == _appDelegate && [self delegateCanHandleURL:url]) { + return YES; + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *, NSDictionary *); + return ((Implmentation)originalImplementation)(object, selector, application, url, options); + } + return NO; +} + +- (BOOL)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + openURL:(NSURL *)url + sourceApplication:(NSString *)sourceApplication + annotation:(id)annotation { + if (object == _appDelegate && [self delegateCanHandleURL:url]) { + return YES; + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *, NSString *, id); + return ((Implmentation)originalImplementation)(object, selector, application, url, + sourceApplication, annotation); + } + return NO; +} + +- (BOOL)object:(id)object + selector:(SEL)selector + application:(UIApplication *)application + handleOpenURL:(NSURL *)url { + if (object == _appDelegate && [self delegateCanHandleURL:url]) { + return YES; + } + IMP originalImplementation = [self originalImplementationForSelector:selector]; + if (originalImplementation && originalImplementation != &noop) { + typedef BOOL (*Implmentation)(id, SEL, UIApplication*, NSURL *); + return ((Implmentation)originalImplementation)(object, selector, application, url); + } + return NO; +} + +#pragma mark - Internal Methods + +/** @fn delegateCanHandleURL: + @brief Checks for whether any of the delegates can handle the URL. + @param url The URL in question. + @return Whether any of the delegate can handle the URL. + */ +- (BOOL)delegateCanHandleURL:(NSURL *)url { + for (id handler in [self handlers]) { + if ([handler canHandleURL:url]) { + return YES; + }; + } + return NO; +} + +/** @fn handlers + @brief Gets the list of handlers from `_handlers` safely. + */ +- (NSArray> *)handlers { + @synchronized (_handlers) { + NSMutableArray> *liveHandlers = + [[NSMutableArray> alloc] initWithCapacity:_handlers.count]; + for (__weak id handler in _handlers) { + if (handler) { + [liveHandlers addObject:handler]; + } + } + if (liveHandlers.count < _handlers.count) { + [_handlers compact]; + } + return liveHandlers; + } +} + +/** @fn replaceSelector:withBlock: + @brief replaces the implementation for a method of `_appDelegate` specified by a selector. + @param selector The selector for the method. + @param block The block as the new implementation of the method. + */ +- (void)replaceSelector:(SEL)selector withBlock:(id)block { + Method originalMethod = class_getInstanceMethod([_appDelegate class], selector); + IMP newImplementation = imp_implementationWithBlock(block); + IMP originalImplementation; + if (originalMethod) { + originalImplementation = method_setImplementation(originalMethod, newImplementation) ?: &noop; + } else { + // The original method was not implemented in the class, add it with the new implementation. + struct objc_method_description methodDescription = + protocol_getMethodDescription(@protocol(UIApplicationDelegate), selector, NO, YES); + class_addMethod([_appDelegate class], selector, newImplementation, methodDescription.types); + originalImplementation = &noop; + } + _originalImplementationsBySelector[[NSValue valueWithPointer:selector]] = + [NSValue valueWithPointer:originalImplementation]; +} + +/** @fn originalImplementationForSelector: + @brief Gets the original implementation for the given selector. + @param selector The selector for the method that has been replaced. + @return The original implementation if there was one. + */ +- (IMP)originalImplementationForSelector:(SEL)selector { + return _originalImplementationsBySelector[[NSValue valueWithPointer:selector]].pointerValue; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential.m new file mode 100644 index 0000000..54cb15c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential.m @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthCredential_Internal.h" + +@implementation FIRAuthCredential + +- (instancetype)init { + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." + reason:@"This class is an abstract base class. It's init method " + "should not be called directly." + userInfo:nil]; +} + +- (nullable instancetype)initWithProvider:(NSString *)provider { + self = [super init]; + if (self) { + _provider = [provider copy]; + } + return self; +} + +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request { + @throw [NSException exceptionWithName:@"Attempt to call virtual method." + reason:@"This method must be overridden by a subclass." + userInfo:nil]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential_Internal.h new file mode 100644 index 0000000..e060cda --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthCredential_Internal.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthCredential.h" + +@class FIRVerifyAssertionRequest; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAuthCredential () + +/** @fn initWithProvider: + @brief Designated initializer. + @remarks This is the designated initializer for internal/friend subclasses. + @param provider The provider name. + */ +- (nullable instancetype)initWithProvider:(NSString *)provider NS_DESIGNATED_INITIALIZER; + +/** @fn prepareVerifyAssertionRequest: + @brief Called immediately before a request to the verifyAssertion endpoint is made. Implementers + should update the passed request instance with their credentials. + @param request The request to be updated with credentials. + */ +- (void)prepareVerifyAssertionRequest:(FIRVerifyAssertionRequest *)request; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult.m new file mode 100644 index 0000000..9d8e598 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult.m @@ -0,0 +1,69 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthDataResult_Internal.h" + +#import "FIRAdditionalUserInfo.h" +#import "FIRUser.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAuthDataResult + +/** @var kAdditionalUserInfoCodingKey + @brief The key used to encode the additionalUserInfo property for NSSecureCoding. + */ +static NSString *const kAdditionalUserInfoCodingKey = @"additionalUserInfo"; + +/** @var kUserCodingKey + @brief The key used to encode the user property for NSSecureCoding. + */ +static NSString *const kUserCodingKey = @"user"; + +- (nullable instancetype)initWithUser:(nullable FIRUser *)user + additionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo { + self = [super init]; + if (self) { + _additionalUserInfo = additionalUserInfo; + _user = user; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + FIRUser *user = + [aDecoder decodeObjectOfClass:[FIRUser class] forKey:kUserCodingKey]; + FIRAdditionalUserInfo *additionalUserInfo = + [aDecoder decodeObjectOfClass:[FIRAdditionalUserInfo class] + forKey:kAdditionalUserInfoCodingKey]; + + return [self initWithUser:user additionalUserInfo:additionalUserInfo]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_user forKey:kUserCodingKey]; + [aCoder encodeObject:_additionalUserInfo forKey:kAdditionalUserInfoCodingKey]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult_Internal.h new file mode 100644 index 0000000..b90b5fd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDataResult_Internal.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthDataResult.h" + +@interface FIRAuthDataResult () + +/** @fn initWithUser:additionalUserInfo: + @brief Designated initializer. + @param user The signed in user reference. + @param additionalUserInfo The additional user info if available. + */ +- (nullable instancetype)initWithUser:(nullable FIRUser *)user + additionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo + NS_DESIGNATED_INITIALIZER; + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.h new file mode 100644 index 0000000..03cadf7 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.h @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthUIDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthDefaultUIDelegate + @brief Class responsible for providing a default FIRAuthUIDelegte. + @remarks This class should be used in the case that a UIDelegate was expected and necessary to + continue a given flow, but none was provided. + */ +@interface FIRAuthDefaultUIDelegate : NSObject + +/** @fn defaultUIDelegate + @brief Unavailable. Please use @c +defaultUIDelegate: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn defaultUIDelegate + @brief Returns a default FIRAuthUIDelegate object. + @return The default FIRAuthUIDelegate object. + */ ++ (id)defaultUIDelegate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.m new file mode 100644 index 0000000..d5cd648 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDefaultUIDelegate.m @@ -0,0 +1,92 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthDefaultUIDelegate.h" + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAuthDefaultUIDelegate () + +/** @fn initWithViewController: + @brief Initializes the instance with a view controller. + @param viewController The view controller as the presenting view controller in @c + FIRAuthUIDelegate. + @return The initialized instance. + */ +- (instancetype)initWithViewController:(nullable UIViewController *)viewController NS_DESIGNATED_INITIALIZER; + +@end + +@implementation FIRAuthDefaultUIDelegate { + /** @var _viewController + @brief The presenting view controller. + */ + UIViewController *_viewController; +} + +- (instancetype)initWithViewController:(nullable UIViewController *)viewController { + self = [super init]; + if (self) { + _viewController = viewController; + } + return self; +} + +- (void)presentViewController:(UIViewController *)viewControllerToPresent + animated:(BOOL)flag + completion:(nullable void (^)(void))completion { + [_viewController presentViewController:viewControllerToPresent + animated:flag + completion:completion]; +} + +- (void)dismissViewControllerAnimated:(BOOL)flag completion:(nullable void (^)(void))completion { + [_viewController dismissViewControllerAnimated:flag completion:completion]; +} + ++ (id)defaultUIDelegate { + // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication + // responds to it. + static Class applicationClass = nil; + if (![GULAppEnvironmentUtil isAppExtension]) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + UIApplication *application = [applicationClass sharedApplication]; + UIViewController *topViewController = application.keyWindow.rootViewController; + while (true){ + if (topViewController.presentedViewController) { + topViewController = topViewController.presentedViewController; + } else if ([topViewController isKindOfClass:[UINavigationController class]]) { + UINavigationController *nav = (UINavigationController *)topViewController; + topViewController = nav.topViewController; + } else if ([topViewController isKindOfClass:[UITabBarController class]]) { + UITabBarController *tab = (UITabBarController *)topViewController; + topViewController = tab.selectedViewController; + } else { + break; + } + } + return [[FIRAuthDefaultUIDelegate alloc] initWithViewController:topViewController]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.h new file mode 100644 index 0000000..f8ddca5 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.h @@ -0,0 +1,63 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthDispatcherImplBlock + @brief The type of block which can be set as the implementation for @c + dispatchAfterDelay:queue:callback: . + + @param delay The delay in seconds after which the task will be scheduled to execute. + @param queue The dispatch queue on which the task will be submitted. + @param task The task (block) to be scheduled for future execution. + */ +typedef void(^FIRAuthDispatcherImplBlock)(NSTimeInterval delay, + dispatch_queue_t queue, + void (^task)(void)); + +/** @class FIRAuthDispatchAfter + @brief A utility class used to facilitate scheduling tasks to be executed in the future. + */ +@interface FIRAuthDispatcher : NSObject + +/** @property dispatchAfterImplementation + @brief Allows custom implementation of dispatchAfterDelay:queue:callback:. + @remarks Set to nil to restore default implementation. + */ +@property(nonatomic, nullable, copy) FIRAuthDispatcherImplBlock dispatchAfterImplementation; + +/** @fn dispatchAfterDelay:queue:callback: + @brief Schedules task in the future after a specified delay. + + @param delay The delay in seconds after which the task will be scheduled to execute. + @param queue The dispatch queue on which the task will be submitted. + @param task The task (block) to be scheduled for future execution. + */ + - (void)dispatchAfterDelay:(NSTimeInterval)delay + queue:(dispatch_queue_t)queue + task:(void (^)(void))task; + +/** @fn sharedInstance + @brief Gets the shared instance of this class. + @returns The shared instance of this clss + */ ++ (instancetype)sharedInstance; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.m new file mode 100644 index 0000000..78ed2e3 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthDispatcher.m @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthDispatcher.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAuthDispatcher + +@synthesize dispatchAfterImplementation = _dispatchAfterImplementation; + ++ (instancetype)sharedInstance { + static dispatch_once_t onceToken; + static FIRAuthDispatcher *sharedInstance; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (void)dispatchAfterDelay:(NSTimeInterval)delay + queue:(dispatch_queue_t)queue + task:(void (^)(void))task { + if (_dispatchAfterImplementation) { + _dispatchAfterImplementation(delay, queue, task); + return; + } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), queue, task); +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.h new file mode 100644 index 0000000..a8a937b --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.h @@ -0,0 +1,530 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRPhoneAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthErrorUtils + @brief Utility class used to construct @c NSError instances. + */ +@interface FIRAuthErrorUtils : NSObject + +/** @fn RPCRequestEncodingErrorWithUnderlyingError + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeRPCRequestEncodingError + code and a populated @c NSUnderlyingErrorKey in the @c NSError.userInfo dictionary. + @param underlyingError The value of the @c NSUnderlyingErrorKey key. + @remarks This error is used when an @c FIRAuthRPCRequest.unencodedHTTPRequestBodyWithError: + invocation returns an error. The error returned is wrapped in this internal error code. + */ ++ (NSError *)RPCRequestEncodingErrorWithUnderlyingError:(NSError *)underlyingError; + +/** @fn JSONSerializationErrorForUnencodableType + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeJSONSerializationError code. + @remarks This error is used when an @c NSJSONSerialization.isValidJSONObject: check fails, not + for when an error is returned from @c NSJSONSerialization.dataWithJSONObject:options:error:. + */ ++ (NSError *)JSONSerializationErrorForUnencodableType; + +/** @fn JSONSerializationErrorWithUnderlyingError: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeJSONSerializationError code, and the + @c underlyingError as the @c NSUnderlyingErrorKey value in the @c NSError.userInfo + dictionary. + @param underlyingError The value of the @c NSUnderlyingErrorKey key. + @remarks This error is used when an invocation of + @c NSJSONSerialization.dataWithJSONObject:options:error: returns an error. + */ ++ (NSError *)JSONSerializationErrorWithUnderlyingError:(NSError *)underlyingError; + +/** @fn networkErrorWithUnderlyingError: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeNetworkError code, and the + @c underlyingError as the @c NSUnderlyingErrorKey value in the @c NSError.userInfo + dictionary. + @param underlyingError The value of the @c NSUnderlyingErrorKey key. Should be the error from + GTM. + @remarks This error is used when a network request results in an error, and no body data was + returned. + */ ++ (NSError *)networkErrorWithUnderlyingError:(NSError *)underlyingError; + +/** @fn unexpectedErrorResponseWithUnderlyingError: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeNetworkError code, and the + @c underlyingError as the @c NSUnderlyingErrorKey value. + @param data The value of the @c FIRAuthErrorUserInfoDataKey key in the @c NSError.userInfo + dictionary. + @param underlyingError The value of the @c NSUnderlyingErrorKey key in the @c NSError.userInfo + dictionary. + @remarks This error is used when a network request results in an error, and unserializable body + data was returned. + */ ++ (NSError *)unexpectedErrorResponseWithData:(NSData *)data + underlyingError:(NSError *)underlyingError; + +/** @fn unexpectedErrorResponseWithDeserializedResponse: + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeUnexpectedErrorResponse + code, and a populated @c FIRAuthErrorUserInfoDeserializedResponseKey key in the + @c NSError.userInfo dictionary. + @param deserializedResponse The value of the @c FIRAuthErrorUserInfoDeserializedResponseKey key. + @remarks This error is used when a network request results in an error, and the body data was + deserializable as JSON, but couldn't be decoded as an error. + */ ++ (NSError *)unexpectedErrorResponseWithDeserializedResponse:(id)deserializedResponse; + +/** @fn malformedJWTErrorWithToken:underlyingError: + @brief Constructs an @c NSError with the code set to @c FIRAuthErrorCodeMalformedJWT and + populates the userInfo dictionary with an error message, the bad token, and an underlying + error that may have occurred when parsing. + @param token The token that failed to parse. + @param underlyingError The error that caused this error. If this parameter is nil, the + NSUnderlyingErrorKey value will not be set. + @remarks This error is returned when JWT parsing fails. + @returns An @c FIRAuthErrorCodeMalformedJWT error wrapping an underlying error, if available. + */ ++ (NSError *)malformedJWTErrorWithToken:(NSString *)token + underlyingError:(NSError *_Nullable)underlyingError; + +/** @fn unexpectedResponseWithData:underlyingError: + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeUnexpectedResponse + code, and a populated @c FIRAuthErrorUserInfoDataKey key in the @c NSError.userInfo + dictionary. + @param data The value of the @c FIRAuthErrorUserInfoDataKey key in the @c NSError.userInfo + dictionary. + @param underlyingError The value of the @c NSUnderlyingErrorKey key in the @c NSError.userInfo + dictionary. + @remarks This error is used when a network request is apparently successful, but the body data + couldn't be deserialized as JSON. + */ ++ (NSError *)unexpectedResponseWithData:(NSData *)data + underlyingError:(NSError *)underlyingError;; + +/** @fn unexpectedResponseWithDeserializedResponse: + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeUnexpectedResponse + code, and a populated @c FIRAuthErrorUserInfoDeserializedResponseKey key in the + @c NSError.userInfo dictionary. + @param deserializedResponse The value of the @c FIRAuthErrorUserInfoDeserializedResponseKey key. + @remarks This error is used when a network request is apparently successful, the body data was + successfully deserialized as JSON, but the JSON wasn't a dictionary. + */ ++ (NSError *)unexpectedResponseWithDeserializedResponse:(id)deserializedResponse; + +/** @fn unexpectedResponseWithDeserializedResponse:underlyingError: + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeUnexpectedResponse + code, and populated @c FIRAuthErrorUserInfoDeserializedResponseKey and + @c NSUnderlyingErrorKey keys in the @c NSError.userInfo dictionary. + @param deserializedResponse The value of the @c FIRAuthErrorUserInfoDeserializedResponseKey key. + @param underlyingError The value of the @c NSUnderlyingErrorKey key. + @remarks This error is used when a network request was apparently successful, the body data was + successfully deserialized as JSON, but the data type of the response was unexpected. + */ ++ (NSError *)unexpectedResponseWithDeserializedResponse:(nullable id)deserializedResponse + underlyingError:(NSError *)underlyingError; + +/** @fn RPCResponseDecodingErrorWithDeserializedResponse:underlyingError: + @brief Constructs an @c NSError with the @c FIRAuthInternalErrorCodeRPCResponseDecodingError + code, and populated @c FIRAuthErrorUserInfoDeserializedResponseKey and + @c NSUnderlyingErrorKey keys in the @c NSError.userInfo dictionary. + @param deserializedResponse The value of the @c FIRAuthErrorUserInfoDeserializedResponseKey key. + @param underlyingError The value of the @c NSUnderlyingErrorKey key. + @remarks This error is used when an invocation of @c FIRAuthRPCResponse.setWithDictionary:error: + resulted in an error. + */ ++ (NSError *)RPCResponseDecodingErrorWithDeserializedResponse:(id)deserializedResponse + underlyingError:(NSError *)underlyingError; + +/** @fn emailAlreadyInUseErrorWithEmail: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeEmailExists code. + @param email The email address that is already in use. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)emailAlreadyInUseErrorWithEmail:(nullable NSString *)email; + +/** @fn userDisabledErrorWithMessageWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeUserDisabled code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)userDisabledErrorWithMessage:(nullable NSString *)message; + +/** @fn wrongPasswordErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeWrongPassword code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)wrongPasswordErrorWithMessage:(nullable NSString *)message; + +/** @fn tooManyRequestsErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeTooManyRequests Code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)tooManyRequestsErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidCustomTokenErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidCustomToken code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidCustomTokenErrorWithMessage:(nullable NSString *)message; + +/** @fn customTokenMistmatchErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeCustomTokenMismatch code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)customTokenMistmatchErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidCredentialErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidCredential code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidCredentialErrorWithMessage:(nullable NSString *)message; + +/** @fn requiresRecentLoginError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeRequiresRecentLogin code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)requiresRecentLoginErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidUserTokenErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidUserToken code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidUserTokenErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidEmailErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidEmail code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidEmailErrorWithMessage:(nullable NSString *)message; + +/** @fn accountExistsWithDifferentCredentialErrorWithEmail: + @brief Constructs an @c NSError with the @c FIRAuthErrorAccountExistsWithDifferentCredential + code. + @param Email The email address that is already associated with an existing account + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)accountExistsWithDifferentCredentialErrorWithEmail:(nullable NSString *)Email; + +/** @fn providerAlreadyLinkedErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeProviderAlreadyLinked code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)providerAlreadyLinkedError; + +/** @fn noSuchProviderError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeNoSuchProvider code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)noSuchProviderError; + +/** @fn userTokenExpiredErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeUserTokenExpired code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)userTokenExpiredErrorWithMessage:(nullable NSString *)message; + +/** @fn userNotFoundErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeUserNotFound code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)userNotFoundErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidLocalAPIKeyErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidAPIKey code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidAPIKeyError; + +/** @fn userMismatchError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeUserMismatch code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)userMismatchError; + +/** @fn credentialAlreadyInUseErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeCredentialAlreadyInUse code. + @param message Error message from the backend, if any. + @param credential Auth credential to be added to the Error User Info dictionary. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)credentialAlreadyInUseErrorWithMessage:(nullable NSString *)message + credential:(nullable FIRPhoneAuthCredential *)credential; + +/** @fn operationNotAllowedErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeOperationNotAllowed code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)operationNotAllowedErrorWithMessage:(nullable NSString *)message; + +/** @fn weakPasswordErrorWithServerResponseReason: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeWeakPassword code. + @param serverResponseReason A more detailed explanation string from server response. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)weakPasswordErrorWithServerResponseReason:(nullable NSString *)serverResponseReason; + +/** @fn appNotAuthorizedError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeAppNotAuthorized code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)appNotAuthorizedError; + +/** @fn expiredActionCodeErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeExpiredActionCode code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)expiredActionCodeErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidActionCodeErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidActionCode code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidActionCodeErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidMessagePayloadError: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidMessagePayload code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidMessagePayloadErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidSenderErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidSender code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidSenderErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidRecipientEmailError: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidRecipientEmail code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidRecipientEmailErrorWithMessage:(nullable NSString *)message; + +/** @fn missingIosBundleIDErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingIosBundleID code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingIosBundleIDErrorWithMessage:(nullable NSString *)message; + +/** @fn missingAndroidPackageNameErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingAndroidPackageName code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingAndroidPackageNameErrorWithMessage:(nullable NSString *)message; + +/** @fn unauthorizedDomainErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeUnauthorizedDomain code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)unauthorizedDomainErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidContinueURIErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidContinueURI code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidContinueURIErrorWithMessage:(nullable NSString *)message; + +/** @fn missingContinueURIErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingContinueURI code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingContinueURIErrorWithMessage:(nullable NSString *)message; + +/** @fn missingEmailErrorWithMessage + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingEmail code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingEmailErrorWithMessage:(nullable NSString *)message; + +/** @fn missingPhoneNumberErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingPhoneNumber code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingPhoneNumberErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidPhoneNumberErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidPhoneNumber code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidPhoneNumberErrorWithMessage:(nullable NSString *)message; + +/** @fn missingVerificationCodeErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingVerificationCode code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingVerificationCodeErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidVerificationCodeErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidVerificationCode code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidVerificationCodeErrorWithMessage:(nullable NSString *)message; + +/** @fn missingVerificationIDErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingVerificationID code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingVerificationIDErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidVerificationIDErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeInvalidVerificationID code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidVerificationIDErrorWithMessage:(nullable NSString *)message; + +/** @fn sessionExpiredErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeSessionExpired code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)sessionExpiredErrorWithMessage:(nullable NSString *)message; + +/** @fn missingAppCredentialWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorMissingCredential code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingAppCredentialWithMessage:(nullable NSString *)message; + +/** @fn invalidAppCredentialWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorInvalidCredential code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)invalidAppCredentialWithMessage:(nullable NSString *)message; + +/** @fn quotaExceededErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeQuotaExceeded code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)quotaExceededErrorWithMessage:(nullable NSString *)message; + +/** @fn missingAppTokenErrorWithUnderlyingError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeMissingAppToken code. + @param underlyingError The underlying error, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)missingAppTokenErrorWithUnderlyingError:(nullable NSError *)underlyingError; + +/** @fn localPlayerNotAuthenticatedError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeLocalPlayerNotAuthenticated code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)localPlayerNotAuthenticatedError; + +/** @fn notificationNotForwardedError + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeNotificationNotForwarded code. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)notificationNotForwardedError; + +/** @fn appNotVerifiedErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeAppNotVerified code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)appNotVerifiedErrorWithMessage:(nullable NSString *)message; + +/** @fn captchaCheckFailedErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCaptchaCheckFailed code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)captchaCheckFailedErrorWithMessage:(nullable NSString *)message; + +/** @fn webContextAlreadyPresentedErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeWebContextAlreadyPresented code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)webContextAlreadyPresentedErrorWithMessage:(nullable NSString *)message; + +/** @fn webContextCancelledErrorWithMessage: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeWebContextCancelled code. + @param message Error message from the backend, if any. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)webContextCancelledErrorWithMessage:(nullable NSString *)message; + +/** @fn appVerificationUserInteractionFailureWithReason: + @brief Constructs an @c NSError with the @c + FIRAuthErrorCodeAppVerificationUserInteractionFailure code. + @param reason Reason for error, returned via URL response. + @return The NSError instance associated with the given FIRAuthError. + */ ++ (NSError *)appVerificationUserInteractionFailureWithReason:(NSString *)reason; + +/** @fn URLResponseErrorWithCode:message: + @brief Constructs an @c NSError with the code and message provided. + @param message Error message from the backend, if any. + @return The nullable NSError instance associated with the given error message, if one is found. + */ ++ (nullable NSError *)URLResponseErrorWithCode:(NSString *)code message:(nullable NSString *)message; + +/** @fn nullUserErrorWithMessage: + @brief Constructs an @c NSError with the code and message provided. + @param message Error message from the backend, if any. + @return The nullable NSError instance associated with the given error message, if one is found. + */ ++ (NSError *)nullUserErrorWithMessage:(nullable NSString *)message; + +/** @fn invalidDynamicLinkDomainErrorWithMessage: + @brief Constructs an @c NSError with the code and message provided. + @param message Error message from the backend, if any. + @return The nullable NSError instance associated with the given error message, if one is found. + */ ++ (NSError *)invalidDynamicLinkDomainErrorWithMessage:(nullable NSString *)message; + +/** @fn keychainErrorWithFunction:status: + @brief Constructs an @c NSError with the @c FIRAuthErrorCodeKeychainError code. + @param keychainFunction The keychain function which was invoked and yielded an unexpected + response. The @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo + dictionary will contain a string partially comprised of this value. + @param status The response status from the invoked keychain function. The + @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo dictionary will contain + a string partially comprised of this value. + */ ++ (NSError *)keychainErrorWithFunction:(NSString *)keychainFunction status:(OSStatus)status; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.m new file mode 100644 index 0000000..05bd867 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthErrorUtils.m @@ -0,0 +1,1060 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthErrorUtils.h" + +#import "FIRAuthCredential.h" +#import "FIRAuthInternalErrors.h" + +NS_ASSUME_NONNULL_BEGIN + +NSString *const FIRAuthErrorDomain = @"FIRAuthErrorDomain"; + +NSString *const FIRAuthInternalErrorDomain = @"FIRAuthInternalErrorDomain"; + +NSString *const FIRAuthErrorUserInfoDeserializedResponseKey = + @"FIRAuthErrorUserInfoDeserializedResponseKey"; + +NSString *const FIRAuthErrorUserInfoDataKey = @"FIRAuthErrorUserInfoDataKey"; + +NSString *const FIRAuthErrorUserInfoEmailKey = @"FIRAuthErrorUserInfoEmailKey"; + +NSString *const FIRAuthErrorNameKey = @"error_name"; + +NSString *const FIRAuthUpdatedCredentialKey = @"FIRAuthUpdatedCredentialKey"; + +/** @var kServerErrorDetailMarker + @brief This marker indicates that the server error message contains a detail error message which + should be used instead of the hardcoded client error message. + */ +static NSString *const kServerErrorDetailMarker = @" : "; + +#pragma mark - URL response error codes + +/** @var kURLResponseErrorCodeInvalidClientID + @brief Error code that indicates that the client ID provided was invalid. + */ +static NSString *const kURLResponseErrorCodeInvalidClientID = @"auth/invalid-oauth-client-id"; + +/** @var kURLResponseErrorCodeNetworkRequestFailed + @brief Error code that indicates that a network request within the SFSafariViewController or + UIWebView failed. + */ +static NSString *const kURLResponseErrorCodeNetworkRequestFailed = @"auth/network-request-failed"; + +/** @var kURLResponseErrorCodeInternalError + @brief Error code that indicates that an internal error occurred within the + SFSafariViewController or UIWebView failed. + */ +static NSString *const kURLResponseErrorCodeInternalError = @"auth/internal-error"; + +#pragma mark - Standard Error Messages + +/** @var kFIRAuthErrorMessageInvalidCustomToken + @brief Message for @c FIRAuthErrorCodeInvalidCustomToken error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidCustomToken = @"The custom token format is " + "incorrect. Please check the documentation."; + +/** @var kFIRAuthErrorMessageCustomTokenMismatch + @brief Message for @c FIRAuthErrorCodeCustomTokenMismatch error code. + */ +static NSString *const kFIRAuthErrorMessageCustomTokenMismatch = @"The custom token corresponds to " + "a different audience."; + +/** @var kFIRAuthErrorMessageInvalidEmail + @brief Message for @c FIRAuthErrorCodeInvalidEmail error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidEmail = @"The email address is badly formatted."; + +/** @var kFIRAuthErrorMessageInvalidCredential + @brief Message for @c FIRAuthErrorCodeInvalidCredential error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidCredential = @"The supplied auth credential is " + "malformed or has expired."; + +/** @var kFIRAuthErrorMessageUserDisabled + @brief Message for @c FIRAuthErrorCodeUserDisabled error code. + */ +static NSString *const kFIRAuthErrorMessageUserDisabled = @"The user account has been disabled by " + "an administrator."; + +/** @var kFIRAuthErrorMessageEmailAlreadyInUse + @brief Message for @c FIRAuthErrorCodeEmailAlreadyInUse error code. + */ +static NSString *const kFIRAuthErrorMessageEmailAlreadyInUse = @"The email address is already in " + "use by another account."; + +/** @var kFIRAuthErrorMessageWrongPassword + @brief Message for @c FIRAuthErrorCodeWrongPassword error code. + */ +static NSString *const kFIRAuthErrorMessageWrongPassword = @"The password is invalid or the user " + "does not have a password."; + +/** @var kFIRAuthErrorMessageTooManyRequests + @brief Message for @c FIRAuthErrorCodeTooManyRequests error code. + */ +static NSString *const kFIRAuthErrorMessageTooManyRequests = @"We have blocked all requests from " + "this device due to unusual activity. Try again later."; + +/** @var kFIRAuthErrorMessageAccountExistsWithDifferentCredential + @brief Message for @c FIRAuthErrorCodeAccountExistsWithDifferentCredential error code. + */ +static NSString *const kFIRAuthErrorMessageAccountExistsWithDifferentCredential = @"An account " + "already exists with the same email address but different sign-in credentials. Sign in using a " + "provider associated with this email address."; + +/** @var kFIRAuthErrorMessageRequiresRecentLogin + @brief Message for @c FIRAuthErrorCodeRequiresRecentLogin error code. + */ +static NSString *const kFIRAuthErrorMessageRequiresRecentLogin= @"This operation is sensitive and " + "requires recent authentication. Log in again before retrying this request."; + +/** @var kFIRAuthErrorMessageProviderAlreadyLinked + @brief Message for @c FIRAuthErrorCodeProviderAlreadyExists error code. + */ +static NSString *const kFIRAuthErrorMessageProviderAlreadyLinked = + @"[ERROR_PROVIDER_ALREADY_LINKED] - User can only be linked to one identity for the given " + "provider."; + +/** @var kFIRAuthErrorMessageNoSuchProvider + @brief Message for @c FIRAuthErrorCodeNoSuchProvider error code. + */ +static NSString *const kFIRAuthErrorMessageNoSuchProvider = @"User was not linked to an account " + "with the given provider."; + +/** @var kFIRAuthErrorMessageInvalidUserToken + @brief Message for @c FIRAuthErrorCodeInvalidUserToken error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidUserToken = @"This user's credential isn't valid " + "for this project. This can happen if the user's token has been tampered with, or if the user " + "doesn’t belong to the project associated with the API key used in your request."; + +/** @var kFIRAuthErrorMessageNetworkError + @brief Message for @c FIRAuthErrorCodeNetworkError error code. + */ +static NSString *const kFIRAuthErrorMessageNetworkError = @"Network error (such as timeout, " + "interrupted connection or unreachable host) has occurred."; + +/** @var kFIRAuthErrorMessageKeychainError + @brief Message for @c FIRAuthErrorCodeKeychainError error code. + */ +static NSString *const kFIRAuthErrorMessageKeychainError = @"An error occurred when accessing the " + "keychain. The @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo dictionary " + "will contain more information about the error encountered"; + +/** @var kFIRAuthErrorMessageUserTokenExpired + @brief Message for @c FIRAuthErrorCodeTokenExpired error code. + */ +static NSString *const kFIRAuthErrorMessageUserTokenExpired = @"The user's credential is no longer " + "valid. The user must sign in again."; + +/** @var kFIRAuthErrorMessageUserNotFound + @brief Message for @c FIRAuthErrorCodeUserNotFound error code. + */ +static NSString *const kFIRAuthErrorMessageUserNotFound = @"There is no user record corresponding " + "to this identifier. The user may have been deleted."; + +/** @var kFIRAuthErrorMessageInvalidAPIKey + @brief Message for @c FIRAuthErrorCodeInvalidAPIKey error code. + @remarks This error is not thrown by the server. + */ +static NSString *const kFIRAuthErrorMessageInvalidAPIKey = @"An invalid API Key was supplied in " + "the request."; + +/** @var kFIRAuthErrorMessageUserMismatch. + @brief Message for @c FIRAuthErrorCodeInvalidAPIKey error code. + */ +static NSString *const FIRAuthErrorMessageUserMismatch = @"The supplied credentials do not " + "correspond to the previously signed in user."; + +/** @var kFIRAuthErrorMessageCredentialAlreadyInUse + @brief Message for @c FIRAuthErrorCodeCredentialAlreadyInUse error code. + */ +static NSString *const kFIRAuthErrorMessageCredentialAlreadyInUse = @"This credential is already " + "associated with a different user account."; + +/** @var kFIRAuthErrorMessageOperationNotAllowed + @brief Message for @c FIRAuthErrorCodeOperationNotAllowed error code. + */ +static NSString *const kFIRAuthErrorMessageOperationNotAllowed = @"The given sign-in provider is " + "disabled for this Firebase project. Enable it in the Firebase console, under the sign-in " + "method tab of the Auth section."; + +/** @var kFIRAuthErrorMessageWeakPassword + @brief Message for @c FIRAuthErrorCodeWeakPassword error code. + */ +static NSString *const kFIRAuthErrorMessageWeakPassword = @"The password must be 6 characters long " + "or more."; + +/** @var kFIRAuthErrorMessageAppNotAuthorized + @brief Message for @c FIRAuthErrorCodeAppNotAuthorized error code. + */ +static NSString *const kFIRAuthErrorMessageAppNotAuthorized = @"This app is not authorized to use " + "Firebase Authentication with the provided API key. Review your key configuration in the " + "Google API console and ensure that it accepts requests from your app's bundle ID."; + +/** @var kFIRAuthErrorMessageExpiredActionCode + @brief Message for @c FIRAuthErrorCodeExpiredActionCode error code. + */ +static NSString *const kFIRAuthErrorMessageExpiredActionCode = @"The action code has expired."; + +/** @var kFIRAuthErrorMessageInvalidActionCode + @brief Message for @c FIRAuthErrorCodeInvalidActionCode error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidActionCode = @"The action code is invalid. This " + "can happen if the code is malformed, expired, or has already been used."; + +/** @var kFIRAuthErrorMessageInvalidMessagePayload + @brief Message for @c FIRAuthErrorCodeInvalidMessagePayload error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidMessagePayload = @"The action code is invalid. " + "This can happen if the code is malformed, expired, or has already been used."; + +/** @var kFIRAuthErrorMessageInvalidSender + @brief Message for @c FIRAuthErrorCodeInvalidSender error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidSender = @"The email template corresponding to " + "this action contains invalid characters in its message. Please fix by going to the Auth email " + "templates section in the Firebase Console."; + +/** @var kFIRAuthErrorMessageInvalidRecipientEmail + @brief Message for @c FIRAuthErrorCodeInvalidRecipient error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidRecipientEmail = @"The action code is invalid. " + "This can happen if the code is malformed, expired, or has already been used."; + +/** @var kFIRAuthErrorMessageMissingIosBundleID + @brief Message for @c FIRAuthErrorCodeMissingIosbundleID error code. + */ +static NSString *const kFIRAuthErrorMessageMissingIosBundleID = + @"An iOS Bundle ID must be provided if an App Store ID is provided."; + +/** @var kFIRAuthErrorMessageMissingAndroidPackageName + @brief Message for @c FIRAuthErrorCodeMissingAndroidPackageName error code. + */ +static NSString *const kFIRAuthErrorMessageMissingAndroidPackageName = + @"An Android Package Name must be provided if the Android App is required to be installed."; + +/** @var kFIRAuthErrorMessageUnauthorizedDomain + @brief Message for @c FIRAuthErrorCodeUnauthorizedDomain error code. + */ +static NSString *const kFIRAuthErrorMessageUnauthorizedDomain = @"The domain of the continue URL " + "is not whitelisted. Please whitelist the domain in the Firebase console."; + +/** @var kFIRAuthErrorMessageInvalidContinueURI + @brief Message for @c FIRAuthErrorCodeInvalidContinueURI error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidContinueURI = + @"The continue URL provided in the request is invalid."; + +/** @var kFIRAuthErrorMessageMissingEmail + @brief Message for @c FIRAuthErrorCodeMissingEmail error code. + */ +static NSString *const kFIRAuthErrorMessageMissingEmail = @"An email address must be provided."; + +/** @var kFIRAuthErrorMessageMissingContinueURI + @brief Message for @c FIRAuthErrorCodeMissingContinueURI error code. + */ +static NSString *const kFIRAuthErrorMessageMissingContinueURI = + @"A continue URL must be provided in the request."; + +/** @var kFIRAuthErrorMessageMissingPhoneNumber + @brief Message for @c FIRAuthErrorCodeMissingPhoneNumber error code. + */ +static NSString *const kFIRAuthErrorMessageMissingPhoneNumber = + @"To send verification codes, provide a phone number for the recipient."; + +/** @var kFIRAuthErrorMessageInvalidPhoneNumber + @brief Message for @c FIRAuthErrorCodeInvalidPhoneNumber error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidPhoneNumber = + @"The format of the phone number provided is incorrect. Please enter the phone number in a " + "format that can be parsed into E.164 format. E.164 phone numbers are written in the format " + "[+][country code][subscriber number including area code]."; + +/** @var kFIRAuthErrorMessageMissingVerificationCode + @brief Message for @c FIRAuthErrorCodeMissingVerificationCode error code. + */ +static NSString *const kFIRAuthErrorMessageMissingVerificationCode = + @"The phone auth credential was created with an empty SMS verification Code."; + +/** @var kFIRAuthErrorMessageInvalidVerificationCode + @brief Message for @c FIRAuthErrorCodeInvalidVerificationCode error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidVerificationCode = + @"The SMS verification code used to create the phone auth credential is invalid. Please resend " + "the verification code SMS and be sure to use the verification code provided by the user."; + +/** @var kFIRAuthErrorMessageMissingVerificationID + @brief Message for @c FIRAuthErrorCodeInvalidVerificationID error code. + */ +static NSString *const kFIRAuthErrorMessageMissingVerificationID = + @"The phone auth credential was created with an empty verification ID."; + +/** @var kFIRAuthErrorMessageInvalidVerificationID + @brief Message for @c FIRAuthErrorCodeInvalidVerificationID error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidVerificationID = + @"The verification ID used to create the phone auth credential is invalid."; + +/** @var kFIRAuthErrorMessageLocalPlayerNotAuthenticated + @brief Message for @c FIRAuthErrorCodeLocalPlayerNotAuthenticated error code. + */ +static NSString *const kFIRAuthErrorMessageLocalPlayerNotAuthenticated = + @"The local player is not authenticated. Please log the local player in to Game Center."; + +/** @var kFIRAuthErrorMessageSessionExpired + @brief Message for @c FIRAuthErrorCodeSessionExpired error code. + */ +static NSString *const kFIRAuthErrorMessageSessionExpired = @"The SMS code has expired. Please " + @"re-send the verification code to try again."; + +/** @var kFIRAuthErrorMessageMissingAppCredential + @brief Message for @c FIRAuthErrorCodeMissingAppCredential error code. + */ +static NSString *const kFIRAuthErrorMessageMissingAppCredential = @"The phone verification request " + "is missing an APNs Device token. Firebase Auth automatically detects APNs Device Tokens, " + "however, if method swizzling is disabled, the APNs token must be set via the APNSToken " + "property on FIRAuth or by calling setAPNSToken:type on FIRAuth."; + +/** @var kFIRAuthErrorMessageInvalidAppCredential + @brief Message for @c FIRAuthErrorCodeInvalidAppCredential error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidAppCredential = @"The APNs device token provided " + "is either incorrect or does not match the private certificate uploaded to the Firebase " + "Console."; + +/** @var kFIRAuthErrorMessageQuotaExceeded + @brief Message for @c FIRAuthErrorCodeQuotaExceeded error code. + */ +static NSString *const kFIRAuthErrorMessageQuotaExceeded = @"The phone verification quota for this " + "project has been exceeded."; + +/** @var kFIRAuthErrorMessageMissingAppToken + @brief Message for @c FIRAuthErrorCodeMissingAppToken error code. + */ +static NSString *const kFIRAuthErrorMessageMissingAppToken = @"There seems to be a problem with " + "your project's Firebase phone number authentication set-up, please make sure to follow the " + "instructions found at https://firebase.google.com/docs/auth/ios/phone-auth"; + +/** @var kFIRAuthErrorMessageMissingAppToken + @brief Message for @c FIRAuthErrorCodeMissingAppToken error code. + */ +static NSString *const kFIRAuthErrorMessageNotificationNotForwarded = @"If app delegate swizzling " + "is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to " + "FIRAuth's canHandleNotificaton: method."; + +/** @var kFIRAuthErrorMessageAppNotVerified + @brief Message for @c FIRAuthErrorCodeMissingAppToken error code. + */ +static NSString *const kFIRAuthErrorMessageAppNotVerified = @"Firebase could not retrieve the " + "silent push notification and therefore could not verify your app. Ensure that you configured " + "your app correctly to receive push notifications."; + +/** @var kFIRAuthErrorMessageCaptchaCheckFailed + @brief Message for @c FIRAuthErrorCodeCaptchaCheckFailed error code. + */ +static NSString *const kFIRAuthErrorMessageCaptchaCheckFailed = @"The reCAPTCHA response token " + "provided is either invalid, expired or already"; + +/** @var kFIRAuthErrorMessageWebContextAlreadyPresented + @brief Message for @c FIRAuthErrorCodeWebContextAlreadyPresented error code. + */ +static NSString *const kFIRAuthErrorMessageWebContextAlreadyPresented = @"User interaction is " + "still ongoing, another view cannot be presented."; + +/** @var kFIRAuthErrorMessageWebContextCancelled + @brief Message for @c FIRAuthErrorCodeWebContextCancelled error code. + */ +static NSString *const kFIRAuthErrorMessageWebContextCancelled = @"The interaction was cancelled " + "by the user."; + +/** @var kFIRAuthErrorMessageInvalidClientID + @brief Message for @c FIRAuthErrorCodeInvalidClientID error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidClientID = @"The OAuth client ID provided is " + "either invalid or does not match the specified API key."; + +/** @var kFIRAuthErrorMessageWebRequestFailed + @brief Message for @c FIRAuthErrorCodeWebRequestFailed error code. + */ +static NSString *const kFIRAuthErrorMessageWebRequestFailed = @"A network error (such as timeout, " + "interrupted connection, or unreachable host) has occurred within the web context."; + +/** @var kFIRAuthErrorMessageWebInternalError + @brief Message for @c FIRAuthErrorCodeWebInternalError error code. + */ +static NSString *const kFIRAuthErrorMessageWebInternalError = @"An internal error has occurred " + "within the SFSafariViewController or UIWebView."; + +/** @var kFIRAuthErrorMessageAppVerificationUserInteractionFailure + @brief Message for @c FIRAuthErrorCodeInvalidClientID error code. + */ +static NSString *const kFIRAuthErrorMessageAppVerificationUserInteractionFailure = @"The app " + "verification process has failed, print and inspect the error details for more information"; + +/** @var kFIRAuthErrorMessageNullUser + @brief Message for @c FIRAuthErrorCodeNullUser error code. + */ +static NSString *const kFIRAuthErrorMessageNullUser = @"A null user object was provided as the " + "argument for an operation which requires a non-null user object."; + +/** @var kFIRAuthErrorMessageInvalidDynamicLinkDomain + @brief Message for @c kFIRAuthErrorMessageInvalidDynamicLinkDomain error code. + */ +static NSString *const kFIRAuthErrorMessageInvalidDynamicLinkDomain = @"The " + "Firebase Dynamic Link domain used is either not configured or is unauthorized " + "for the current project."; + +/** @var kFIRAuthErrorMessageInternalError + @brief Message for @c FIRAuthErrorCodeInternalError error code. + */ +static NSString *const kFIRAuthErrorMessageInternalError = @"An internal error has occurred, " + "print and inspect the error details for more information."; + +/** @var kFIRAuthErrorMessageMalformedJWT + @brief Error message constant describing @c FIRAuthErrorCodeMalformedJWT errors. + */ +static NSString *const kFIRAuthErrorMessageMalformedJWT = + @"Failed to parse JWT. Check the userInfo dictionary for the full token."; + +/** @var FIRAuthErrorDescription + @brief The error descrioption, based on the error code. + @remarks No default case so that we get a compiler warning if a new value was added to the enum. + */ +static NSString *FIRAuthErrorDescription(FIRAuthErrorCode code) { + switch (code) { + case FIRAuthErrorCodeInvalidCustomToken: + return kFIRAuthErrorMessageInvalidCustomToken; + case FIRAuthErrorCodeCustomTokenMismatch: + return kFIRAuthErrorMessageCustomTokenMismatch; + case FIRAuthErrorCodeInvalidEmail: + return kFIRAuthErrorMessageInvalidEmail; + case FIRAuthErrorCodeInvalidCredential: + return kFIRAuthErrorMessageInvalidCredential; + case FIRAuthErrorCodeUserDisabled: + return kFIRAuthErrorMessageUserDisabled; + case FIRAuthErrorCodeEmailAlreadyInUse: + return kFIRAuthErrorMessageEmailAlreadyInUse; + case FIRAuthErrorCodeWrongPassword: + return kFIRAuthErrorMessageWrongPassword; + case FIRAuthErrorCodeTooManyRequests: + return kFIRAuthErrorMessageTooManyRequests; + case FIRAuthErrorCodeAccountExistsWithDifferentCredential: + return kFIRAuthErrorMessageAccountExistsWithDifferentCredential; + case FIRAuthErrorCodeRequiresRecentLogin: + return kFIRAuthErrorMessageRequiresRecentLogin; + case FIRAuthErrorCodeProviderAlreadyLinked: + return kFIRAuthErrorMessageProviderAlreadyLinked; + case FIRAuthErrorCodeNoSuchProvider: + return kFIRAuthErrorMessageNoSuchProvider; + case FIRAuthErrorCodeInvalidUserToken: + return kFIRAuthErrorMessageInvalidUserToken; + case FIRAuthErrorCodeNetworkError: + return kFIRAuthErrorMessageNetworkError; + case FIRAuthErrorCodeKeychainError: + return kFIRAuthErrorMessageKeychainError; + case FIRAuthErrorCodeUserTokenExpired: + return kFIRAuthErrorMessageUserTokenExpired; + case FIRAuthErrorCodeUserNotFound: + return kFIRAuthErrorMessageUserNotFound; + case FIRAuthErrorCodeInvalidAPIKey: + return kFIRAuthErrorMessageInvalidAPIKey; + case FIRAuthErrorCodeCredentialAlreadyInUse: + return kFIRAuthErrorMessageCredentialAlreadyInUse; + case FIRAuthErrorCodeInternalError: + return kFIRAuthErrorMessageInternalError; + case FIRAuthErrorCodeUserMismatch: + return FIRAuthErrorMessageUserMismatch; + case FIRAuthErrorCodeOperationNotAllowed: + return kFIRAuthErrorMessageOperationNotAllowed; + case FIRAuthErrorCodeWeakPassword: + return kFIRAuthErrorMessageWeakPassword; + case FIRAuthErrorCodeAppNotAuthorized: + return kFIRAuthErrorMessageAppNotAuthorized; + case FIRAuthErrorCodeExpiredActionCode: + return kFIRAuthErrorMessageExpiredActionCode; + case FIRAuthErrorCodeInvalidActionCode: + return kFIRAuthErrorMessageInvalidActionCode; + case FIRAuthErrorCodeInvalidSender: + return kFIRAuthErrorMessageInvalidSender; + case FIRAuthErrorCodeInvalidMessagePayload: + return kFIRAuthErrorMessageInvalidMessagePayload; + case FIRAuthErrorCodeInvalidRecipientEmail: + return kFIRAuthErrorMessageInvalidRecipientEmail; + case FIRAuthErrorCodeMissingIosBundleID: + return kFIRAuthErrorMessageMissingIosBundleID; + case FIRAuthErrorCodeMissingAndroidPackageName: + return kFIRAuthErrorMessageMissingAndroidPackageName; + case FIRAuthErrorCodeUnauthorizedDomain: + return kFIRAuthErrorMessageUnauthorizedDomain; + case FIRAuthErrorCodeInvalidContinueURI: + return kFIRAuthErrorMessageInvalidContinueURI; + case FIRAuthErrorCodeMissingContinueURI: + return kFIRAuthErrorMessageMissingContinueURI; + case FIRAuthErrorCodeMissingEmail: + return kFIRAuthErrorMessageMissingEmail; + case FIRAuthErrorCodeMissingPhoneNumber: + return kFIRAuthErrorMessageMissingPhoneNumber; + case FIRAuthErrorCodeInvalidPhoneNumber: + return kFIRAuthErrorMessageInvalidPhoneNumber; + case FIRAuthErrorCodeMissingVerificationCode: + return kFIRAuthErrorMessageMissingVerificationCode; + case FIRAuthErrorCodeInvalidVerificationCode: + return kFIRAuthErrorMessageInvalidVerificationCode; + case FIRAuthErrorCodeMissingVerificationID: + return kFIRAuthErrorMessageMissingVerificationID; + case FIRAuthErrorCodeInvalidVerificationID: + return kFIRAuthErrorMessageInvalidVerificationID; + case FIRAuthErrorCodeSessionExpired: + return kFIRAuthErrorMessageSessionExpired; + case FIRAuthErrorCodeMissingAppCredential: + return kFIRAuthErrorMessageMissingAppCredential; + case FIRAuthErrorCodeInvalidAppCredential: + return kFIRAuthErrorMessageInvalidAppCredential; + case FIRAuthErrorCodeQuotaExceeded: + return kFIRAuthErrorMessageQuotaExceeded; + case FIRAuthErrorCodeMissingAppToken: + return kFIRAuthErrorMessageMissingAppToken; + case FIRAuthErrorCodeNotificationNotForwarded: + return kFIRAuthErrorMessageNotificationNotForwarded; + case FIRAuthErrorCodeAppNotVerified: + return kFIRAuthErrorMessageAppNotVerified; + case FIRAuthErrorCodeCaptchaCheckFailed: + return kFIRAuthErrorMessageCaptchaCheckFailed; + case FIRAuthErrorCodeWebContextAlreadyPresented: + return kFIRAuthErrorMessageWebContextAlreadyPresented; + case FIRAuthErrorCodeWebContextCancelled: + return kFIRAuthErrorMessageWebContextCancelled; + case FIRAuthErrorCodeInvalidClientID: + return kFIRAuthErrorMessageInvalidClientID; + case FIRAuthErrorCodeAppVerificationUserInteractionFailure: + return kFIRAuthErrorMessageAppVerificationUserInteractionFailure; + case FIRAuthErrorCodeWebNetworkRequestFailed: + return kFIRAuthErrorMessageWebRequestFailed; + case FIRAuthErrorCodeNullUser: + return kFIRAuthErrorMessageNullUser; + case FIRAuthErrorCodeInvalidDynamicLinkDomain: + return kFIRAuthErrorMessageInvalidDynamicLinkDomain; + case FIRAuthErrorCodeWebInternalError: + return kFIRAuthErrorMessageWebInternalError; + case FIRAuthErrorCodeMalformedJWT: + return kFIRAuthErrorMessageMalformedJWT; + case FIRAuthErrorCodeLocalPlayerNotAuthenticated: + return kFIRAuthErrorMessageLocalPlayerNotAuthenticated; + } +} + +/** @var FIRAuthErrorCodeString + @brief The the error short string, based on the error code. + @remarks No default case so that we get a compiler warning if a new value was added to the enum. + */ +static NSString *const FIRAuthErrorCodeString(FIRAuthErrorCode code) { + switch (code) { + case FIRAuthErrorCodeInvalidCustomToken: + return @"ERROR_INVALID_CUSTOM_TOKEN"; + case FIRAuthErrorCodeCustomTokenMismatch: + return @"ERROR_CUSTOM_TOKEN_MISMATCH"; + case FIRAuthErrorCodeInvalidEmail: + return @"ERROR_INVALID_EMAIL"; + case FIRAuthErrorCodeInvalidCredential: + return @"ERROR_INVALID_CREDENTIAL"; + case FIRAuthErrorCodeUserDisabled: + return @"ERROR_USER_DISABLED"; + case FIRAuthErrorCodeEmailAlreadyInUse: + return @"ERROR_EMAIL_ALREADY_IN_USE"; + case FIRAuthErrorCodeWrongPassword: + return @"ERROR_WRONG_PASSWORD"; + case FIRAuthErrorCodeTooManyRequests: + return @"ERROR_TOO_MANY_REQUESTS"; + case FIRAuthErrorCodeAccountExistsWithDifferentCredential: + return @"ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"; + case FIRAuthErrorCodeRequiresRecentLogin: + return @"ERROR_REQUIRES_RECENT_LOGIN"; + case FIRAuthErrorCodeProviderAlreadyLinked: + return @"ERROR_PROVIDER_ALREADY_LINKED"; + case FIRAuthErrorCodeNoSuchProvider: + return @"ERROR_NO_SUCH_PROVIDER"; + case FIRAuthErrorCodeInvalidUserToken: + return @"ERROR_INVALID_USER_TOKEN"; + case FIRAuthErrorCodeNetworkError: + return @"ERROR_NETWORK_REQUEST_FAILED"; + case FIRAuthErrorCodeKeychainError: + return @"ERROR_KEYCHAIN_ERROR"; + case FIRAuthErrorCodeUserTokenExpired: + return @"ERROR_USER_TOKEN_EXPIRED"; + case FIRAuthErrorCodeUserNotFound: + return @"ERROR_USER_NOT_FOUND"; + case FIRAuthErrorCodeInvalidAPIKey: + return @"ERROR_INVALID_API_KEY"; + case FIRAuthErrorCodeCredentialAlreadyInUse: + return @"ERROR_CREDENTIAL_ALREADY_IN_USE"; + case FIRAuthErrorCodeInternalError: + return @"ERROR_INTERNAL_ERROR"; + case FIRAuthErrorCodeUserMismatch: + return @"ERROR_USER_MISMATCH"; + case FIRAuthErrorCodeOperationNotAllowed: + return @"ERROR_OPERATION_NOT_ALLOWED"; + case FIRAuthErrorCodeWeakPassword: + return @"ERROR_WEAK_PASSWORD"; + case FIRAuthErrorCodeAppNotAuthorized: + return @"ERROR_APP_NOT_AUTHORIZED"; + case FIRAuthErrorCodeExpiredActionCode: + return @"ERROR_EXPIRED_ACTION_CODE"; + case FIRAuthErrorCodeInvalidActionCode: + return @"ERROR_INVALID_ACTION_CODE"; + case FIRAuthErrorCodeInvalidMessagePayload: + return @"ERROR_INVALID_MESSAGE_PAYLOAD"; + case FIRAuthErrorCodeInvalidSender: + return @"ERROR_INVALID_SENDER"; + case FIRAuthErrorCodeInvalidRecipientEmail: + return @"ERROR_INVALID_RECIPIENT_EMAIL"; + case FIRAuthErrorCodeMissingIosBundleID: + return @"ERROR_MISSING_IOS_BUNDLE_ID"; + case FIRAuthErrorCodeMissingAndroidPackageName: + return @"ERROR_MISSING_ANDROID_PKG_NAME"; + case FIRAuthErrorCodeUnauthorizedDomain: + return @"ERROR_UNAUTHORIZED_DOMAIN"; + case FIRAuthErrorCodeInvalidContinueURI: + return @"ERROR_INVALID_CONTINUE_URI"; + case FIRAuthErrorCodeMissingContinueURI: + return @"ERROR_MISSING_CONTINUE_URI"; + case FIRAuthErrorCodeMissingEmail: + return @"ERROR_MISSING_EMAIL"; + case FIRAuthErrorCodeMissingPhoneNumber: + return @"ERROR_MISSING_PHONE_NUMBER"; + case FIRAuthErrorCodeInvalidPhoneNumber: + return @"ERROR_INVALID_PHONE_NUMBER"; + case FIRAuthErrorCodeMissingVerificationCode: + return @"ERROR_MISSING_VERIFICATION_CODE"; + case FIRAuthErrorCodeInvalidVerificationCode: + return @"ERROR_INVALID_VERIFICATION_CODE"; + case FIRAuthErrorCodeMissingVerificationID: + return @"ERROR_MISSING_VERIFICATION_ID"; + case FIRAuthErrorCodeInvalidVerificationID: + return @"ERROR_INVALID_VERIFICATION_ID"; + case FIRAuthErrorCodeSessionExpired: + return @"ERROR_SESSION_EXPIRED"; + case FIRAuthErrorCodeMissingAppCredential: + return @"MISSING_APP_CREDENTIAL"; + case FIRAuthErrorCodeInvalidAppCredential: + return @"INVALID_APP_CREDENTIAL"; + case FIRAuthErrorCodeQuotaExceeded: + return @"ERROR_QUOTA_EXCEEDED"; + case FIRAuthErrorCodeMissingAppToken: + return @"ERROR_MISSING_APP_TOKEN"; + case FIRAuthErrorCodeNotificationNotForwarded: + return @"ERROR_NOTIFICATION_NOT_FORWARDED"; + case FIRAuthErrorCodeAppNotVerified: + return @"ERROR_APP_NOT_VERIFIED"; + case FIRAuthErrorCodeCaptchaCheckFailed: + return @"ERROR_CAPTCHA_CHECK_FAILED"; + case FIRAuthErrorCodeWebContextAlreadyPresented: + return @"ERROR_WEB_CONTEXT_ALREADY_PRESENTED"; + case FIRAuthErrorCodeWebContextCancelled: + return @"ERROR_WEB_CONTEXT_CANCELLED"; + case FIRAuthErrorCodeInvalidClientID: + return @"ERROR_INVALID_CLIENT_ID"; + case FIRAuthErrorCodeAppVerificationUserInteractionFailure: + return @"ERROR_APP_VERIFICATION_FAILED"; + case FIRAuthErrorCodeWebNetworkRequestFailed: + return @"ERROR_WEB_NETWORK_REQUEST_FAILED"; + case FIRAuthErrorCodeNullUser: + return @"ERROR_NULL_USER"; + case FIRAuthErrorCodeInvalidDynamicLinkDomain: + return @"ERROR_INVALID_DYNAMIC_LINK_DOMAIN"; + case FIRAuthErrorCodeWebInternalError: + return @"ERROR_WEB_INTERNAL_ERROR"; + case FIRAuthErrorCodeMalformedJWT: + return @"ERROR_MALFORMED_JWT"; + case FIRAuthErrorCodeLocalPlayerNotAuthenticated: + return @"ERROR_LOCAL_PLAYER_NOT_AUTHENTICATED"; + } +} + +@implementation FIRAuthErrorUtils + ++ (NSError *)errorWithCode:(FIRAuthInternalErrorCode)code { + return [self errorWithCode:code message:nil]; +} + ++ (NSError *)errorWithCode:(FIRAuthInternalErrorCode)code + message:(nullable NSString *)message { + NSDictionary *userInfo = nil; + if (message.length) { + userInfo = @{ + NSLocalizedDescriptionKey : message + }; + } + return [self errorWithCode:code userInfo:userInfo]; +} + ++ (NSError *)errorWithCode:(FIRAuthInternalErrorCode)code + underlyingError:(nullable NSError *)underlyingError { + NSDictionary *errorUserInfo = nil; + if (underlyingError) { + errorUserInfo = @{ + NSUnderlyingErrorKey : underlyingError + }; + } + return [self errorWithCode:code userInfo:errorUserInfo]; +} + ++ (NSError *)errorWithCode:(FIRAuthInternalErrorCode)code + userInfo:(nullable NSDictionary *)userInfo { + BOOL isPublic = (code & FIRAuthPublicErrorCodeFlag) == FIRAuthPublicErrorCodeFlag; + if (isPublic) { + // This is a public error. Return it as a public error and add a description. + NSInteger errorCode = code & ~FIRAuthPublicErrorCodeFlag; + NSMutableDictionary *errorUserInfo = [NSMutableDictionary dictionaryWithDictionary:userInfo]; + if (!errorUserInfo[NSLocalizedDescriptionKey]) { + errorUserInfo[NSLocalizedDescriptionKey] = FIRAuthErrorDescription(errorCode); + } + errorUserInfo[FIRAuthErrorNameKey] = FIRAuthErrorCodeString(errorCode); + return [NSError errorWithDomain:FIRAuthErrorDomain code:errorCode userInfo:errorUserInfo]; + } else { + // This is an internal error. Wrap it in an internal error. + NSError *error = + [NSError errorWithDomain:FIRAuthInternalErrorDomain code:code userInfo:userInfo]; + return [self errorWithCode:FIRAuthInternalErrorCodeInternalError underlyingError:error]; + } +} + ++ (NSError *)RPCRequestEncodingErrorWithUnderlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeRPCRequestEncodingError + underlyingError:underlyingError]; +} + ++ (NSError *)JSONSerializationErrorForUnencodableType { + return [self errorWithCode:FIRAuthInternalErrorCodeJSONSerializationError]; +} + ++ (NSError *)JSONSerializationErrorWithUnderlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeJSONSerializationError + underlyingError:underlyingError]; +} + ++ (NSError *)networkErrorWithUnderlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeNetworkError + underlyingError:underlyingError]; +} + ++ (NSError *)unexpectedErrorResponseWithData:(NSData *)data + underlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeUnexpectedErrorResponse userInfo:@{ + FIRAuthErrorUserInfoDataKey : data, + NSUnderlyingErrorKey : underlyingError + }]; +} + ++ (NSError *)unexpectedErrorResponseWithDeserializedResponse:(id)deserializedResponse { + return [self errorWithCode:FIRAuthInternalErrorCodeUnexpectedErrorResponse userInfo:@{ + FIRAuthErrorUserInfoDeserializedResponseKey : deserializedResponse + }]; +} + ++ (NSError *)malformedJWTErrorWithToken:(NSString *)token + underlyingError:(NSError *_Nullable)underlyingError { + NSMutableDictionary *userInfo = + [NSMutableDictionary dictionaryWithObject:kFIRAuthErrorMessageMalformedJWT + forKey:NSLocalizedDescriptionKey]; + [userInfo setObject:token forKey:FIRAuthErrorUserInfoDataKey]; + if (underlyingError != nil) { + [userInfo setObject:underlyingError forKey:NSUnderlyingErrorKey]; + } + return [self errorWithCode:FIRAuthInternalErrorCodeMalformedJWT userInfo:[userInfo copy]]; +} + ++ (NSError *)unexpectedResponseWithData:(NSData *)data + underlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeUnexpectedResponse userInfo:@{ + FIRAuthErrorUserInfoDataKey : data, + NSUnderlyingErrorKey : underlyingError + }]; +} + ++ (NSError *)unexpectedResponseWithDeserializedResponse:(id)deserializedResponse { + return [self errorWithCode:FIRAuthInternalErrorCodeUnexpectedResponse userInfo:@{ + FIRAuthErrorUserInfoDeserializedResponseKey : deserializedResponse + }]; +} + ++ (NSError *)unexpectedResponseWithDeserializedResponse:(nullable id)deserializedResponse + underlyingError:(NSError *)underlyingError { + NSMutableDictionary *userInfo = + [NSMutableDictionary dictionaryWithDictionary:@{ NSUnderlyingErrorKey : underlyingError }]; + if (deserializedResponse) { + userInfo[FIRAuthErrorUserInfoDeserializedResponseKey] = deserializedResponse; + } + return [self errorWithCode:FIRAuthInternalErrorCodeUnexpectedResponse userInfo:userInfo]; +} + ++ (NSError *)RPCResponseDecodingErrorWithDeserializedResponse:(id)deserializedResponse + underlyingError:(NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeRPCResponseDecodingError userInfo:@{ + FIRAuthErrorUserInfoDeserializedResponseKey : deserializedResponse, + NSUnderlyingErrorKey : underlyingError + }]; +} + ++ (NSError *)emailAlreadyInUseErrorWithEmail:(nullable NSString *)email { + NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init]; + if (email.length) { + userInfo[FIRAuthErrorUserInfoEmailKey] = email; + } + return [self errorWithCode:FIRAuthInternalErrorCodeEmailAlreadyInUse userInfo:userInfo]; +} + ++ (NSError *)userDisabledErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeUserDisabled message:message]; +} + ++ (NSError *)wrongPasswordErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeWrongPassword message:message]; +} + ++ (NSError *)tooManyRequestsErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeTooManyRequests message:message]; +} + ++ (NSError *)invalidCustomTokenErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidCustomToken message:message]; +} + ++ (NSError *)customTokenMistmatchErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeCustomTokenMismatch message:message]; +} + ++ (NSError *)invalidCredentialErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidCredential message:message]; +} + ++ (NSError *)requiresRecentLoginErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeRequiresRecentLogin message:message]; +} + ++ (NSError *)invalidUserTokenErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidUserToken message:message]; +} + ++ (NSError *)invalidEmailErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidEmail message:message]; +} + ++ (NSError *)accountExistsWithDifferentCredentialErrorWithEmail:(nullable NSString *)email { + return [self errorWithCode:FIRAuthInternalErrorCodeAccountExistsWithDifferentCredential + userInfo:@{ FIRAuthErrorUserInfoEmailKey : email }]; +} + ++ (NSError *)providerAlreadyLinkedError { + return [self errorWithCode:FIRAuthInternalErrorCodeProviderAlreadyLinked]; +} + ++ (NSError *)noSuchProviderError { + return [self errorWithCode:FIRAuthInternalErrorCodeNoSuchProvider]; +} + ++ (NSError *)userTokenExpiredErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeUserTokenExpired message:message]; +} + ++ (NSError *)userNotFoundErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeUserNotFound message:message]; +} + ++ (NSError *)invalidAPIKeyError { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidAPIKey]; +} + ++ (NSError *)userMismatchError { + return [self errorWithCode:FIRAuthInternalErrorCodeUserMismatch]; +} + ++ (NSError *)credentialAlreadyInUseErrorWithMessage:(nullable NSString *)message + credential:(nullable FIRPhoneAuthCredential *)credential { + if (credential) { + return [self errorWithCode:FIRAuthInternalErrorCodeCredentialAlreadyInUse + userInfo:@{ FIRAuthUpdatedCredentialKey : credential }]; + } + return [self errorWithCode:FIRAuthInternalErrorCodeCredentialAlreadyInUse message:message]; +} + ++ (NSError *)operationNotAllowedErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeOperationNotAllowed message:message]; +} + ++ (NSError *)weakPasswordErrorWithServerResponseReason:(nullable NSString *)reason { + return [self errorWithCode:FIRAuthInternalErrorCodeWeakPassword userInfo:@{ + NSLocalizedFailureReasonErrorKey : reason + }]; +} + ++ (NSError *)appNotAuthorizedError { + return [self errorWithCode:FIRAuthInternalErrorCodeAppNotAuthorized]; +} + ++ (NSError *)expiredActionCodeErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeExpiredActionCode message:message]; +} + ++ (NSError *)invalidActionCodeErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidActionCode message:message]; +} + ++ (NSError *)invalidMessagePayloadErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidMessagePayload message:message]; +} + ++ (NSError *)invalidSenderErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidSender message:message]; +} + ++ (NSError *)invalidRecipientEmailErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidRecipientEmail message:message]; +} + ++ (NSError *)missingIosBundleIDErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthinternalErrorCodeMissingIosBundleID message:message]; +} + ++ (NSError *)missingAndroidPackageNameErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingAndroidPackageName message:message]; +} + ++ (NSError *)unauthorizedDomainErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeUnauthorizedDomain message:message]; +} + ++ (NSError *)invalidContinueURIErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidContinueURI message:message]; +} + ++ (NSError *)missingContinueURIErrorWithMessage:(nullable NSString *)message { + return[self errorWithCode:FIRAuthInternalErrorCodeMissingContinueURI message:message]; +} + ++ (NSError *)missingEmailErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingEmail message:message]; +} + ++ (NSError *)missingPhoneNumberErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingPhoneNumber message:message]; +} + ++ (NSError *)invalidPhoneNumberErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidPhoneNumber message:message]; +} + ++ (NSError *)missingVerificationCodeErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingVerificationCode message:message]; +} + ++ (NSError *)invalidVerificationCodeErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidVerificationCode message:message]; +} + ++ (NSError *)missingVerificationIDErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingVerificationID message:message]; +} + ++ (NSError *)invalidVerificationIDErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidVerificationID message:message]; +} + ++ (NSError *)sessionExpiredErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeSessionExpired message:message]; +} + ++ (NSError *)missingAppCredentialWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingAppCredential message:message]; +} + ++ (NSError *)invalidAppCredentialWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidAppCredential message:message]; +} + ++ (NSError *)quotaExceededErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeQuotaExceeded message:message]; +} + ++ (NSError *)missingAppTokenErrorWithUnderlyingError:(nullable NSError *)underlyingError { + return [self errorWithCode:FIRAuthInternalErrorCodeMissingAppToken + underlyingError:underlyingError]; +} + ++ (NSError *)localPlayerNotAuthenticatedError { + return [self errorWithCode:FIRAuthInternalErrorCodeLocalPlayerNotAuthenticated]; +} + ++ (NSError *)notificationNotForwardedError { + return [self errorWithCode:FIRAuthInternalErrorCodeNotificationNotForwarded]; +} + ++ (NSError *)appNotVerifiedErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeAppNotVerified message:message]; +} + ++ (NSError *)captchaCheckFailedErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeCaptchaCheckFailed message:message]; +} + ++ (NSError *)webContextAlreadyPresentedErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeWebContextAlreadyPresented message:message]; +} + ++ (NSError *)webContextCancelledErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeWebContextCancelled message:message]; +} + ++ (NSError *)appVerificationUserInteractionFailureWithReason:(NSString *)reason { + return [self errorWithCode:FIRAuthInternalErrorCodeAppVerificationUserInteractionFailure + userInfo:@{ + NSLocalizedFailureReasonErrorKey : reason + }]; +} + ++ (nullable NSError *)URLResponseErrorWithCode:(NSString *)code message:(nullable NSString *)message { + if ([code isEqualToString:kURLResponseErrorCodeInvalidClientID]) { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidClientID message:message]; + } + if ([code isEqualToString:kURLResponseErrorCodeNetworkRequestFailed]) { + return [self errorWithCode:FIRAuthInternalErrorCodeWebNetworkRequestFailed message:message]; + } + if ([code isEqualToString:kURLResponseErrorCodeInternalError]) { + return [self errorWithCode:FIRAuthInternalErrorCodeWebInternalError message:message]; + } + return nil; +} + ++ (NSError *)nullUserErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeNullUser message:message]; +} + ++ (NSError *)invalidDynamicLinkDomainErrorWithMessage:(nullable NSString *)message { + return [self errorWithCode:FIRAuthInternalErrorCodeInvalidDynamicLinkDomain message:message]; +} + ++ (NSError *)keychainErrorWithFunction:(NSString *)keychainFunction status:(OSStatus)status { + NSString *failureReason = [NSString stringWithFormat:@"%@ (%li)", keychainFunction, (long)status]; + return [self errorWithCode:FIRAuthInternalErrorCodeKeychainError userInfo:@{ + NSLocalizedFailureReasonErrorKey : failureReason, + }]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.h new file mode 100644 index 0000000..3ae9159 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthExceptionUtils + @brief Utility class used to raise standardized Auth related exceptions. +*/ +@interface FIRAuthExceptionUtils : NSObject + +/** @fn raiseInvalidParameterExceptionWithReason: + @brief raises the "invalid parameter" exception + @param reason string will contain a description of the error. + */ ++ (void)raiseInvalidParameterExceptionWithReason:(nullable NSString *)reason; + +/** @fn raiseMethodNotImplementedExceptionWithReason: + @brief raises the "method not implemented" exception + @param reason string will contain a description of the error. + @see FIRMethodNotImplementedException + */ ++ (void)raiseMethodNotImplementedExceptionWithReason:(nullable NSString *)reason; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.m new file mode 100644 index 0000000..0adcd34 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthExceptionUtils.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthExceptionUtils.h" + +/** @var FIRMethodNotImplementedException + @brief The name of the "Method Not Implemented" exception. + */ +static NSString *const FIRMethodNotImplementedException = @"FIRMethodNotImplementedException"; + +@implementation FIRAuthExceptionUtils + ++ (void)raiseInvalidParameterExceptionWithReason:(NSString *)reason { + [NSException raise:NSInvalidArgumentException format:@"%@", reason]; +} + ++ (void)raiseMethodNotImplementedExceptionWithReason:(nullable NSString *)reason { + NSException *exception = + [NSException exceptionWithName:FIRMethodNotImplementedException reason:reason userInfo:nil]; + [exception raise]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.h new file mode 100644 index 0000000..55bb1a7 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.h @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @fn FIRAuthGlobalWorkQueue + @brief Retrieves the global serial work queue for Firebase Auth. + @return The global serial dispatch queue. + @remarks To ensure thread safety, all auth code must be executed in either this global work + queue, or a serial queue that has its target queue set to this work queue. All public method + implementations that may involve contested code shall dispatch to this work queue as the + first thing they do. + */ +extern dispatch_queue_t FIRAuthGlobalWorkQueue(void); + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.m new file mode 100644 index 0000000..accac89 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthGlobalWorkQueue.m @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthGlobalWorkQueue.h" + +dispatch_queue_t FIRAuthGlobalWorkQueue() { + static dispatch_once_t once; + static dispatch_queue_t queue; + dispatch_once(&once, ^{ + queue = dispatch_queue_create("com.google.firebase.auth.globalWorkQueue", NULL); + }); + return queue; +} diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthInternalErrors.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthInternalErrors.h new file mode 100644 index 0000000..71a8fd0 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthInternalErrors.h @@ -0,0 +1,454 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthErrors.h" + +/** @var FIRAuthPublicErrorCodeFlag + @brief Bitmask value indicating the error represents a public error code when this bit is + zeroed. Error codes which don't contain this flag will be wrapped in an @c NSError whose + code is @c FIRAuthErrorCodeInternalError. + */ +static const NSInteger FIRAuthPublicErrorCodeFlag = 1 << 20; + +/** @var FIRAuthInternalErrorDomain + @brief The Firebase Auth error domain for internal errors. + */ +extern NSString *const FIRAuthInternalErrorDomain; + +/** @var FIRAuthErrorUserInfoDeserializedResponseKey + @brief Errors with the code @c FIRAuthErrorCodeUnexpectedResponseError, + @c FIRAuthErrorCodeUnexpectedErrorResponseError, and + @c FIRAuthInternalErrorCodeRPCResponseDecodingError may contain an @c NSError.userInfo + dictionary which contains this key. The value associated with this key is an object of + unspecified contents containing the deserialized server response. + */ +extern NSString *const FIRAuthErrorUserInfoDeserializedResponseKey; + +/** @var FIRAuthErrorUserInfoDataKey + @brief Errors with the code @c FIRAuthErrorCodeUnexpectedResponseError or + @c FIRAuthErrorCodeUnexpectedErrorResponseError may contain an @c NSError.userInfo + dictionary which contains this key. The value associated with this key is an @c NSString + which represents the response from a server to an RPC which could not be deserialized. + */ +extern NSString *const FIRAuthErrorUserInfoDataKey; + + +/** @var FIRAuthInternalErrorCode + @brief Error codes used internally by Firebase Auth. + @remarks All errors are generated using an internal error code. These errors are automatically + converted to the appropriate public version of the @c NSError by the methods in + @c FIRAuthErrorUtils + */ +typedef NS_ENUM(NSInteger, FIRAuthInternalErrorCode) { + /** @var FIRAuthInternalErrorCodeNetworkError + @brief Indicates a network error occurred (such as a timeout, interrupted connection, or + unreachable host.) + @remarks These types of errors are often recoverable with a retry. + + See the @c NSUnderlyingError value in the @c NSError.userInfo dictionary for details about + the network error which occurred. + */ + FIRAuthInternalErrorCodeNetworkError = FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeNetworkError, + + /** @var FIRAuthInternalErrorCodeEmailAlreadyInUse + @brief The email used to attempt a sign-up already exists. + */ + FIRAuthInternalErrorCodeEmailAlreadyInUse = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeEmailAlreadyInUse, + + /** @var FIRAuthInternalErrorCodeUserDisabled + @brief Indicates the user's account is disabled on the server side. + */ + FIRAuthInternalErrorCodeUserDisabled = FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeUserDisabled, + + /** @var FIRAuthInternalErrorCodeWrongPassword + @brief Indicates the user attempted sign in with a wrong password + */ + FIRAuthInternalErrorCodeWrongPassword = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWrongPassword, + + /** @var FIRAuthInternalErrorCodeKeychainError + @brief Indicates an error occurred accessing the keychain. + @remarks The @c NSLocalizedFailureReasonErrorKey field in the @c NSError.userInfo dictionary + will contain more information about the error encountered. + */ + FIRAuthInternalErrorCodeKeychainError = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeKeychainError, + + /** @var FIRAuthInternalErrorCodeInternalError + @brief An internal error occurred. + @remarks This value is here for consistency. It's also used to make the implementation of + wrapping internal errors simpler. + */ + FIRAuthInternalErrorCodeInternalError = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInternalError, + + /** @var FIRAuthInternalErrorCodeTooManyRequests + @brief Indicates that too many requests were made to a server method. + */ + FIRAuthInternalErrorCodeTooManyRequests = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeTooManyRequests, + + /** @var FIRAuthInternalErrorCodeInvalidCustomToken + @brief Indicates a validation error with the custom token. + */ + FIRAuthInternalErrorCodeInvalidCustomToken = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidCustomToken, + + /** @var FIRAuthInternalErrorCodeCredentialMismatch + @brief Indicates the service account and the API key belong to different projects. + */ + FIRAuthInternalErrorCodeCustomTokenMismatch = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeCustomTokenMismatch, + + /** @var FIRAuthInternalErrorCodeInvalidCredential + @brief Indicates the IDP token or requestUri is invalid. + */ + FIRAuthInternalErrorCodeInvalidCredential = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidCredential, + + /** @var FIRAuthInternalErrorCodeRequiresRecentLogin + @brief Indicates the user has attemped to change email or password more than 5 minutes after + signing in. + */ + FIRAuthInternalErrorCodeRequiresRecentLogin = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeRequiresRecentLogin, + + /** @var FIRAuthInternalErrorCodeInvalidUserToken + @brief Indicates user's saved auth credential is invalid, the user needs to sign in again. + */ + FIRAuthInternalErrorCodeInvalidUserToken = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidUserToken, + + /** @var FIRAuthInternalErrorCodeInvalidEmail + @brief Indicates the email identifier is invalid. + */ + FIRAuthInternalErrorCodeInvalidEmail = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidEmail, + + /** @var FIRAuthInternalErrorCodeAccountExistsWithDifferentCredential + @brief Indicates account linking is needed. + */ + FIRAuthInternalErrorCodeAccountExistsWithDifferentCredential = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeAccountExistsWithDifferentCredential, + + /** @var FIRAuthInternalErrorCodeProviderAlreadyLinked + @brief Indicates an attempt to link a provider to which we are already linked. + */ + FIRAuthInternalErrorCodeProviderAlreadyLinked = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeProviderAlreadyLinked, + + /** @var FIRAuthInternalErrorCodeNoSuchProvider + @brief Indicates an attempt to unlink a provider that is not is not linked. + */ + FIRAuthInternalErrorCodeNoSuchProvider = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeNoSuchProvider, + + /** @var FIRAuthInternalErrorCodeUserTokenExpired + @brief Indicates the token issue time is older than account's valid_since time. + */ + FIRAuthInternalErrorCodeUserTokenExpired = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeUserTokenExpired, + + /** @var FIRAuthInternalErrorCodeUserNotFound + @brief Indicates the user account was been found. + */ + FIRAuthInternalErrorCodeUserNotFound = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeUserNotFound, + + /** @var FIRAuthInternalErrorCodeInvalidAPIKey + @brief Indicates an invalid API Key was supplied in the request. + */ + FIRAuthInternalErrorCodeInvalidAPIKey = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidAPIKey, + + /** @var FIRAuthInternalErrorCodeOperationNotAllowed + @brief Indicates that admin disabled sign-in with the specified IDP. + */ + FIRAuthInternalErrorCodeOperationNotAllowed = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeOperationNotAllowed, + + /** @var FIRAuthInternalErrorCodeUserMismatch + @brief Indicates that user attempted to reauthenticate with a user other than the current + user. + */ + FIRAuthInternalErrorCodeUserMismatch = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeUserMismatch, + + /** @var FIRAuthInternalErrorCodeCredentialAlreadyInUse + @brief Indicates an attempt to link with a credential that has already been linked with a + different Firebase account. + */ + FIRAuthInternalErrorCodeCredentialAlreadyInUse = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeCredentialAlreadyInUse, + + /** @var FIRAuthInternalErrorCodeWeakPassword + @brief Indicates an attempt to set a password that is considered too weak. + */ + FIRAuthInternalErrorCodeWeakPassword = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWeakPassword, + + /** @var FIRAuthInternalErrorCodeAppNotAuthorized + @brief Indicates the App is not authorized to use Firebase Authentication with the + provided API Key. + */ + FIRAuthInternalErrorCodeAppNotAuthorized = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeAppNotAuthorized, + + /** @var FIRAuthInternalErrorCodeExpiredActionCode + @brief Indicates the OOB code is expired. + */ + FIRAuthInternalErrorCodeExpiredActionCode = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeExpiredActionCode, + + /** @var FIRAuthInternalErrorCodeInvalidActionCode + @brief Indicates the OOB code is invalid. + */ + FIRAuthInternalErrorCodeInvalidActionCode = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidActionCode, + + /** Indicates that there are invalid parameters in the payload during a "send password reset email + * " attempt. + */ + FIRAuthInternalErrorCodeInvalidMessagePayload = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidMessagePayload, + + /** Indicates that the sender email is invalid during a "send password reset email" attempt. + */ + FIRAuthInternalErrorCodeInvalidSender = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidSender, + + /** Indicates that the recipient email is invalid. + */ + FIRAuthInternalErrorCodeInvalidRecipientEmail = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidRecipientEmail, + + /** Indicates that the iOS bundle ID is missing when a iOS App Store ID is provided. + */ + FIRAuthinternalErrorCodeMissingIosBundleID = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingIosBundleID, + + /** Indicates that the android package name is missing when the @c androidInstallApp flag is set + to true. + */ + FIRAuthInternalErrorCodeMissingAndroidPackageName = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingAndroidPackageName, + + /** Indicates that the domain specified in the continue URL is not whitelisted in the Firebase + console. + */ + FIRAuthInternalErrorCodeUnauthorizedDomain = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeUnauthorizedDomain, + + /** Indicates that the domain specified in the continue URI is not valid. + */ + FIRAuthInternalErrorCodeInvalidContinueURI = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidContinueURI, + + /** Indicates that a continue URI was not provided in a request to the backend which requires + one. + */ + FIRAuthInternalErrorCodeMissingContinueURI = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingContinueURI, + + /** Indicates that an email address was expected but one was not provided. + */ + FIRAuthInternalErrorCodeMissingEmail = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingEmail, + + /** Indicates that a phone number was not provided in a call to @c verifyPhoneNumber:completion:. + */ + FIRAuthInternalErrorCodeMissingPhoneNumber = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingPhoneNumber, + + /** Indicates that an invalid phone number was provided in a call to @c + verifyPhoneNumber:completion:. + */ + FIRAuthInternalErrorCodeInvalidPhoneNumber = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidPhoneNumber, + + /** Indicates that the phone auth credential was created with an empty verification code. + */ + FIRAuthInternalErrorCodeMissingVerificationCode = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingVerificationCode, + + /** Indicates that an invalid verification code was used in the verifyPhoneNumber request. + */ + FIRAuthInternalErrorCodeInvalidVerificationCode = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidVerificationCode, + + /** Indicates that the phone auth credential was created with an empty verification ID. + */ + FIRAuthInternalErrorCodeMissingVerificationID = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingVerificationID, + + /** Indicates that the APNS device token is missing in the verifyClient request. + */ + FIRAuthInternalErrorCodeMissingAppCredential = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingAppCredential, + + /** Indicates that an invalid APNS device token was used in the verifyClient request. + */ + FIRAuthInternalErrorCodeInvalidAppCredential = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidAppCredential, + + /** Indicates that the reCAPTCHA token is not valid. + */ + FIRAuthInternalErrorCodeCaptchaCheckFailed = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeCaptchaCheckFailed, + + /** Indicates that an invalid verification ID was used in the verifyPhoneNumber request. + */ + FIRAuthInternalErrorCodeInvalidVerificationID = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidVerificationID, + + /** Indicates that the quota of SMS messages for a given project has been exceeded. + */ + FIRAuthInternalErrorCodeQuotaExceeded = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeQuotaExceeded, + + /** Indicates that an attempt was made to present a new web context while one was already being + presented. + */ + FIRAuthInternalErrorCodeWebContextAlreadyPresented = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWebContextAlreadyPresented, + + /** Indicates that the URL presentation was cancelled prematurely by the user. + */ + FIRAuthInternalErrorCodeWebContextCancelled = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWebContextCancelled, + + /** Indicates a general failure during the app verification flow. + */ + FIRAuthInternalErrorCodeAppVerificationUserInteractionFailure = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeAppVerificationUserInteractionFailure, + + /** Indicates that the clientID used to invoke a web flow is invalid. + */ + FIRAuthInternalErrorCodeInvalidClientID = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidClientID, + + /** Indicates that a network request within a SFSafariViewController or UIWebview failed. + */ + FIRAuthInternalErrorCodeWebNetworkRequestFailed = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWebNetworkRequestFailed, + + /** Indicates that an internal error occurred within a SFSafariViewController or UIWebview. + */ + FIRAuthInternalErrorCodeWebInternalError = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeWebInternalError, + + // The enum values between 17046 and 17051 are reserved and should NOT be used for new error + // codes. + + /** Indicates that the SMS code has expired + */ + FIRAuthInternalErrorCodeSessionExpired = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeSessionExpired, + + FIRAuthInternalErrorCodeMissingAppToken = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMissingAppToken, + + FIRAuthInternalErrorCodeNotificationNotForwarded = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeNotificationNotForwarded, + + FIRAuthInternalErrorCodeAppNotVerified = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeAppNotVerified, + + /** Indicates that the Game Center local player was not authenticated. + */ + FIRAuthInternalErrorCodeLocalPlayerNotAuthenticated = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeLocalPlayerNotAuthenticated, + + /** Indicates that a non-null user was expected as an argmument to the operation but a null + user was provided. + */ + FIRAuthInternalErrorCodeNullUser = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeNullUser, + + /** Indicates that the Firebase Dynamic Link domain used is either not configured or is unauthorized + for the current project. + */ + FIRAuthInternalErrorCodeInvalidDynamicLinkDomain = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeInvalidDynamicLinkDomain, + + FIRAuthInternalErrorCodeMalformedJWT = + FIRAuthPublicErrorCodeFlag | FIRAuthErrorCodeMalformedJWT, + + /** @var FIRAuthInternalErrorCodeRPCRequestEncodingError + @brief Indicates an error encoding the RPC request. + @remarks This is typically due to some sort of unexpected input value. + + See the @c NSUnderlyingError value in the @c NSError.userInfo dictionary for details. + */ + FIRAuthInternalErrorCodeRPCRequestEncodingError = 1, + + /** @var FIRAuthInternalErrorCodeJSONSerializationError + @brief Indicates an error serializing an RPC request. + @remarks This is typically due to some sort of unexpected input value. + + If an @c NSJSONSerialization.isValidJSONObject: check fails, the error will contain no + @c NSUnderlyingError key in the @c NSError.userInfo dictionary. If an error was + encountered calling @c NSJSONSerialization.dataWithJSONObject:options:error:, the + resulting error will be associated with the @c NSUnderlyingError key in the + @c NSError.userInfo dictionary. + */ + FIRAuthInternalErrorCodeJSONSerializationError = 2, + + /** @var FIRAuthInternalErrorCodeUnexpectedErrorResponse + @brief Indicates an HTTP error occurred and the data returned either couldn't be deserialized + or couldn't be decoded. + @remarks See the @c NSUnderlyingError value in the @c NSError.userInfo dictionary for details + about the HTTP error which occurred. + + If the response could be deserialized as JSON then the @c NSError.userInfo dictionary will + contain a value for the key @c FIRAuthErrorUserInfoDeserializedResponseKey which is the + deserialized response value. + + If the response could not be deserialized as JSON then the @c NSError.userInfo dictionary + will contain values for the @c NSUnderlyingErrorKey and @c FIRAuthErrorUserInfoDataKey + keys. + */ + FIRAuthInternalErrorCodeUnexpectedErrorResponse = 3, + + /** @var FIRAuthInternalErrorCodeUnexpectedResponse + @brief Indicates the HTTP response indicated the request was a successes, but the response + contains something other than a JSON-encoded dictionary, or the data type of the response + indicated it is different from the type of response we expected. + @remarks See the @c NSUnderlyingError value in the @c NSError.userInfo dictionary. + If this key is present in the dictionary, it may contain an error from + @c NSJSONSerialization error (indicating the response received was of the wrong data + type). + + See the @c FIRAuthErrorUserInfoDeserializedResponseKey value in the @c NSError.userInfo + dictionary. If the response could be deserialized, it's deserialized representation will + be associated with this key. If the @c NSUnderlyingError value in the @c NSError.userInfo + dictionary is @c nil, this indicates the JSON didn't represent a dictionary. + */ + FIRAuthInternalErrorCodeUnexpectedResponse = 4, + + /** @var FIRAuthInternalErrorCodeRPCResponseDecodingError + @brief Indicates an error decoding the RPC response. + This is typically due to some sort of unexpected response value from the server. + @remarks See the @c NSUnderlyingError value in the @c NSError.userInfo dictionary for details. + + See the @c FIRErrorUserInfoDecodedResponseKey value in the @c NSError.userInfo dictionary. + The deserialized representation of the response will be associated with this key. + */ + FIRAuthInternalErrorCodeRPCResponseDecodingError = 5, +}; diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.h new file mode 100644 index 0000000..c52e26a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.h @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief The protocol for permanant data storage. + */ +@protocol FIRAuthStorage + +/** @fn initWithService: + @brief Initialize a @c FIRAuthStorage instance. + @param service The name of the storage service to use. + @return An initialized @c FIRAuthStorage instance for the specified service. + */ +- (id)initWithService:(NSString *)service; + +/** @fn dataForKey:error: + @brief Gets the data for @c key in the storage. The key is set for the attribute + @c kSecAttrAccount of a generic password query. + @param key The key to use. + @param error The address to store any error that occurs during the process, if not NULL. + If the operation was successful, its content is set to @c nil . + @return The data stored in the storage for @c key, if any. + */ +- (nullable NSData *)dataForKey:(NSString *)key error:(NSError **_Nullable)error; + +/** @fn setData:forKey:error: + @brief Sets the data for @c key in the storage. The key is set for the attribute + @c kSecAttrAccount of a generic password query. + @param data The data to store. + @param key The key to use. + @param error The address to store any error that occurs during the process, if not NULL. + @return Whether the operation succeeded or not. + */ +- (BOOL)setData:(NSData *)data forKey:(NSString *)key error:(NSError **_Nullable)error; + +/** @fn removeDataForKey:error: + @brief Removes the data for @c key in the storage. The key is set for the attribute + @c kSecAttrAccount of a generic password query. + @param key The key to use. + @param error The address to store any error that occurs during the process, if not NULL. + @return Whether the operation succeeded or not. + */ +- (BOOL)removeDataForKey:(NSString *)key error:(NSError **_Nullable)error; + +@end + +/** @class FIRAuthKeychain + @brief The utility class to manipulate data in iOS Keychain. + */ +@interface FIRAuthKeychain : NSObject +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.m new file mode 100644 index 0000000..199dea2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthKeychain.m @@ -0,0 +1,256 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthKeychain.h" + +#import + +#import "FIRAuthErrorUtils.h" +#import "FIRAuthUserDefaultsStorage.h" + +#if FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE +#import + +/** @var kOSVersionMatcherForUsingUserDefaults + @brief The regular expression to match all OS versions that @c FIRAuthUserDefaultsStorage is + used instead if available. + */ +static NSString *const kOSVersionMatcherForUsingUserDefaults = @"^10\\.[01](\\..*)?$"; + +#endif // FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE + +/** @var kAccountPrefix + @brief The prefix string for keychain item account attribute before the key. + @remarks A number "1" is encoded in the prefix in case we need to upgrade the scheme in future. + */ +static NSString *const kAccountPrefix = @"firebase_auth_1_"; + +@implementation FIRAuthKeychain { + /** @var _service + @brief The name of the keychain service. + */ + NSString *_service; + + /** @var _legacyItemDeletedForKey + @brief Indicates whether or not this class knows that the legacy item for a particular key has + been deleted. + @remarks This dictionary is to avoid unecessary keychain operations against legacy items. + */ + NSMutableDictionary *_legacyEntryDeletedForKey; +} + +- (id)initWithService:(NSString *)service { + +#if FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE + + NSString *OSVersion = [UIDevice currentDevice].systemVersion; + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:kOSVersionMatcherForUsingUserDefaults + options:0 + error:NULL]; + if ([regex numberOfMatchesInString:OSVersion options:0 range:NSMakeRange(0, OSVersion.length)]) { + return (id)[[FIRAuthUserDefaultsStorage alloc] initWithService:service]; + } + +#endif // FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE + + self = [super init]; + if (self) { + _service = [service copy]; + _legacyEntryDeletedForKey = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (NSData *)dataForKey:(NSString *)key error:(NSError **_Nullable)error { + if (!key.length) { + [NSException raise:NSInvalidArgumentException + format:@"%@", @"The key cannot be nil or empty."]; + return nil; + } + NSData *data = [self itemWithQuery:[self genericPasswordQueryWithKey:key] error:error]; + if (error && *error) { + return nil; + } + if (data) { + return data; + } + // Check for legacy form. + if (_legacyEntryDeletedForKey[key]) { + return nil; + } + data = [self itemWithQuery:[self legacyGenericPasswordQueryWithKey:key] error:error]; + if (error && *error) { + return nil; + } + if (!data) { + // Mark legacy data as non-existing so we don't have to query it again. + _legacyEntryDeletedForKey[key] = @YES; + return nil; + } + // Move the data to current form. + if (![self setData:data forKey:key error:error]) { + return nil; + } + [self deleteLegacyItemWithKey:key]; + return data; +} + +- (BOOL)setData:(NSData *)data forKey:(NSString *)key error:(NSError **_Nullable)error { + if (!key.length) { + [NSException raise:NSInvalidArgumentException + format:@"%@", @"The key cannot be nil or empty."]; + return NO; + } + NSDictionary *attributes = @{ + (__bridge id)kSecValueData : data, + (__bridge id)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + }; + return [self setItemWithQuery:[self genericPasswordQueryWithKey:key] + attributes:attributes + error:error]; +} + +- (BOOL)removeDataForKey:(NSString *)key error:(NSError **_Nullable)error { + if (!key.length) { + [NSException raise:NSInvalidArgumentException + format:@"%@", @"The key cannot be nil or empty."]; + return NO; + } + if (![self deleteItemWithQuery:[self genericPasswordQueryWithKey:key] error:error]) { + return NO; + } + // Legacy form item, if exists, also needs to be removed, otherwise it will be exposed when + // current form item is removed, leading to incorrect semantics. + [self deleteLegacyItemWithKey:key]; + return YES; +} + +#pragma mark - Private + +- (NSData *)itemWithQuery:(NSDictionary *)query error:(NSError **_Nullable)error { + NSMutableDictionary *returningQuery = [query mutableCopy]; + returningQuery[(__bridge id)kSecReturnData] = @YES; + returningQuery[(__bridge id)kSecReturnAttributes] = @YES; + // Using a match limit of 2 means that we can check whether there is more than one item. + // If we used a match limit of 1 we would never find out. + returningQuery[(__bridge id)kSecMatchLimit] = @2; + + CFArrayRef result = NULL; + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)returningQuery, + (CFTypeRef *)&result); + + if (status == noErr && result != NULL) { + NSArray *items = (__bridge_transfer NSArray *)result; + if (items.count != 1) { + if (error) { + *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching" + status:status]; + } + return nil; + } + + if (error) { + *error = nil; + } + NSDictionary *item = items[0]; + return item[(__bridge id)kSecValueData]; + } + + if (status == errSecItemNotFound) { + if (error) { + *error = nil; + } + } else { + if (error) { + *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching" status:status]; + } + } + return nil; +} + +- (BOOL)setItemWithQuery:(NSDictionary *)query + attributes:(NSDictionary *)attributes + error:(NSError **_Nullable)error { + NSMutableDictionary *combined = [attributes mutableCopy]; + [combined addEntriesFromDictionary:query]; + BOOL hasItem = NO; + OSStatus status = SecItemAdd((__bridge CFDictionaryRef)combined, NULL); + + if (status == errSecDuplicateItem) { + hasItem = YES; + status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)attributes); + } + + if (status == noErr) { + return YES; + } + if (error) { + NSString *function = hasItem ? @"SecItemUpdate" : @"SecItemAdd"; + *error = [FIRAuthErrorUtils keychainErrorWithFunction:function status:status]; + } + return NO; +} + +- (BOOL)deleteItemWithQuery:(NSDictionary *)query error:(NSError **_Nullable)error { + OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query); + if (status == noErr || status == errSecItemNotFound) { + return YES; + } + if (error) { + *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemDelete" status:status]; + } + return NO; +} + +/** @fn deleteLegacyItemsWithKey: + @brief Deletes legacy item from the keychain if it is not already known to be deleted. + @param key The key for the item. + */ +- (void)deleteLegacyItemWithKey:(NSString *)key { + if (_legacyEntryDeletedForKey[key]) { + return; + } + NSDictionary *query = [self legacyGenericPasswordQueryWithKey:key]; + SecItemDelete((__bridge CFDictionaryRef)query); + _legacyEntryDeletedForKey[key] = @YES; +} + +/** @fn genericPasswordQueryWithKey: + @brief Returns a keychain query of generic password to be used to manipulate key'ed value. + @param key The key for the value being manipulated, used as the account field in the query. + */ +- (NSDictionary *)genericPasswordQueryWithKey:(NSString *)key { + return @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : [kAccountPrefix stringByAppendingString:key], + (__bridge id)kSecAttrService : _service, + }; +} + +/** @fn legacyGenericPasswordQueryWithKey: + @brief Returns a keychain query of generic password without service field, which is used by + previous version of this class. + @param key The key for the value being manipulated, used as the account field in the query. + */ +- (NSDictionary *)legacyGenericPasswordQueryWithKey:(NSString *)key { + return @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : key, + }; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.h new file mode 100644 index 0000000..42e5db8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.h @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +@class FIRAuthAppCredentialManager; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthNotificationForwardingCallback + @brief The type of block to receive whether or not remote notifications are being forwarded. + @param isNotificationBeingForwarded Whether or not remote notifications are being forwarded. + */ +typedef void (^FIRAuthNotificationForwardingCallback)(BOOL isNotificationBeingForwarded); + +/** @class FIRAuthNotificationManager + */ +@interface FIRAuthNotificationManager : NSObject + +/** @property timeout + @brief The timeout for checking for notification forwarding. + @remarks Only tests should access this property. + */ +@property(nonatomic, assign) NSTimeInterval timeout; + +/** @fn initWithApplication:appCredentialManager: + @brief Initializes the instance. + @param application The application. + @param appCredentialManager The object to handle app credentials delivered via notification. + @return The initialized instance. + */ +- (instancetype)initWithApplication:(UIApplication *)application + appCredentialManager:(FIRAuthAppCredentialManager *)appCredentialManager + NS_DESIGNATED_INITIALIZER; + +/** @fn init + @brief please use initWithAppCredentialManager: instead. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn checkNotificationForwardingWithCallback: + @brief Checks whether or not remote notifications are being forwarded to this class. + @param callback The block to be called either immediately or in future once a result + is available. + */ +- (void)checkNotificationForwardingWithCallback:(FIRAuthNotificationForwardingCallback)callback; + +/** @fn canHandleNotification: + @brief Attempts to handle the remote notification. + @param notification The notification in question. + @return Whether or the notification has been handled. + */ +- (BOOL)canHandleNotification:(NSDictionary *)notification; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.m new file mode 100644 index 0000000..682ffcb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthNotificationManager.m @@ -0,0 +1,177 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthNotificationManager.h" + +#import +#import "FIRAuthAppCredential.h" +#import "FIRAuthAppCredentialManager.h" +#import "FIRAuthGlobalWorkQueue.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kNotificationKey + @brief The key to locate payload data in the remote notification. + */ +static NSString *const kNotificationDataKey = @"com.google.firebase.auth"; + +/** @var kNotificationReceiptKey + @brief The key for the receipt in the remote notification payload data. + */ +static NSString *const kNotificationReceiptKey = @"receipt"; + +/** @var kNotificationSecretKey + @brief The key for the secret in the remote notification payload data. + */ +static NSString *const kNotificationSecretKey = @"secret"; + +/** @var kNotificationProberKey + @brief The key for marking the prober in the remote notification payload data. + */ +static NSString *const kNotificationProberKey = @"warning"; + +/** @var kProbingTimeout + @brief Timeout for probing whether the app delegate forwards the remote notification to us. + */ +static const NSTimeInterval kProbingTimeout = 1; + +@implementation FIRAuthNotificationManager { + /** @var _application + @brief The application. + */ + UIApplication *_application; + + /** @var _appCredentialManager + @brief The object to handle app credentials delivered via notification. + */ + FIRAuthAppCredentialManager *_appCredentialManager; + + /** @var _hasCheckedNotificationForwarding + @brief Whether notification forwarding has been checked or not. + */ + BOOL _hasCheckedNotificationForwarding; + + /** @var _isNotificationBeingForwarded + @brief Whether or not notification is being forwarded + */ + BOOL _isNotificationBeingForwarded; + + /** @var _pendingCallbacks + @brief All pending callbacks while a check is being performed. + */ + NSMutableArray *_pendingCallbacks; +} + +- (instancetype)initWithApplication:(UIApplication *)application + appCredentialManager:(FIRAuthAppCredentialManager *)appCredentialManager { + self = [super init]; + if (self) { + _application = application; + _appCredentialManager = appCredentialManager; + _timeout = kProbingTimeout; + } + return self; +} + +- (void)checkNotificationForwardingWithCallback:(FIRAuthNotificationForwardingCallback)callback { + if (_pendingCallbacks) { + [_pendingCallbacks addObject:callback]; + return; + } + if (_hasCheckedNotificationForwarding) { + callback(_isNotificationBeingForwarded); + return; + } + _hasCheckedNotificationForwarding = YES; + _pendingCallbacks = + [[NSMutableArray alloc] initWithObjects:callback, nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + NSDictionary *proberNotification = @{ + kNotificationDataKey : @{ + kNotificationProberKey : @"This fake notification should be forwarded to Firebase Auth." + } + }; + if ([self->_application.delegate respondsToSelector: + @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)]) { + [self->_application.delegate application:self->_application + didReceiveRemoteNotification:proberNotification + fetchCompletionHandler:^(UIBackgroundFetchResult result) {}]; +#if !TARGET_OS_TV + } else if ([self->_application.delegate respondsToSelector: + @selector(application:didReceiveRemoteNotification:)]) { + [self->_application.delegate application:self->_application + didReceiveRemoteNotification:proberNotification]; +#endif + } else { + FIRLogWarning(kFIRLoggerAuth, @"I-AUT000015", + @"The UIApplicationDelegate must handle remote notification for phone number " + @"authentication to work."); + } + }); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_timeout * NSEC_PER_SEC)), + FIRAuthGlobalWorkQueue(), ^{ + [self callBack]; + }); +} + +- (BOOL)canHandleNotification:(NSDictionary *)notification { + NSDictionary *data = notification[kNotificationDataKey]; + if ([data isKindOfClass:[NSString class]]) { + // Deserialize in case the data is a JSON string. + NSData *JSONData = [((NSString *)data) dataUsingEncoding:NSUTF8StringEncoding]; + data = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:NULL]; + } + if (![data isKindOfClass:[NSDictionary class]]) { + return NO; + } + if (data[kNotificationProberKey]) { + if (!_pendingCallbacks) { + // The prober notification probably comes from another instance, so pass it along. + return NO; + } + _isNotificationBeingForwarded = YES; + [self callBack]; + return YES; + } + NSString *receipt = data[kNotificationReceiptKey]; + if (![receipt isKindOfClass:[NSString class]]) { + return NO; + } + NSString *secret = data[kNotificationSecretKey]; + if (![receipt isKindOfClass:[NSString class]]) { + return NO; + } + return [_appCredentialManager canFinishVerificationWithReceipt:receipt secret:secret]; +} + +#pragma mark - Internal methods + +/** @fn callBack + @brief Calls back all pending callbacks with the result of notification forwarding check. + */ +- (void)callBack { + if (!_pendingCallbacks) { + return; + } + NSArray *allCallbacks = _pendingCallbacks; + _pendingCallbacks = nil; + for (FIRAuthNotificationForwardingCallback callback in allCallbacks) { + callback(_isNotificationBeingForwarded); + } +}; + +@end +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthOperationType.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthOperationType.h new file mode 100644 index 0000000..15d3dd7 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthOperationType.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief Indicates the type of operation performed for RPCs that support the operation + parameter. + */ +typedef NS_ENUM(NSInteger, FIRAuthOperationType) { + /** Indicates that the operation type is uspecified. + */ + FIRAuthOperationTypeUnspecified = 0, + + /** Indicates that the operation type is sign in or sign up. + */ + FIRAuthOperationTypeSignUpOrSignIn = 1, + + /** Indicates that the operation type is reauthentication. + */ + FIRAuthOperationTypeReauth = 2, + + /** Indicates that the operation type is update. + */ + FIRAuthOperationTypeUpdate = 3, + + /** Indicates that the operation type is link. + */ + FIRAuthOperationTypeLink = 4, +}; + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthProvider.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthProvider.m new file mode 100644 index 0000000..8a08d9b --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthProvider.m @@ -0,0 +1,69 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#pragma mark - Provider ID constants + +// Declared 'extern' in FIRGoogleAuthProvider.h +NSString *const FIRGoogleAuthProviderID = @"google.com"; + +// Declared 'extern' in FIRFacebookAuthProvider.h +NSString *const FIRFacebookAuthProviderID = @"facebook.com"; + +// Declared 'extern' in FIREmailAuthProvider.h +NSString *const FIREmailAuthProviderID = @"password"; + +// Declared 'extern' in FIREmailAuthProvider.h +NSString *const FIREmailPasswordAuthProviderID = @"password"; + +// Declared 'extern' in FIRTwitterAuthProvider.h +NSString *const FIRTwitterAuthProviderID = @"twitter.com"; + +// Declared 'extern' in FIRGitHubAuthProvider.h +NSString *const FIRGitHubAuthProviderID = @"github.com"; + +// Declared 'extern' in FIRPhoneAuthProvider.h +NSString *const FIRPhoneAuthProviderID = @"phone"; + +// Declared 'extern' in FIRGameCenterAuthProvider.h +NSString *const FIRGameCenterAuthProviderID = @"gc.apple.com"; + +#pragma mark - sign-in methods constants + +// Declared 'extern' in FIRGoogleAuthProvider.h +NSString *const FIRGoogleAuthSignInMethod = @"google.com"; + +// Declared 'extern' in FIREmailAuthProvider.h +NSString *const FIREmailPasswordAuthSignInMethod = @"password"; + +// Declared 'extern' in FIREmailAuthProvider.h +NSString *const FIREmailLinkAuthSignInMethod = @"emailLink"; + +// Declared 'extern' in FIRTwitterAuthProvider.h +NSString *const FIRTwitterAuthSignInMethod = @"twitter.com"; + +// Declared 'extern' in FIRFacebookAuthProvider.h +NSString *const FIRFacebookAuthSignInMethod = @"facebook.com"; + +// Declared 'extern' in FIRGitHubAuthProvider.h +NSString *const FIRGitHubAuthSignInMethod = @"github.com"; + +// Declared 'extern' in FIRPhoneAuthProvider.h +NSString *const FIRPhoneAuthSignInMethod = @"phone"; + +// Declared 'extern' in FIRGameCenterAuthProvider.h +NSString *const FIRGameCenterAuthSignInMethod = @"gc.apple.com"; diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.h new file mode 100644 index 0000000..cdae046 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthSerialTaskCompletionBlock + @brief The type of method a @c FIRAuthSerialTask must call when it is complete. + */ +typedef void (^FIRAuthSerialTaskCompletionBlock)(void); + +/** @typedef FIRAuthSerialTask + @brief Represents a unit of work submitted to a task queue. + @param complete The task MUST call the complete method when done. + */ +typedef void (^FIRAuthSerialTask)(FIRAuthSerialTaskCompletionBlock complete); + +/** @class FIRAuthSerialTaskQueue + @brief An easy to use serial task queue which supports a callback-based completion notification + system for easy asyncronous call chaining. + */ +@interface FIRAuthSerialTaskQueue : NSObject + +/** @fn enqueueTask: + @brief Enqueues a task for serial execution in the queue. + @remarks The task MUST call the complete method when done. This method is thread-safe. + The task block won't be executed concurrently with any other blocks in other task queues or + the global work queue as returned by @c FIRAuthGlobalWorkQueue , but an uncompleted task + (e.g. task block finished executation before complete method is called at a later time) + does not affect other task queues or the global work queue. + */ +- (void)enqueueTask:(FIRAuthSerialTask)task; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.m new file mode 100644 index 0000000..edceeec --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSerialTaskQueue.m @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthSerialTaskQueue.h" + +#import "FIRAuthGlobalWorkQueue.h" + +@implementation FIRAuthSerialTaskQueue { + /** @var _dispatchQueue + @brief The asyncronous dispatch queue into which tasks are enqueued and processed + serially. + */ + dispatch_queue_t _dispatchQueue; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _dispatchQueue = dispatch_queue_create("com.google.firebase.auth.serialTaskQueue", NULL); + dispatch_set_target_queue(_dispatchQueue, FIRAuthGlobalWorkQueue()); + } + return self; +} + +- (void)enqueueTask:(FIRAuthSerialTask)task { + // This dispatch queue will run tasks serially in FIFO order, as long as it's not suspended. + dispatch_async(self->_dispatchQueue, ^{ + // But as soon as a task is started, stop other tasks from running until the task calls it's + // completion handler, which allows the queue to resume processing of tasks. This allows the + // task to perform other asyncronous actions on other dispatch queues and "get back to us" when + // all of their sub-tasks are complete. + dispatch_suspend(self->_dispatchQueue); + task(^{ + dispatch_resume(self->_dispatchQueue); + }); + }); +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSettings.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSettings.m new file mode 100644 index 0000000..575bb3c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthSettings.m @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "FIRAuthSettings.h" + +@implementation FIRAuthSettings + +- (instancetype)init { + self = [super init]; + if (self) { + _appVerificationDisabledForTesting = NO; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult.m new file mode 100644 index 0000000..3a06ac6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult.m @@ -0,0 +1,110 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthTokenResult_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kExpirationDateKey + @brief The key used to encode the expirationDate property for NSSecureCoding. + */ +static NSString *const kExpirationDateKey = @"expiratinDate"; + +/** @var kTokenKey + @brief The key used to encode the token property for NSSecureCoding. + */ +static NSString *const kTokenKey = @"token"; + +/** @var kAuthDateKey + @brief The key used to encode the authDate property for NSSecureCoding. + */ +static NSString *const kAuthDateKey = @"authDate"; + +/** @var kIssuedDateKey + @brief The key used to encode the issuedDate property for NSSecureCoding. + */ +static NSString *const kIssuedDateKey = @"issuedDate"; + +/** @var kSignInProviderKey + @brief The key used to encode the signInProvider property for NSSecureCoding. + */ +static NSString *const kSignInProviderKey = @"signInProvider"; + +/** @var kClaimsKey + @brief The key used to encode the claims property for NSSecureCoding. + */ +static NSString *const kClaimsKey = @"claims"; + +@implementation FIRAuthTokenResult + +- (instancetype)initWithToken:(NSString *)token + expirationDate:(NSDate *)expirationDate + authDate:(NSDate *)authDate + issuedAtDate:(NSDate *)issuedAtDate + signInProvider:(NSString *)signInProvider + claims:(NSDictionary *)claims { + self = [super init]; + if (self) { + _token = token; + _expirationDate = expirationDate; + _authDate = authDate; + _issuedAtDate = issuedAtDate; + _signInProvider = signInProvider; + _claims = claims; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *token = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kTokenKey]; + NSDate *expirationDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kExpirationDateKey]; + NSDate *authDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kAuthDateKey]; + NSDate *issuedAtDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kAuthDateKey]; + NSString *signInProvider = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kSignInProviderKey]; + NSDictionary *claims = + [aDecoder decodeObjectOfClass:[NSDictionary class] forKey:kClaimsKey]; + + return [self initWithToken:token + expirationDate:expirationDate + authDate:authDate + issuedAtDate:issuedAtDate + signInProvider:signInProvider + claims:claims]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_token forKey:kTokenKey]; + [aCoder encodeObject:_expirationDate forKey:kExpirationDateKey]; + [aCoder encodeObject:_authDate forKey:kAuthDateKey]; + [aCoder encodeObject:_issuedAtDate forKey:kIssuedDateKey]; + [aCoder encodeObject:_signInProvider forKey:kSignInProviderKey]; + [aCoder encodeObject:_claims forKey:kClaimsKey]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult_Internal.h new file mode 100644 index 0000000..2914f2a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthTokenResult_Internal.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #import + + #import "FIRAuthTokenResult.h" + + NS_ASSUME_NONNULL_BEGIN + +/** @extension FIRAuthAPNSTokenResult + @brief An internal class used to expose internal methods of FIRAuthAPNSTokenResult. + */ +@interface FIRAuthTokenResult () + +- (instancetype)initWithToken:(NSString *)token + expirationDate:(NSDate *)expirationDate + authDate:(NSDate *)authDate + issuedAtDate:(NSDate *)issuedAtDate + signInProvider:(NSString *)signInProvider + claims:(NSDictionary *)claims; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.h new file mode 100644 index 0000000..a886a3e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.h @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol FIRAuthUIDelegate; + +/** @typedef FIRAuthURLPresentationCompletion + @brief The type of block invoked when the URLPresentation completes. + @param callbackURL The callback URL if the presentation ends with a matching callback. + @param error The error if the presentation fails to start or ends with an error. + */ +typedef void (^FIRAuthURLPresentationCompletion)(NSURL *_Nullable callbackURL, + NSError *_Nullable error); + +/** @typedef FIRAuthCallbackMatcher + @brief The type of block invoked for checking whether a callback URL matches. + @param callbackURL The callback URL to check for match. + @return Whether or not the specific callback URL matches or not. + */ +typedef BOOL (^FIRAuthURLCallbackMatcher)(NSURL * _Nullable callbackURL); + +/** @class FIRAuthURLPresenter + @brief A Class responsible for presenting URL via SFSafariViewController or UIWebView. + */ +@interface FIRAuthURLPresenter : NSObject + +/** @fn presentURL:UIDelegate:callbackMatcher:completion: + @brief Presents an URL to interact with user. + @param URL The URL to present. + @param UIDelegate The UI delegate to present view controller. + @param completion A block to be called either synchronously if the presentation fails to start, + or asynchronously in future on an unspecified thread once the presentation finishes. + */ +- (void)presentURL:(NSURL *)URL + UIDelegate:(nullable id)UIDelegate + callbackMatcher:(FIRAuthURLCallbackMatcher)callbackMatcher + completion:(FIRAuthURLPresentationCompletion)completion; + +/** @fn canHandleURL: + @brief Determines if a URL was produced by the currently presented URL. + @param URL The URL to handle. + @return Whether the URL could be handled or not. + */ +- (BOOL)canHandleURL:(NSURL *)URL; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.m new file mode 100644 index 0000000..d8e3593 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthURLPresenter.m @@ -0,0 +1,190 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthURLPresenter.h" + +#import + +#import "FIRAuthDefaultUIDelegate.h" +#import "FIRAuthErrorUtils.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FIRAuthUIDelegate.h" +#import "FIRAuthWebViewController.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAuthURLPresenter () +@end + +// Disable unguarded availability warnings because SFSafariViewController is been used throughout +// the code, including as an iVar, which cannot be simply excluded by @available check. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + +@implementation FIRAuthURLPresenter { + /** @var _isPresenting + @brief Whether or not some web-based content is being presented. + */ + BOOL _isPresenting; + + /** @var _callbackMatcher + @brief The callback URL matcher for the current presentation, if one is active. + */ + FIRAuthURLCallbackMatcher _Nullable _callbackMatcher; + + /** @var _safariViewController + @brief The SFSafariViewController used for the current presentation, if any. + */ + SFSafariViewController *_Nullable _safariViewController; + + /** @var _webViewController + @brief The FIRAuthWebViewController used for the current presentation, if any. + */ + FIRAuthWebViewController *_Nullable _webViewController; + + /** @var _UIDelegate + @brief The UIDelegate used to present the SFSafariViewController. + */ + id _UIDelegate; + + /** @var _completion + @brief The completion handler for the current presentaion, if one is active. + @remarks This variable is also used as a flag to indicate a presentation is active. + */ + FIRAuthURLPresentationCompletion _Nullable _completion; +} + +- (void)presentURL:(NSURL *)URL + UIDelegate:(nullable id)UIDelegate + callbackMatcher:(FIRAuthURLCallbackMatcher)callbackMatcher + completion:(FIRAuthURLPresentationCompletion)completion { + if (_isPresenting) { + // Unable to start a new presentation on top of another. + _completion(nil, [FIRAuthErrorUtils webContextAlreadyPresentedErrorWithMessage:nil]); + return; + } + _isPresenting = YES; + _callbackMatcher = callbackMatcher; + _completion = completion; + dispatch_async(dispatch_get_main_queue(), ^() { + self->_UIDelegate = UIDelegate ?: [FIRAuthDefaultUIDelegate defaultUIDelegate]; + if ([SFSafariViewController class]) { + self->_safariViewController = [[SFSafariViewController alloc] initWithURL:URL]; + self->_safariViewController.delegate = self; + [self->_UIDelegate presentViewController:self->_safariViewController + animated:YES + completion:nil]; + return; + } else { + self->_webViewController = [[FIRAuthWebViewController alloc] initWithURL:URL delegate:self]; + UINavigationController *navController = + [[UINavigationController alloc] initWithRootViewController:self->_webViewController]; + [self->_UIDelegate presentViewController:navController animated:YES completion:nil]; + } + }); +} + +- (BOOL)canHandleURL:(NSURL *)URL { + if (_isPresenting && _callbackMatcher && _callbackMatcher(URL)) { + [self finishPresentationWithURL:URL error:nil]; + return YES; + } + return NO; +} + +#pragma mark - SFSafariViewControllerDelegate + +- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller { + dispatch_async(FIRAuthGlobalWorkQueue(), ^() { + if (controller == self->_safariViewController) { + self->_safariViewController = nil; + //TODO:Ensure that the SFSafariViewController is actually removed from the screen before + //invoking finishPresentationWithURL:error: + [self finishPresentationWithURL:nil + error:[FIRAuthErrorUtils webContextCancelledErrorWithMessage:nil]]; + } + }); +} + +#pragma mark - FIRAuthwebViewControllerDelegate + +- (BOOL)webViewController:(FIRAuthWebViewController *)webViewController canHandleURL:(NSURL *)URL { + __block BOOL result = NO; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^() { + if (webViewController == self->_webViewController) { + result = [self canHandleURL:URL]; + } + }); + return result; +} + +- (void)webViewControllerDidCancel:(FIRAuthWebViewController *)webViewController { + dispatch_async(FIRAuthGlobalWorkQueue(), ^() { + if (webViewController == self->_webViewController) { + [self finishPresentationWithURL:nil + error:[FIRAuthErrorUtils webContextCancelledErrorWithMessage:nil]]; + } + }); +} + +- (void)webViewController:(FIRAuthWebViewController *)webViewController + didFailWithError:(NSError *)error { + dispatch_async(FIRAuthGlobalWorkQueue(), ^() { + if (webViewController == self->_webViewController) { + [self finishPresentationWithURL:nil error:error]; + } + }); +} + +#pragma mark - Private methods + +/** @fn finishPresentationWithURL:error: + @brief Finishes the presentation for a given URL, if any. + @param URL The URL to finish presenting. + @param error The error with which to finish presenting, if any. + */ +- (void)finishPresentationWithURL:(nullable NSURL *)URL + error:(nullable NSError *)error { + _callbackMatcher = nil; + id UIDelegate = _UIDelegate; + _UIDelegate = nil; + FIRAuthURLPresentationCompletion completion = _completion; + _completion = nil; + void (^finishBlock)(void) = ^() { + self->_isPresenting = NO; + completion(URL, error); + }; + SFSafariViewController *safariViewController = _safariViewController; + _safariViewController = nil; + FIRAuthWebViewController *webViewController = _webViewController; + _webViewController = nil; + if (safariViewController || webViewController) { + dispatch_async(dispatch_get_main_queue(), ^() { + [UIDelegate dismissViewControllerAnimated:YES completion:^() { + dispatch_async(FIRAuthGlobalWorkQueue(), finishBlock); + }]; + }); + } else { + finishBlock(); + } +} + +#pragma clang diagnostic pop // ignored "-Wunguarded-availability" + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.h new file mode 100644 index 0000000..13774ab --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +// This class is only available in the simulator. +#if TARGET_OS_SIMULATOR +#ifndef FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE +#define FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE 1 +#endif +#endif + +#if FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE + +#import "FIRAuthKeychain.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthUserDefaultsStorage + @brief The utility class to storage data in NSUserDefaults. + */ +@interface FIRAuthUserDefaultsStorage : NSObject + +/** @fn clear + @brief Clears all data from the storage. + @remarks This method is only supposed to be called from tests. + */ +- (void)clear; + +@end + +NS_ASSUME_NONNULL_END + +#endif // FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.m new file mode 100644 index 0000000..d9f012a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthUserDefaultsStorage.m @@ -0,0 +1,78 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthUserDefaultsStorage.h" + +#if FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE + +NS_ASSUME_NONNULL_BEGIN + +static NSString *const kPersistentDomainNamePrefix = @"com.google.Firebase.Auth."; + +@implementation FIRAuthUserDefaultsStorage { + /** @var _persistentDomainName + @brief The name of the persistent domain in user defaults. + */ + NSString *_persistentDomainName; + + /** @var _storage + @brief The backing NSUserDefaults storage for this instance. + */ + NSUserDefaults *_storage; +} + +- (id)initWithService:(NSString *)service { + self = [super init]; + if (self) { + _persistentDomainName = [kPersistentDomainNamePrefix stringByAppendingString:service]; + _storage = [[NSUserDefaults alloc] init]; + } + return self; +} + +- (nullable NSData *)dataForKey:(NSString *)key error:(NSError **_Nullable)error { + if (error) { + *error = nil; + } + NSDictionary *allData = [_storage persistentDomainForName:_persistentDomainName]; + return allData[key]; +} + +- (BOOL)setData:(NSData *)data forKey:(NSString *)key error:(NSError **_Nullable)error { + NSMutableDictionary *allData = + [([_storage persistentDomainForName:_persistentDomainName] ?: @{}) mutableCopy]; + allData[key] = data; + [_storage setPersistentDomain:allData forName:_persistentDomainName]; + return YES; +} + +- (BOOL)removeDataForKey:(NSString *)key error:(NSError **_Nullable)error { + NSMutableDictionary *allData = + [[_storage persistentDomainForName:_persistentDomainName] mutableCopy]; + [allData removeObjectForKey:key]; + [_storage setPersistentDomain:allData forName:_persistentDomainName]; + return YES; +} + +- (void)clear { + [_storage setPersistentDomain:@{} forName:_persistentDomainName]; +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // FIRAUTH_USER_DEFAULTS_STORAGE_AVAILABLE diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.h new file mode 100644 index 0000000..dedd1a5 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.h @@ -0,0 +1,67 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthRequestConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRFetchAuthDomainCallback + @brief The callback invoked at the end of the flow to fetch the Auth domain. + @param authDomain The Auth domain. + @param error The error that occurred while fetching the auth domain, if any. + */ +typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain, + NSError *_Nullable error); + +/** @class FIRAuthURLUtils + @brief A utility class used to facilitate the creation of auth related URLs. + */ +@interface FIRAuthWebUtils : NSObject + +/** @fn randomStringWithLength: + @brief Generates a random string of a specified length. + */ ++ (NSString *)randomStringWithLength:(NSUInteger)length; + +/** @fn isCallbackSchemeRegisteredForCustomURLScheme: + @brief Checks whether or not the provided custom URL scheme has been registered by the app. + @param URLScheme The custom URL scheme to be checked against all custom URL schemes registered by the app. + @return whether or not the provided custom URL scheme has been registered by the app. + */ ++ (BOOL)isCallbackSchemeRegisteredForCustomURLScheme:(NSString *)URLScheme; + +/** @fn fetchAuthDomainWithCompletion:completion: + @brief Fetches the auth domain associated with the Firebase Project. + @param completion The callback invoked after the auth domain has been constructed or an error + has been encountered. + */ ++ (void)fetchAuthDomainWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + completion:(FIRFetchAuthDomainCallback)completion; + +/** @fn queryItemValue:from: + @brief Utility function to get a value from a NSURLQueryItem array. + @param name The key. + @param queryList The NSURLQueryItem array. + @return The value for the key. + */ + ++ (nullable NSString *)queryItemValue:(NSString *)name from:(NSArray *)queryList; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.m new file mode 100644 index 0000000..372e424 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebUtils.m @@ -0,0 +1,100 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthWebUtils.h" + +#import "FIRAuthBackend.h" +#import "FIRAuthErrorUtils.h" +#import "FIRGetProjectConfigRequest.h" +#import "FIRGetProjectConfigResponse.h" + +/** @var kAuthDomainSuffix + @brief The suffix of the auth domain pertiaining to a given Firebase project. + */ +static NSString *const kAuthDomainSuffix = @"firebaseapp.com"; + +@implementation FIRAuthWebUtils + ++ (NSString *)randomStringWithLength:(NSUInteger)length { + NSMutableString *randomString = [[NSMutableString alloc] init]; + for (int i=0; i < length; i++) { + [randomString appendString: + [NSString stringWithFormat:@"%c", 'a' + arc4random_uniform('z' - 'a' + 1)]]; + } + return randomString; +} + ++ (BOOL)isCallbackSchemeRegisteredForCustomURLScheme:(NSString *)URLScheme { + NSString *expectedCustomScheme = [URLScheme lowercaseString]; + NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"]; + for (NSDictionary *urlType in urlTypes) { + NSArray *urlTypeSchemes = urlType[@"CFBundleURLSchemes"]; + for (NSString *urlTypeScheme in urlTypeSchemes) { + if ([urlTypeScheme.lowercaseString isEqualToString:expectedCustomScheme]) { + return YES; + } + } + } + return NO; +} + ++ (void)fetchAuthDomainWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + completion:(FIRFetchAuthDomainCallback)completion { + FIRGetProjectConfigRequest *request = + [[FIRGetProjectConfigRequest alloc] initWithRequestConfiguration:requestConfiguration]; + + [FIRAuthBackend getProjectConfig:request + callback:^(FIRGetProjectConfigResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + completion(nil, error); + return; + } + NSString *authDomain; + for (NSString *domain in response.authorizedDomains) { + NSInteger index = domain.length - kAuthDomainSuffix.length; + if (index >= 2) { + if ([domain hasSuffix:kAuthDomainSuffix] && domain.length >= kAuthDomainSuffix.length + 2) { + authDomain = domain; + break; + } + } + } + if (!authDomain.length) { + completion(nil, [FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:response]); + return; + } + completion(authDomain, nil); + }]; +} + +/** @fn queryItemValue:from: + @brief Utility function to get a value from a NSURLQueryItem array. + @param name The key. + @param queryList The NSURLQueryItem array. + @return The value for the key. + */ + ++ (nullable NSString *)queryItemValue:(NSString *)name from:(NSArray *)queryList { + for (NSURLQueryItem *item in queryList) { + if ([item.name isEqualToString:name]) { + return item.value; + } + } + return nil; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.h new file mode 100644 index 0000000..28af833 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthWebView + @brief A class reponsible for creating a UIWebview for use within Firebase Auth. + */ +@interface FIRAuthWebView : UIView + +/** @property webView + * @brief The web view. + */ +@property(nonatomic, weak) UIWebView *webView; + +/** @property spinner + * @brief The spinner that indicates web view loading. + */ +@property(nonatomic, weak) UIActivityIndicatorView *spinner; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.m new file mode 100644 index 0000000..80b90f0 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebView.m @@ -0,0 +1,86 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthWebView.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAuthWebView + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor whiteColor]; + [self initializeSubviews]; + } + return self; +} + +/** @fn initializeSubviews + @brief Initializes the subviews of this view. + */ +- (void)initializeSubviews { + UIWebView *webView = [self createWebView]; + UIActivityIndicatorView *spinner = [self createSpinner]; + + // The order of the following controls z-order. + [self addSubview:webView]; + [self addSubview:spinner]; + + [self layoutSubviews]; + _webView = webView; + _spinner = spinner; +} + +- (void)layoutSubviews { + CGFloat height = self.bounds.size.height; + CGFloat width = self.bounds.size.width; + _webView.frame = CGRectMake(0, 0, width, height); + _spinner.center = _webView.center; +} + +/** @fn createWebView + @brief Creates a web view to be used by this view. + @return The newly created web view. + */ +- (UIWebView *)createWebView { + UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero]; + // Trickery to make the web view not do weird things (like showing a black background when + // the prompt in the navigation bar animates changes.) + webView.opaque = NO; + webView.backgroundColor = [UIColor clearColor]; + webView.scrollView.opaque = NO; + webView.scrollView.backgroundColor = [UIColor clearColor]; + webView.scrollView.bounces = NO; + webView.scrollView.alwaysBounceVertical = NO; + webView.scrollView.alwaysBounceHorizontal = NO; + return webView; +} + +/** @fn createSpinner + @brief Creates a spinner to be used by this view. + @return The newly created spinner. + */ +- (UIActivityIndicatorView *)createSpinner { + UIActivityIndicatorViewStyle spinnerStyle = UIActivityIndicatorViewStyleGray; + UIActivityIndicatorView *spinner = + [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:spinnerStyle]; + return spinner; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.h new file mode 100644 index 0000000..4bf9678 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.h @@ -0,0 +1,73 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthWebViewController; + +NS_ASSUME_NONNULL_BEGIN + +/** @protocol FIRAuthWebViewControllerDelegate + @brief Defines a delegate for FIRAuthWebViewController + */ +@protocol FIRAuthWebViewControllerDelegate + +/** @fn webViewController:canHandleURL: + @brief Determines if a URL should be handled by the delegate. + @param URL The URL to handle. + @return Whether the URL could be handled or not. + */ +- (BOOL)webViewController:(FIRAuthWebViewController *)webViewController canHandleURL:(NSURL *)URL; + +/** @fn webViewControllerDidCancel: + @brief Notifies the delegate that the web view controller is being cancelled by the user. + @param webViewController The web view controller in question. + */ +- (void)webViewControllerDidCancel:(FIRAuthWebViewController *)webViewController; + +/** @fn webViewController:didFailWithError: + @brief Notifies the delegate that the web view controller failed to load a page. + @param webViewController The web view controller in question. + @param error The error that has occurred. + */ +- (void)webViewController:(FIRAuthWebViewController *)webViewController + didFailWithError:(NSError *)error; + +@end + +/** @class FIRAuthWebViewController + @brief Reponsible for creating a UIViewController for presenting a FIRAutWebView. + */ +@interface FIRAuthWebViewController : UIViewController + +/** @fn initWithNibName:bundle: + * @brief Please call initWithURL:delegate: + */ +- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil + bundle:(nullable NSBundle *)nibBundleOrNil NS_UNAVAILABLE; + +/** @fn initWithCoder: + * @brief Please call initWithURL:delegate: + */ +- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; + +- (instancetype)initWithURL:(NSURL *)URL + delegate:(__weak id)delegate + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.m new file mode 100644 index 0000000..a3ab06a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuthWebViewController.m @@ -0,0 +1,111 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthWebViewController.h" + +#import "FIRAuthWebView.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAuthWebViewController () +@end + +@implementation FIRAuthWebViewController { + /** @var _URL + @brief The initial URL to display. + */ + NSURL *_URL; + + /** @var _delegate + @brief The delegate to call. + */ + __weak id _delegate; + + /** @var _webView; + @brief The web view instance for easier access. + */ + __weak FIRAuthWebView *_webView; +} + +- (instancetype)initWithURL:(NSURL *)URL + delegate:(__weak id)delegate { + self = [super initWithNibName:nil bundle:nil]; + if (self) { + _URL = URL; + _delegate = delegate; + } + return self; +} + +#pragma mark - Lifecycle + +- (void)loadView { + FIRAuthWebView *webView = [[FIRAuthWebView alloc] initWithFrame:[UIScreen mainScreen].bounds]; + webView.webView.delegate = self; + self.view = webView; + _webView = webView; + self.navigationItem.leftBarButtonItem = + [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel + target:self + action:@selector(cancel)]; +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + + // Loads the requested URL in the web view. + [_webView.webView loadRequest:[NSURLRequest requestWithURL:_URL]]; +} + +#pragma mark - UI Targets + +- (void)cancel { + [_delegate webViewControllerDidCancel:self]; +} + +#pragma mark - UIWebViewDelegate + +- (BOOL)webView:(UIWebView *)webView + shouldStartLoadWithRequest:(NSURLRequest *)request + navigationType:(UIWebViewNavigationType)navigationType { + return ![_delegate webViewController:self canHandleURL:request.URL]; +} + +- (void)webViewDidStartLoad:(UIWebView *)webView { + // Show & animate the activity indicator. + _webView.spinner.hidden = NO; + [_webView.spinner startAnimating]; +} + +- (void)webViewDidFinishLoad:(UIWebView *)webView { + // Hide & stop the activity indicator. + _webView.spinner.hidden = YES; + [_webView.spinner stopAnimating]; +} + +- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { + if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) { + // It's okay for the page to be redirected before it is completely loaded. See b/32028062 . + return; + } + // Forward notification to our delegate. + [self webViewDidFinishLoad:webView]; + [_delegate webViewController:self didFailWithError:error]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth_Internal.h new file mode 100644 index 0000000..d4184f1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRAuth_Internal.h @@ -0,0 +1,122 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuth.h" + +#import + +@class FIRAuthRequestConfiguration; + +#if TARGET_OS_IOS +@class FIRAuthAPNSTokenManager; +@class FIRAuthAppCredentialManager; +@class FIRAuthNotificationManager; +@class FIRAuthURLPresenter; +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAuth () + +/** @property requestConfiguration + @brief The configuration object comprising of paramters needed to make a request to Firebase + Auth's backend. + */ +@property(nonatomic, copy, readonly) FIRAuthRequestConfiguration *requestConfiguration; + +#if TARGET_OS_IOS + +/** @property tokenManager + @brief The manager for APNs tokens used by phone number auth. + */ +@property(nonatomic, strong, readonly) FIRAuthAPNSTokenManager *tokenManager; + +/** @property appCredentailManager + @brief The manager for app credentials used by phone number auth. + */ +@property(nonatomic, strong, readonly) FIRAuthAppCredentialManager *appCredentialManager; + +/** @property notificationManager + @brief The manager for remote notifications used by phone number auth. + */ +@property(nonatomic, strong, readonly) FIRAuthNotificationManager *notificationManager; + +/** @property authURLPresenter + @brief An object that takes care of presenting URLs via the auth instance. + */ +@property(nonatomic, strong, readonly) FIRAuthURLPresenter *authURLPresenter; + +#endif // TARGET_OS_IOS + +/** @fn initWithAPIKey:appName: + @brief Designated initializer. + @param APIKey The Google Developers Console API key for making requests from your app. + @param appName The name property of the previously created @c FIRApp instance. + */ +- (nullable instancetype)initWithAPIKey:(NSString *)APIKey + appName:(NSString *)appName NS_DESIGNATED_INITIALIZER; + +/** @fn getUserID + @brief Gets the identifier of the current user, if any. + @return The identifier of the current user, or nil if there is no current user. + */ +- (nullable NSString *)getUserID; + +/** @fn updateKeychainWithUser:error: + @brief Updates the keychain for the given user. + @param user The user to be updated. + @param error The error caused the method to fail if the method returns NO. + @return Whether updating keychain has succeeded or not. + @remarks Called by @c FIRUser when user info or token changes occur. + */ +- (BOOL)updateKeychainWithUser:(FIRUser *)user error:(NSError *_Nullable *_Nullable)error; + +/** @fn internalSignInWithCredential:callback: + @brief Convenience method for @c internalSignInAndRetrieveDataWithCredential:callback: + This method doesn't return additional identity provider data. +*/ +- (void)internalSignInWithCredential:(FIRAuthCredential *)credential + callback:(FIRAuthResultCallback)callback; + +/** @fn internalSignInAndRetrieveDataWithCredential:callback: + @brief Asynchronously signs in Firebase with the given 3rd party credentials (e.g. a Facebook + login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional + identity provider data. + @param credential The credential supplied by the IdP. + @param isReauthentication Indicates whether or not the current invocation originated from an + attempt to reauthenticate. + @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked + asynchronously on the auth global work queue in the future. + @remarks This is the internal counterpart of this method, which uses a callback that does not + update the current user. + */ +- (void)internalSignInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential + isReauthentication:(BOOL)isReauthentication + callback:(nullable FIRAuthDataResultCallback)callback; + +/** @fn signOutByForceWithUserID:error: + @brief Signs out the current user. + @param userID The ID of the user to force sign out. + @param error An optional out parameter for error results. + @return @YES when the sign out request was successful. @NO otherwise. + */ +- (BOOL)signOutByForceWithUserID:(NSString *)userID error:(NSError *_Nullable *_Nullable)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.h new file mode 100644 index 0000000..989e786 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.h @@ -0,0 +1,99 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthRequestConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRFetchAccessTokenCallback + @brief The callback used to return the value of attempting to fetch an access token. + + In the event the operation was successful @c token will be set and @c error will be @c nil. + In the event of failure @c token will be @c nil and @c error will be set. + @c tokenUpdated indicates whether either the access or the refresh token has been updated. + + The token returned should be considered ephemeral and not cached. It should be used immediately + and discarded. All operations that need this token should call fetchAccessToken and do their + work from the callback. + */ +typedef void(^FIRFetchAccessTokenCallback)(NSString *_Nullable token, + NSError *_Nullable error, + BOOL tokenUpdated); + +/** @class FIRSecureTokenService + @brief Provides services for token exchanges and refreshes. + */ +@interface FIRSecureTokenService : NSObject + +/** @property requestConfiguration + @brief The configuration for making requests to server. + */ +@property(nonatomic, strong) FIRAuthRequestConfiguration *requestConfiguration; + +/** @property rawAccessToken + @brief The cached access token. + @remarks This method is specifically for providing the access token to internal clients during + deserialization and sign-in events, and should not be used to retrieve the access token by + anyone else. + */ +@property(nonatomic, copy, readonly) NSString *rawAccessToken; + +/** @property refreshToken + @brief The refresh token for the user, or @c nil if the user has yet completed sign-in flow. + @remarks This property needs to be set manually after the instance is decoded from archive. + */ +@property(nonatomic, copy, readonly, nullable) NSString *refreshToken; + +/** @property accessTokenExpirationDate + @brief The expiration date of the cached access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *accessTokenExpirationDate; + +/** @fn initWithRequestConfiguration:authorizationCode: + @brief Creates a @c FIRSecureTokenService with an authroization code. + @param requestConfiguration The configuration for making requests to server. + @param authorizationCode An authorization code which needs to be exchanged for STS tokens. + */ +- (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + authorizationCode:(NSString *)authorizationCode; + +/** @fn initWithRequestConfiguration:accessToken:accessTokenExpirationDate:refreshToken + @brief Creates a @c FIRSecureTokenService with access and refresh tokens. + @param requestConfiguration The configuration for making requests to server. + @param accessToken The STS access token. + @param accessTokenExpirationDate The approximate expiration date of the access token. + @param refreshToken The STS refresh token. + */ +- (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + accessToken:(nullable NSString *)accessToken + accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate + refreshToken:(NSString *)refreshToken; + +/** @fn fetchAccessTokenForcingRefresh:callback: + @brief Fetch a fresh ephemeral access token for the ID associated with this instance. The token + received in the callback should be considered short lived and not cached. + @param forceRefresh Forces the token to be refreshed. + @param callback Callback block that will be called to return either the token or an error. + Invoked asyncronously on the auth global work queue in the future. + */ +- (void)fetchAccessTokenForcingRefresh:(BOOL)forceRefresh + callback:(FIRFetchAccessTokenCallback)callback; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.m new file mode 100644 index 0000000..69434ff --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRSecureTokenService.m @@ -0,0 +1,206 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSecureTokenService.h" + +#import "FIRAuth.h" +#import "FIRAuthKeychain.h" +#import "FIRAuthSerialTaskQueue.h" +#import "FIRAuthBackend.h" +#import "FIRAuthRequestConfiguration.h" +#import "FIRSecureTokenRequest.h" +#import "FIRSecureTokenResponse.h" + +/** @var kAPIKeyCodingKey + @brief The key used to encode the APIKey for NSSecureCoding. + */ +static NSString *const kAPIKeyCodingKey = @"APIKey"; + +/** @var kRefreshTokenKey + @brief The key used to encode the refresh token for NSSecureCoding. + */ +static NSString *const kRefreshTokenKey = @"refreshToken"; + +/** @var kAccessTokenKey + @brief The key used to encode the access token for NSSecureCoding. + */ +static NSString *const kAccessTokenKey = @"accessToken"; + +/** @var kAccessTokenExpirationDateKey + @brief The key used to encode the access token expiration date for NSSecureCoding. + */ +static NSString *const kAccessTokenExpirationDateKey = @"accessTokenExpirationDate"; + +/** @var kFiveMinutes + @brief Five minutes (in seconds.) + */ +static const NSTimeInterval kFiveMinutes = 5 * 60; + +@interface FIRSecureTokenService () +- (instancetype)init NS_DESIGNATED_INITIALIZER; +@end + +@implementation FIRSecureTokenService { + /** @var _taskQueue + @brief Used to serialize all requests for access tokens. + */ + FIRAuthSerialTaskQueue *_taskQueue; + + /** @var _authorizationCode + @brief An authorization code which needs to be exchanged for Secure Token Service tokens. + */ + NSString *_Nullable _authorizationCode; + + /** @var _accessToken + @brief The currently cached access token. Or |nil| if no token is currently cached. + */ + NSString *_Nullable _accessToken; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _taskQueue = [[FIRAuthSerialTaskQueue alloc] init]; + } + return self; +} + +- (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + authorizationCode:(NSString *)authorizationCode { + self = [self init]; + if (self) { + _requestConfiguration = requestConfiguration; + _authorizationCode = [authorizationCode copy]; + } + return self; +} + +- (instancetype)initWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + accessToken:(nullable NSString *)accessToken + accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate + refreshToken:(NSString *)refreshToken { + self = [self init]; + if (self) { + _requestConfiguration = requestConfiguration; + _accessToken = [accessToken copy]; + _accessTokenExpirationDate = [accessTokenExpirationDate copy]; + _refreshToken = [refreshToken copy]; + } + return self; +} + +- (void)fetchAccessTokenForcingRefresh:(BOOL)forceRefresh + callback:(FIRFetchAccessTokenCallback)callback { + [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock complete) { + if (!forceRefresh && [self hasValidAccessToken]) { + complete(); + callback(self->_accessToken, nil, NO); + } else { + [self requestAccessToken:^(NSString *_Nullable token, + NSError *_Nullable error, + BOOL tokenUpdated) { + complete(); + callback(token, error, tokenUpdated); + }]; + } + }]; +} + +- (NSString *)rawAccessToken { + return _accessToken; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey]; + NSString *accessToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAccessTokenKey]; + NSDate *accessTokenExpirationDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kAccessTokenExpirationDateKey]; + if (!refreshToken) { + return nil; + } + self = [self init]; + if (self) { + _refreshToken = refreshToken; + _accessToken = accessToken; + _accessTokenExpirationDate = accessTokenExpirationDate; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + // The API key is encoded even it is not used in decoding to be compatible with previous versions + // of the library. + [aCoder encodeObject:_requestConfiguration.APIKey forKey:kAPIKeyCodingKey]; + // Authorization code is not encoded because it is not long-lived. + [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey]; + [aCoder encodeObject:_accessToken forKey:kAccessTokenKey]; + [aCoder encodeObject:_accessTokenExpirationDate forKey:kAccessTokenExpirationDateKey]; +} + +#pragma mark - Private methods + +/** @fn requestAccessToken: + @brief Makes a request to STS for an access token. + @details This handles both the case that the token has not been granted yet and that it just + needs to be refreshed. The caller is responsible for making sure that this is occurring in + a @c _taskQueue task. + @param callback Called when the fetch is complete. Invoked asynchronously on the main thread in + the future. + @remarks Because this method is guaranteed to only be called from tasks enqueued in + @c _taskQueue, we do not need any @synchronized guards around access to _accessToken/etc. + since only one of those tasks is ever running at a time, and those tasks are the only + access to and mutation of these instance variables. + */ +- (void)requestAccessToken:(FIRFetchAccessTokenCallback)callback { + FIRSecureTokenRequest *request; + if (_refreshToken.length) { + request = [FIRSecureTokenRequest refreshRequestWithRefreshToken:_refreshToken + requestConfiguration:_requestConfiguration]; + } else { + request = [FIRSecureTokenRequest authCodeRequestWithCode:_authorizationCode + requestConfiguration:_requestConfiguration]; + } + [FIRAuthBackend secureToken:request + callback:^(FIRSecureTokenResponse *_Nullable response, + NSError *_Nullable error) { + BOOL tokenUpdated = NO; + NSString *newAccessToken = response.accessToken; + if (newAccessToken.length && ![newAccessToken isEqualToString:self->_accessToken]) { + self->_accessToken = [newAccessToken copy]; + self->_accessTokenExpirationDate = response.approximateExpirationDate; + tokenUpdated = YES; + } + NSString *newRefreshToken = response.refreshToken; + if (newRefreshToken.length && + ![newRefreshToken isEqualToString:self->_refreshToken]) { + self->_refreshToken = [newRefreshToken copy]; + tokenUpdated = YES; + } + callback(newAccessToken, error, tokenUpdated); + }]; +} + +- (BOOL)hasValidAccessToken { + return _accessToken && [_accessTokenExpirationDate timeIntervalSinceNow] > kFiveMinutes; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser.m new file mode 100644 index 0000000..4bfdc1a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser.m @@ -0,0 +1,1450 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRUser_Internal.h" + +#import + +#import "FIRAdditionalUserInfo_Internal.h" +#import "FIRAuth.h" +#import "FIRAuthCredential_Internal.h" +#import "FIRAuthDataResult_Internal.h" +#import "FIRAuthErrorUtils.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FIRAuthSerialTaskQueue.h" +#import "FIRAuthOperationType.h" +#import "FIRAuth_Internal.h" +#import "FIRAuthBackend.h" +#import "FIRAuthRequestConfiguration.h" +#import "FIRAuthTokenResult_Internal.h" +#import "FIRDeleteAccountRequest.h" +#import "FIRDeleteAccountResponse.h" +#import "FIREmailAuthProvider.h" +#import "FIREmailPasswordAuthCredential.h" +#import "FIRGameCenterAuthCredential.h" +#import "FIRGetAccountInfoRequest.h" +#import "FIRGetAccountInfoResponse.h" +#import "FIRGetOOBConfirmationCodeRequest.h" +#import "FIRGetOOBConfirmationCodeResponse.h" +#import "FIRSecureTokenService.h" +#import "FIRSetAccountInfoRequest.h" +#import "FIRSetAccountInfoResponse.h" +#import "FIRSignInWithGameCenterRequest.h" +#import "FIRSignInWithGameCenterResponse.h" +#import "FIRUserInfoImpl.h" +#import "FIRUserMetadata_Internal.h" +#import "FIRVerifyAssertionRequest.h" +#import "FIRVerifyAssertionResponse.h" +#import "FIRVerifyCustomTokenRequest.h" +#import "FIRVerifyCustomTokenResponse.h" +#import "FIRVerifyPasswordRequest.h" +#import "FIRVerifyPasswordResponse.h" +#import "FIRVerifyPhoneNumberRequest.h" +#import "FIRVerifyPhoneNumberResponse.h" + +#if TARGET_OS_IOS +#import "FIRPhoneAuthProvider.h" +#import "AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** @var kUserIDCodingKey + @brief The key used to encode the user ID for NSSecureCoding. + */ +static NSString *const kUserIDCodingKey = @"userID"; + +/** @var kHasEmailPasswordCredentialCodingKey + @brief The key used to encode the hasEmailPasswordCredential property for NSSecureCoding. + */ +static NSString *const kHasEmailPasswordCredentialCodingKey = @"hasEmailPassword"; + +/** @var kAnonymousCodingKey + @brief The key used to encode the anonymous property for NSSecureCoding. + */ +static NSString *const kAnonymousCodingKey = @"anonymous"; + +/** @var kEmailCodingKey + @brief The key used to encode the email property for NSSecureCoding. + */ +static NSString *const kEmailCodingKey = @"email"; + +/** @var kPhoneNumberCodingKey + @brief The key used to encode the phoneNumber property for NSSecureCoding. + */ +static NSString *const kPhoneNumberCodingKey = @"phoneNumber"; + +/** @var kEmailVerifiedCodingKey + @brief The key used to encode the isEmailVerified property for NSSecureCoding. + */ +static NSString *const kEmailVerifiedCodingKey = @"emailVerified"; + +/** @var kDisplayNameCodingKey + @brief The key used to encode the displayName property for NSSecureCoding. + */ +static NSString *const kDisplayNameCodingKey = @"displayName"; + +/** @var kPhotoURLCodingKey + @brief The key used to encode the photoURL property for NSSecureCoding. + */ +static NSString *const kPhotoURLCodingKey = @"photoURL"; + +/** @var kProviderDataKey + @brief The key used to encode the providerData instance variable for NSSecureCoding. + */ +static NSString *const kProviderDataKey = @"providerData"; + +/** @var kAPIKeyCodingKey + @brief The key used to encode the APIKey instance variable for NSSecureCoding. + */ +static NSString *const kAPIKeyCodingKey = @"APIKey"; + +/** @var kTokenServiceCodingKey + @brief The key used to encode the tokenService instance variable for NSSecureCoding. + */ +static NSString *const kTokenServiceCodingKey = @"tokenService"; + +/** @var kMetadataCodingKey + @brief The key used to encode the metadata instance variable for NSSecureCoding. + */ +static NSString *const kMetadataCodingKey = @"metadata"; + +/** @var kMissingUsersErrorMessage + @brief The error message when there is no users array in the getAccountInfo response. + */ +static NSString *const kMissingUsersErrorMessage = @"users"; + +/** @typedef CallbackWithError + @brief The type for a callback block that only takes an error parameter. + */ +typedef void (^CallbackWithError)(NSError *_Nullable); + +/** @typedef CallbackWithUserAndError + @brief The type for a callback block that takes a user parameter and an error parameter. + */ +typedef void (^CallbackWithUserAndError)(FIRUser *_Nullable, NSError *_Nullable); + +/** @typedef CallbackWithUserAndError + @brief The type for a callback block that takes a user parameter and an error parameter. + */ +typedef void (^CallbackWithAuthDataResultAndError)(FIRAuthDataResult *_Nullable, + NSError *_Nullable); + +/** @var kMissingPasswordReason + @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown. + @remarks This error message will be localized in the future. + */ +static NSString *const kMissingPasswordReason = @"Missing Password"; + +/** @fn callInMainThreadWithError + @brief Calls a callback in main thread with error. + @param callback The callback to be called in main thread. + @param error The error to pass to callback. + */ +static void callInMainThreadWithError(_Nullable CallbackWithError callback, + NSError *_Nullable error) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(error); + }); + } +} + +/** @fn callInMainThreadWithUserAndError + @brief Calls a callback in main thread with user and error. + @param callback The callback to be called in main thread. + @param user The user to pass to callback if there is no error. + @param error The error to pass to callback. + */ +static void callInMainThreadWithUserAndError(_Nullable CallbackWithUserAndError callback, + FIRUser *_Nonnull user, + NSError *_Nullable error) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(error ? nil : user, error); + }); + } +} + +/** @fn callInMainThreadWithUserAndError + @brief Calls a callback in main thread with user and error. + @param callback The callback to be called in main thread. + @param result The result to pass to callback if there is no error. + @param error The error to pass to callback. + */ +static void callInMainThreadWithAuthDataResultAndError( + _Nullable CallbackWithAuthDataResultAndError callback, + FIRAuthDataResult *_Nullable result, + NSError *_Nullable error) { + if (callback) { + dispatch_async(dispatch_get_main_queue(), ^{ + callback(result, error); + }); + } +} + +@interface FIRUserProfileChangeRequest () + +/** @fn initWithUser: + @brief Designated initializer. + @param user The user for which we are updating profile information. + */ +- (nullable instancetype)initWithUser:(FIRUser *)user NS_DESIGNATED_INITIALIZER; + +@end + +@interface FIRUser () + +/** @property anonymous + @brief Whether the current user is anonymous. + */ +@property(nonatomic, readwrite) BOOL anonymous; + +@end + +@implementation FIRUser { + /** @var _hasEmailPasswordCredential + @brief Whether or not the user can be authenticated by using Firebase email and password. + */ + BOOL _hasEmailPasswordCredential; + + /** @var _providerData + @brief Provider specific user data. + */ + NSDictionary *_providerData; + + /** @var _taskQueue + @brief Used to serialize the update profile calls. + */ + FIRAuthSerialTaskQueue *_taskQueue; + + /** @var _tokenService + @brief A secure token service associated with this user. For performing token exchanges and + refreshing access tokens. + */ + FIRSecureTokenService *_tokenService; +} + +#pragma mark - Properties + +// Explicitly @synthesize because these properties are defined in FIRUserInfo protocol. +@synthesize uid = _userID; +@synthesize displayName = _displayName; +@synthesize photoURL = _photoURL; +@synthesize email = _email; +@synthesize phoneNumber = _phoneNumber; + +#pragma mark - + ++ (void)retrieveUserWithAuth:(FIRAuth *)auth + accessToken:(nullable NSString *)accessToken + accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate + refreshToken:(nullable NSString *)refreshToken + anonymous:(BOOL)anonymous + callback:(FIRRetrieveUserCallback)callback { + FIRSecureTokenService *tokenService = + [[FIRSecureTokenService alloc] initWithRequestConfiguration:auth.requestConfiguration + accessToken:accessToken + accessTokenExpirationDate:accessTokenExpirationDate + refreshToken:refreshToken]; + FIRUser *user = [[self alloc] initWithTokenService:tokenService]; + user.auth = auth; + user.requestConfiguration = auth.requestConfiguration; + [user internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) { + if (error) { + callback(nil, error); + return; + } + FIRGetAccountInfoRequest *getAccountInfoRequest = + [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken + requestConfiguration:auth.requestConfiguration]; + [FIRAuthBackend getAccountInfo:getAccountInfoRequest + callback:^(FIRGetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + // No need to sign out user here for errors because the user hasn't been signed in yet. + callback(nil, error); + return; + } + user.anonymous = anonymous; + [user updateWithGetAccountInfoResponse:response]; + callback(user, nil); + }]; + }]; +} + +- (instancetype)initWithTokenService:(FIRSecureTokenService *)tokenService { + self = [super init]; + if (self) { + _providerData = @{ }; + _taskQueue = [[FIRAuthSerialTaskQueue alloc] init]; + _tokenService = tokenService; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *userID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserIDCodingKey]; + BOOL hasAnonymousKey = [aDecoder containsValueForKey:kAnonymousCodingKey]; + BOOL anonymous = [aDecoder decodeBoolForKey:kAnonymousCodingKey]; + BOOL hasEmailPasswordCredential = + [aDecoder decodeBoolForKey:kHasEmailPasswordCredentialCodingKey]; + NSString *displayName = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kDisplayNameCodingKey]; + NSURL *photoURL = + [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPhotoURLCodingKey]; + NSString *email = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kEmailCodingKey]; + NSString *phoneNumber = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kPhoneNumberCodingKey]; + BOOL emailVerified = [aDecoder decodeBoolForKey:kEmailVerifiedCodingKey]; + NSSet *providerDataClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class], + [FIRUserInfoImpl class] + ]]; + NSDictionary *providerData = + [aDecoder decodeObjectOfClasses:providerDataClasses forKey:kProviderDataKey]; + FIRSecureTokenService *tokenService = + [aDecoder decodeObjectOfClass:[FIRSecureTokenService class] forKey:kTokenServiceCodingKey]; + FIRUserMetadata *metadata = + [aDecoder decodeObjectOfClass:[FIRUserMetadata class] forKey:kMetadataCodingKey]; + NSString *APIKey = + [aDecoder decodeObjectOfClass:[FIRUserMetadata class] forKey:kAPIKeyCodingKey]; + if (!userID || !tokenService) { + return nil; + } + self = [self initWithTokenService:tokenService]; + if (self) { + _userID = userID; + // Previous version of this code didn't save 'anonymous' bit directly but deduced it from + // 'hasEmailPasswordCredential' and 'providerData' instead, so here backward compatibility is + // provided to read old format data. + _anonymous = hasAnonymousKey ? anonymous : (!hasEmailPasswordCredential && !providerData.count); + _hasEmailPasswordCredential = hasEmailPasswordCredential; + _email = email; + _emailVerified = emailVerified; + _displayName = displayName; + _photoURL = photoURL; + _providerData = providerData; + _phoneNumber = phoneNumber; + _metadata = metadata ?: [[FIRUserMetadata alloc] initWithCreationDate:nil lastSignInDate:nil]; + _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_userID forKey:kUserIDCodingKey]; + [aCoder encodeBool:self.anonymous forKey:kAnonymousCodingKey]; + [aCoder encodeBool:_hasEmailPasswordCredential forKey:kHasEmailPasswordCredentialCodingKey]; + [aCoder encodeObject:_providerData forKey:kProviderDataKey]; + [aCoder encodeObject:_email forKey:kEmailCodingKey]; + [aCoder encodeObject:_phoneNumber forKey:kPhoneNumberCodingKey]; + [aCoder encodeBool:_emailVerified forKey:kEmailVerifiedCodingKey]; + [aCoder encodeObject:_photoURL forKey:kPhotoURLCodingKey]; + [aCoder encodeObject:_displayName forKey:kDisplayNameCodingKey]; + [aCoder encodeObject:_metadata forKey:kMetadataCodingKey]; + [aCoder encodeObject:_auth.requestConfiguration.APIKey forKey:kAPIKeyCodingKey]; + [aCoder encodeObject:_tokenService forKey:kTokenServiceCodingKey]; +} + +#pragma mark - + +- (void)setAuth:(nullable FIRAuth *)auth { + _auth = auth; + _tokenService.requestConfiguration = auth.requestConfiguration; +} + +- (NSString *)providerID { + return @"Firebase"; +} + +- (NSArray> *)providerData { + return _providerData.allValues; +} + +/** @fn getAccountInfoRefreshingCache: + @brief Gets the users's account data from the server, updating our local values. + @param callback Invoked when the request to getAccountInfo has completed, or when an error has + been detected. Invoked asynchronously on the auth global work queue in the future. + */ +- (void)getAccountInfoRefreshingCache:(void(^)(FIRGetAccountInfoResponseUser *_Nullable user, + NSError *_Nullable error))callback { + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) { + if (error) { + callback(nil, error); + return; + } + FIRGetAccountInfoRequest *getAccountInfoRequest = + [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken + requestConfiguration:self->_auth.requestConfiguration]; + [FIRAuthBackend getAccountInfo:getAccountInfoRequest + callback:^(FIRGetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + callback(nil, error); + return; + } + [self updateWithGetAccountInfoResponse:response]; + if (![self updateKeychain:&error]) { + callback(nil, error); + return; + } + callback(response.users.firstObject, nil); + }]; + }]; +} + +- (void)updateWithGetAccountInfoResponse:(FIRGetAccountInfoResponse *)response { + FIRGetAccountInfoResponseUser *user = response.users.firstObject; + _userID = user.localID; + _email = user.email; + _emailVerified = user.emailVerified; + _displayName = user.displayName; + _photoURL = user.photoURL; + _phoneNumber = user.phoneNumber; + _hasEmailPasswordCredential = user.passwordHash.length > 0; + _metadata = + [[FIRUserMetadata alloc]initWithCreationDate:user.creationDate + lastSignInDate:user.lastLoginDate]; + NSMutableDictionary *providerData = + [NSMutableDictionary dictionary]; + for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in user.providerUserInfo) { + FIRUserInfoImpl *userInfo = + [FIRUserInfoImpl userInfoWithGetAccountInfoResponseProviderUserInfo:providerUserInfo]; + if (userInfo) { + providerData[providerUserInfo.providerID] = userInfo; + } + } + _providerData = [providerData copy]; +} + +/** @fn executeUserUpdateWithChanges:callback: + @brief Performs a setAccountInfo request by mutating the results of a getAccountInfo response, + atomically in regards to other calls to this method. + @param changeBlock A block responsible for mutating a template @c FIRSetAccountInfoRequest + @param callback A block to invoke when the change is complete. Invoked asynchronously on the + auth global work queue in the future. + */ +- (void)executeUserUpdateWithChanges:(void(^)(FIRGetAccountInfoResponseUser *, + FIRSetAccountInfoRequest *))changeBlock + callback:(nonnull FIRUserProfileChangeCallback)callback { + [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) { + [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user, + NSError *_Nullable error) { + if (error) { + complete(); + callback(error); + return; + } + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + complete(); + callback(error); + return; + } + FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration; + // Mutate setAccountInfoRequest in block: + FIRSetAccountInfoRequest *setAccountInfoRequest = + [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:configuration]; + setAccountInfoRequest.accessToken = accessToken; + changeBlock(user, setAccountInfoRequest); + // Execute request: + [FIRAuthBackend setAccountInfo:setAccountInfoRequest + callback:^(FIRSetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + complete(); + callback(error); + return; + } + if (response.IDToken && response.refreshToken) { + FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc] + initWithRequestConfiguration:configuration + accessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken]; + [self setTokenService:tokenService callback:^(NSError *_Nullable error) { + complete(); + callback(error); + }]; + return; + } + complete(); + callback(nil); + }]; + }]; + }]; + }]; +} + +/** @fn updateKeychain: + @brief Updates the keychain for user token or info changes. + @param error The error if NO is returned. + @return Whether the operation is successful. + */ +- (BOOL)updateKeychain:(NSError *_Nullable *_Nullable)error { + return [_auth updateKeychainWithUser:self error:error]; +} + +/** @fn setTokenService:callback: + @brief Sets a new token service for the @c FIRUser instance. + @param tokenService The new token service object. + @param callback The block to be called in the global auth working queue once finished. + @remarks The method makes sure the token service has access and refresh token and the new tokens + are saved in the keychain before calling back. + */ +- (void)setTokenService:(FIRSecureTokenService *)tokenService + callback:(nonnull CallbackWithError)callback { + [tokenService fetchAccessTokenForcingRefresh:NO + callback:^(NSString *_Nullable token, + NSError *_Nullable error, + BOOL tokenUpdated) { + if (error) { + callback(error); + return; + } + self->_tokenService = tokenService; + if (![self updateKeychain:&error]) { + callback(error); + return; + } + callback(nil); + }]; +} + +#pragma mark - + +/** @fn updateEmail:password:callback: + @brief Updates email address and/or password for the current user. + @remarks May fail if there is already an email/password-based account for the same email + address. + @param email The email address for the user, if to be updated. + @param password The new password for the user, if to be updated. + @param callback The block called when the user profile change has finished. Invoked + asynchronously on the auth global work queue in the future. + @remarks May fail with a @c FIRAuthErrorCodeRequiresRecentLogin error code. + Call @c reauthentateWithCredential:completion: beforehand to avoid this error case. + */ +- (void)updateEmail:(nullable NSString *)email + password:(nullable NSString *)password + callback:(nonnull FIRUserProfileChangeCallback)callback { + if (password && ![password length]) { + callback([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]); + return; + } + BOOL hadEmailPasswordCredential = _hasEmailPasswordCredential; + [self executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user, + FIRSetAccountInfoRequest *request) { + if (email) { + request.email = email; + } + if (password) { + request.password = password; + } + } + callback:^(NSError *error) { + if (error) { + callback(error); + return; + } + if (email) { + self->_email = [email copy]; + } + if (self->_email) { + if (!hadEmailPasswordCredential) { + // The list of providers need to be updated for the newly added email-password provider. + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + callback(error); + return; + } + FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration; + FIRGetAccountInfoRequest *getAccountInfoRequest = + [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken + requestConfiguration:requestConfiguration]; + [FIRAuthBackend getAccountInfo:getAccountInfoRequest + callback:^(FIRGetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + callback(error); + return; + } + for (FIRGetAccountInfoResponseUser *userAccountInfo in response.users) { + // Set the account to non-anonymous if there are any providers, even if + // they're not email/password ones. + if (userAccountInfo.providerUserInfo.count > 0) { + self.anonymous = NO; + } + for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in + userAccountInfo.providerUserInfo) { + if ([providerUserInfo.providerID isEqualToString:FIREmailAuthProviderID]) { + self->_hasEmailPasswordCredential = YES; + break; + } + } + } + [self updateWithGetAccountInfoResponse:response]; + if (![self updateKeychain:&error]) { + callback(error); + return; + } + callback(nil); + }]; + }]; + return; + } + } + if (![self updateKeychain:&error]) { + callback(error); + return; + } + callback(nil); + }]; +} + +- (void)updateEmail:(NSString *)email completion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self updateEmail:email password:nil callback:^(NSError *_Nullable error) { + callInMainThreadWithError(completion, error); + }]; + }); +} + +- (void)updatePassword:(NSString *)password + completion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self updateEmail:nil password:password callback:^(NSError *_Nullable error){ + callInMainThreadWithError(completion, error); + }]; + }); +} + +#if TARGET_OS_IOS +/** @fn internalUpdateOrLinkPhoneNumberCredential:completion: + @brief Updates the phone number for the user. On success, the cached user profile data is + updated. + + @param phoneAuthCredential The new phone number credential corresponding to the phone number + to be added to the Firebase account, if a phone number is already linked to the account this + new phone number will replace it. + @param isLinkOperation Boolean value indicating whether or not this is a link operation. + @param completion Optionally; the block invoked when the user profile change has finished. + Invoked asynchronously on the global work queue in the future. + */ +- (void)internalUpdateOrLinkPhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential + isLinkOperation:(BOOL)isLinkOperation + completion:(FIRUserProfileChangeCallback)completion { + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + completion(error); + return; + } + FIRAuthOperationType operation = + isLinkOperation ? FIRAuthOperationTypeLink : FIRAuthOperationTypeUpdate; + FIRVerifyPhoneNumberRequest *request = [[FIRVerifyPhoneNumberRequest alloc] + initWithVerificationID:phoneAuthCredential.verificationID + verificationCode:phoneAuthCredential.verificationCode + operation:operation + requestConfiguration:self->_auth.requestConfiguration]; + request.accessToken = accessToken; + [FIRAuthBackend verifyPhoneNumber:request + callback:^(FIRVerifyPhoneNumberResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + completion(error); + return; + } + // Get account info to update cached user info. + [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + completion(error); + return; + } + self.anonymous = NO; + if (![self updateKeychain:&error]) { + completion(error); + return; + } + completion(nil); + }]; + }]; + }]; +} + +- (void)updatePhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential + completion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential + isLinkOperation:NO + completion:^(NSError *_Nullable error) { + callInMainThreadWithError(completion, error); + }]; + }); +} +#endif + +- (FIRUserProfileChangeRequest *)profileChangeRequest { + __block FIRUserProfileChangeRequest *result; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = [[FIRUserProfileChangeRequest alloc] initWithUser:self]; + }); + return result; +} + +- (void)setDisplayName:(NSString *)displayName { + _displayName = [displayName copy]; +} + +- (void)setPhotoURL:(NSURL *)photoURL { + _photoURL = [photoURL copy]; +} + +- (NSString *)rawAccessToken { + return _tokenService.rawAccessToken; +} + +- (NSDate *)accessTokenExpirationDate { + return _tokenService.accessTokenExpirationDate; +} + +#pragma mark - + +- (void)reloadWithCompletion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user, + NSError *_Nullable error) { + callInMainThreadWithError(completion, error); + }]; + }); +} + +#pragma mark - + +- (void)reauthenticateWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRUserProfileChangeCallback)completion { + FIRAuthDataResultCallback callback = ^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + completion(error); + }; + [self reauthenticateAndRetrieveDataWithCredential:credential completion:callback]; +} + +- (void) + reauthenticateAndRetrieveDataWithCredential:(FIRAuthCredential *) credential + completion:(nullable FIRAuthDataResultCallback) completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self->_auth internalSignInAndRetrieveDataWithCredential:credential + isReauthentication:YES + callback:^(FIRAuthDataResult *_Nullable + authResult, + NSError *_Nullable error) { + if (error) { + // If "user not found" error returned by backend, translate to user mismatch error which is + // more accurate. + if (error.code == FIRAuthErrorCodeUserNotFound) { + error = [FIRAuthErrorUtils userMismatchError]; + } + callInMainThreadWithAuthDataResultAndError(completion, authResult, error); + return; + } + if (![authResult.user.uid isEqual:[self->_auth getUserID]]) { + callInMainThreadWithAuthDataResultAndError(completion, authResult, + [FIRAuthErrorUtils userMismatchError]); + return; + } + // Successful reauthenticate + [self setTokenService:authResult.user->_tokenService callback:^(NSError *_Nullable error) { + callInMainThreadWithAuthDataResultAndError(completion, authResult, error); + }]; + }]; + }); +} + +- (nullable NSString *)refreshToken { + __block NSString *result; + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + result = self->_tokenService.refreshToken; + }); + return result; +} + +- (void)getIDTokenWithCompletion:(nullable FIRAuthTokenCallback)completion { + // |getIDTokenForcingRefresh:completion:| is also a public API so there is no need to dispatch to + // global work queue here. + [self getIDTokenForcingRefresh:NO completion:completion]; +} + +- (void)getIDTokenForcingRefresh:(BOOL)forceRefresh + completion:(nullable FIRAuthTokenCallback)completion { + [self getIDTokenResultForcingRefresh:forceRefresh + completion:^(FIRAuthTokenResult *_Nullable tokenResult, + NSError *_Nullable error) { + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(tokenResult.token, error); + }); + } + }]; +} + +- (void)getIDTokenResultWithCompletion:(nullable FIRAuthTokenResultCallback)completion { + [self getIDTokenResultForcingRefresh:NO + completion:^(FIRAuthTokenResult *_Nullable tokenResult, + NSError *_Nullable error) { + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(tokenResult, error); + }); + } + }]; +} + +- (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh + completion:(nullable FIRAuthTokenResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self internalGetTokenForcingRefresh:forceRefresh + callback:^(NSString *_Nullable token, NSError *_Nullable error) { + FIRAuthTokenResult *tokenResult; + if (token) { + tokenResult = [self parseIDToken:token error:&error]; + } + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(tokenResult, error); + }); + } + }]; + }); +} + +/** @fn parseIDToken:error: + @brief Parses the provided IDToken and returns an instance of FIRAuthTokenResult containing + claims obtained from the IDToken. + + @param token The raw text of the Firebase IDToken encoded in base64. + @param error An out parameter which would contain any error that occurs during parsing. + @return An instance of FIRAuthTokenResult containing claims obtained from the IDToken. + + @remarks IDToken returned from the backend in some cases is of a length that is not a multiple + of 4. In these cases this function pads the token with as many "=" characters as needed and + then attempts to parse the token. If the token cannot be parsed an error is returned via the + "error" out parameter. + */ +- (nullable FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error { + // Though this is an internal method, errors returned here are surfaced in user-visible + // callbacks. + if (error) { + *error = nil; + } + NSArray *tokenStringArray = [token componentsSeparatedByString:@"."]; + + // The JWT should have three parts, though we only use the second in this method. + if (tokenStringArray.count != 3) { + if (error) { + *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil]; + } + return nil; + } + + // The token payload is always the second index of the array. + NSString *idToken = tokenStringArray[1]; + + // Convert the base64URL encoded string to a base64 encoded string. + // Replace "_" with "/" + NSMutableString *tokenPayload = + [[idToken stringByReplacingOccurrencesOfString:@"_" withString:@"/"] mutableCopy]; + + // Replace "-" with "+" + [tokenPayload replaceOccurrencesOfString:@"-" + withString:@"+" + options:kNilOptions + range:NSMakeRange(0, tokenPayload.length)]; + + // Pad the token payload with "=" signs if the payload's length is not a multiple of 4. + while ((tokenPayload.length % 4) != 0) { + [tokenPayload appendFormat:@"="]; + } + NSData *decodedTokenPayloadData = + [[NSData alloc] initWithBase64EncodedString:tokenPayload + options:NSDataBase64DecodingIgnoreUnknownCharacters]; + if (!decodedTokenPayloadData) { + if (error) { + *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil]; + } + return nil; + } + NSError *jsonError = nil; + NSJSONReadingOptions options = NSJSONReadingMutableContainers|NSJSONReadingAllowFragments; + NSDictionary *tokenPayloadDictionary = + [NSJSONSerialization JSONObjectWithData:decodedTokenPayloadData + options:options + error:&jsonError]; + if (jsonError != nil) { + if (error) { + *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:jsonError]; + } + return nil; + } + + if (!tokenPayloadDictionary) { + if (error) { + *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil]; + } + return nil; + } + + // These are dates since 00:00:00 January 1 1970, as described by the Terminology section in + // the JWT spec. https://tools.ietf.org/html/rfc7519 + NSDate *expDate = + [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"exp"] doubleValue]]; + NSDate *authDate = + [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"auth_time"] doubleValue]]; + NSDate *issuedDate = + [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"iat"] doubleValue]]; + FIRAuthTokenResult *result = + [[FIRAuthTokenResult alloc] initWithToken:token + expirationDate:expDate + authDate:authDate + issuedAtDate:issuedDate + signInProvider:tokenPayloadDictionary[@"sign_in_provider"] + claims:tokenPayloadDictionary]; + return result; +} + +/** @fn internalGetTokenForcingRefresh:callback: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + @param callback The block to invoke when the token is available. Invoked asynchronously on the + global work thread in the future. + */ +- (void)internalGetTokenWithCallback:(nonnull FIRAuthTokenCallback)callback { + [self internalGetTokenForcingRefresh:NO callback:callback]; +} + +- (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh + callback:(nonnull FIRAuthTokenCallback)callback { + [_tokenService fetchAccessTokenForcingRefresh:forceRefresh + callback:^(NSString *_Nullable token, + NSError *_Nullable error, + BOOL tokenUpdated) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + callback(nil, error); + return; + } + if (tokenUpdated) { + if (![self updateKeychain:&error]) { + callback(nil, error); + return; + } + } + callback(token, nil); + }]; +} + +- (void)linkWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthResultCallback)completion { + FIRAuthDataResultCallback callback = ^(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) { + completion(authResult.user, error); + }; + [self linkAndRetrieveDataWithCredential:credential completion:callback]; +} + +- (void)linkAndRetrieveDataWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthDataResultCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + if (self->_providerData[credential.provider]) { + callInMainThreadWithAuthDataResultAndError(completion, + nil, + [FIRAuthErrorUtils providerAlreadyLinkedError]); + return; + } + FIRAuthDataResult *result = + [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:nil]; + if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) { + if (self->_hasEmailPasswordCredential) { + callInMainThreadWithAuthDataResultAndError(completion, + nil, + [FIRAuthErrorUtils providerAlreadyLinkedError]); + return; + } + FIREmailPasswordAuthCredential *emailPasswordCredential = + (FIREmailPasswordAuthCredential *)credential; + [self updateEmail:emailPasswordCredential.email + password:emailPasswordCredential.password + callback:^(NSError *error) { + if (error) { + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + } else { + callInMainThreadWithAuthDataResultAndError(completion, result, nil); + } + }]; + return; + } + + if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) { + FIRGameCenterAuthCredential *gameCenterCredential = (FIRGameCenterAuthCredential *)credential; + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration; + FIRSignInWithGameCenterRequest *gameCenterRequest = + [[FIRSignInWithGameCenterRequest alloc] initWithPlayerID:gameCenterCredential.playerID + publicKeyURL:gameCenterCredential.publicKeyURL + signature:gameCenterCredential.signature + salt:gameCenterCredential.salt + timestamp:gameCenterCredential.timestamp + displayName:gameCenterCredential.displayName + requestConfiguration:requestConfiguration]; + gameCenterRequest.accessToken = accessToken; + + [FIRAuthBackend signInWithGameCenter:gameCenterRequest + callback:^(FIRSignInWithGameCenterResponse *_Nullable response, + NSError *_Nullable error) { + if (error){ + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + } else { + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + return; + } + + FIRGetAccountInfoRequest *getAccountInfoRequest = + [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken + requestConfiguration:requestConfiguration]; + [FIRAuthBackend getAccountInfo:getAccountInfoRequest + callback:^(FIRGetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + return; + } + self.anonymous = NO; + [self updateWithGetAccountInfoResponse:response]; + if (![self updateKeychain:&error]) { + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + return; + } + callInMainThreadWithAuthDataResultAndError(completion, result, nil); + }]; + }]; + } + }]; + }]; + return; + } + + #if TARGET_OS_IOS + if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) { + FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential; + [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential + isLinkOperation:YES + completion:^(NSError *_Nullable error) { + if (error){ + callInMainThreadWithAuthDataResultAndError(completion, nil, error); + } else { + callInMainThreadWithAuthDataResultAndError(completion, result, nil); + } + }]; + return; + } + #endif + + [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) { + CallbackWithAuthDataResultAndError completeWithError = + ^(FIRAuthDataResult *result, NSError *error) { + complete(); + callInMainThreadWithAuthDataResultAndError(completion, result, error); + }; + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + completeWithError(nil, error); + return; + } + FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration; + FIRVerifyAssertionRequest *request = + [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider + requestConfiguration:requestConfiguration]; + [credential prepareVerifyAssertionRequest:request]; + request.accessToken = accessToken; + [FIRAuthBackend verifyAssertion:request + callback:^(FIRVerifyAssertionResponse *response, NSError *error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + completeWithError(nil, error); + return; + } + FIRAdditionalUserInfo *additionalUserInfo = + [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response]; + FIRAuthDataResult *result = + [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:additionalUserInfo]; + // Update the new token and refresh user info again. + self->_tokenService = [[FIRSecureTokenService alloc] + initWithRequestConfiguration:requestConfiguration + accessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken]; + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + completeWithError(nil, error); + return; + } + FIRGetAccountInfoRequest *getAccountInfoRequest = + [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken + requestConfiguration:requestConfiguration]; + [FIRAuthBackend getAccountInfo:getAccountInfoRequest + callback:^(FIRGetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + completeWithError(nil, error); + return; + } + self.anonymous = NO; + [self updateWithGetAccountInfoResponse:response]; + if (![self updateKeychain:&error]) { + completeWithError(nil, error); + return; + } + completeWithError(result, nil); + }]; + }]; + }]; + }]; + }]; + }); +} + +- (void)unlinkFromProvider:(NSString *)provider + completion:(nullable FIRAuthResultCallback)completion { + [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) { + CallbackWithError completeAndCallbackWithError = ^(NSError *error) { + complete(); + callInMainThreadWithUserAndError(completion, self, error); + }; + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + completeAndCallbackWithError(error); + return; + } + FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration; + FIRSetAccountInfoRequest *setAccountInfoRequest = + [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration]; + setAccountInfoRequest.accessToken = accessToken; + BOOL isEmailPasswordProvider = [provider isEqualToString:FIREmailAuthProviderID]; + if (isEmailPasswordProvider) { + if (!self->_hasEmailPasswordCredential) { + completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]); + return; + } + setAccountInfoRequest.deleteAttributes = @[ FIRSetAccountInfoUserAttributePassword ]; + } else { + if (!self->_providerData[provider]) { + completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]); + return; + } + setAccountInfoRequest.deleteProviders = @[ provider ]; + } + [FIRAuthBackend setAccountInfo:setAccountInfoRequest + callback:^(FIRSetAccountInfoResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + [self signOutIfTokenIsInvalidWithError:error]; + completeAndCallbackWithError(error); + return; + } + if (isEmailPasswordProvider) { + self->_hasEmailPasswordCredential = NO; + } else { + // We can't just use the provider info objects in FIRSetAcccountInfoResponse because they + // don't have localID and email fields. Remove the specific provider manually. + NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy]; + [mutableProviderData removeObjectForKey:provider]; + self->_providerData = [mutableProviderData copy]; + + #if TARGET_OS_IOS + // After successfully unlinking a phone auth provider, remove the phone number from the + // cached user info. + if ([provider isEqualToString:FIRPhoneAuthProviderID]) { + self->_phoneNumber = nil; + } + #endif + } + if (response.IDToken && response.refreshToken) { + FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc] + initWithRequestConfiguration:requestConfiguration + accessToken:response.IDToken + accessTokenExpirationDate:response.approximateExpirationDate + refreshToken:response.refreshToken]; + [self setTokenService:tokenService callback:^(NSError *_Nullable error) { + completeAndCallbackWithError(error); + }]; + return; + } + if (![self updateKeychain:&error]) { + completeAndCallbackWithError(error); + return; + } + completeAndCallbackWithError(nil); + }]; + }]; + }]; +} + +- (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion { + [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion]; +} + +- (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendEmailVerificationCallback) + completion { + [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings + completion:completion]; +} + +/** @fn sendEmailVerificationWithNullableActionCodeSettings:completion: + @brief Initiates email verification for the user. + + @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings + related to the handling action codes. + */ +- (void)sendEmailVerificationWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *) + actionCodeSettings + completion: + (nullable FIRSendEmailVerificationCallback) + completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + callInMainThreadWithError(completion, error); + return; + } + FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration; + FIRGetOOBConfirmationCodeRequest *request = + [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken + actionCodeSettings:actionCodeSettings + requestConfiguration:configuration]; + [FIRAuthBackend getOOBConfirmationCode:request + callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable + response, + NSError *_Nullable error) { + [self signOutIfTokenIsInvalidWithError:error]; + callInMainThreadWithError(completion, error); + }]; + }]; + }); +} + +- (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_async(FIRAuthGlobalWorkQueue(), ^{ + [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, + NSError *_Nullable error) { + if (error) { + callInMainThreadWithError(completion, error); + return; + } + FIRDeleteAccountRequest *deleteUserRequest = + [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID + accessToken:accessToken + requestConfiguration:self->_auth.requestConfiguration]; + [FIRAuthBackend deleteAccount:deleteUserRequest callback:^(NSError *_Nullable error) { + if (error) { + callInMainThreadWithError(completion, error); + return; + } + if (![self->_auth signOutByForceWithUserID:self->_userID error:&error]) { + callInMainThreadWithError(completion, error); + return; + } + callInMainThreadWithError(completion, error); + }]; + }]; + }); +} + +/** @fn signOutIfTokenIsInvalidWithError: + @brief Signs out this user if the user or the token is invalid. + @param error The error from the server. + */ +- (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error { + NSInteger errorCode = error.code; + if (errorCode == FIRAuthErrorCodeUserNotFound || + errorCode == FIRAuthErrorCodeUserDisabled || + errorCode == FIRAuthErrorCodeInvalidUserToken || + errorCode == FIRAuthErrorCodeUserTokenExpired) { + FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016", + @"Invalid user token detected, user is automatically signed out."); + [_auth signOutByForceWithUserID:_userID error:NULL]; + } +} + +@end + +@implementation FIRUserProfileChangeRequest { + /** @var _user + @brief The user associated with the change request. + */ + FIRUser *_user; + + /** @var _displayName + @brief The display name value to set if @c _displayNameSet is YES. + */ + NSString *_displayName; + + /** @var _displayNameSet + @brief Indicates the display name should be part of the change request. + */ + BOOL _displayNameSet; + + /** @var _photoURL + @brief The photo URL value to set if @c _displayNameSet is YES. + */ + NSURL *_photoURL; + + /** @var _photoURLSet + @brief Indicates the photo URL should be part of the change request. + */ + BOOL _photoURLSet; + + /** @var _consumed + @brief Indicates the @c commitChangesWithCallback: method has already been invoked. + */ + BOOL _consumed; +} + +- (nullable instancetype)initWithUser:(FIRUser *)user { + self = [super init]; + if (self) { + _user = user; + } + return self; +} + +- (nullable NSString *)displayName { + return _displayName; +} + +- (void)setDisplayName:(nullable NSString *)displayName { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + if (self->_consumed) { + [NSException raise:NSInternalInconsistencyException + format:@"%@", + @"Invalid call to setDisplayName: after commitChangesWithCallback:."]; + return; + } + self->_displayNameSet = YES; + self->_displayName = [displayName copy]; + }); +} + +- (nullable NSURL *)photoURL { + return _photoURL; +} + +- (void)setPhotoURL:(nullable NSURL *)photoURL { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + if (self->_consumed) { + [NSException raise:NSInternalInconsistencyException + format:@"%@", + @"Invalid call to setPhotoURL: after commitChangesWithCallback:."]; + return; + } + self->_photoURLSet = YES; + self->_photoURL = [photoURL copy]; + }); +} + +/** @fn hasUpdates + @brief Indicates at least one field has a value which needs to be committed. + */ +- (BOOL)hasUpdates { + return _displayNameSet || _photoURLSet; +} + +- (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion { + dispatch_sync(FIRAuthGlobalWorkQueue(), ^{ + if (self->_consumed) { + [NSException raise:NSInternalInconsistencyException + format:@"%@", + @"commitChangesWithCallback: should only be called once."]; + return; + } + self->_consumed = YES; + // Return fast if there is nothing to update: + if (![self hasUpdates]) { + callInMainThreadWithError(completion, nil); + return; + } + NSString *displayName = [self->_displayName copy]; + BOOL displayNameWasSet = self->_displayNameSet; + NSURL *photoURL = [self->_photoURL copy]; + BOOL photoURLWasSet = self->_photoURLSet; + [self->_user executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user, + FIRSetAccountInfoRequest *request) { + if (photoURLWasSet) { + request.photoURL = photoURL; + } + if (displayNameWasSet) { + request.displayName = displayName; + } + } + callback:^(NSError *_Nullable error) { + if (error) { + callInMainThreadWithError(completion, error); + return; + } + if (displayNameWasSet) { + [self->_user setDisplayName:displayName]; + } + if (photoURLWasSet) { + [self->_user setPhotoURL:photoURL]; + } + if (![self->_user updateKeychain:&error]) { + callInMainThreadWithError(completion, error); + return; + } + callInMainThreadWithError(completion, nil); + }]; + }); +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.h new file mode 100644 index 0000000..0022a68 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.h @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRUserInfo.h" + +@class FIRGetAccountInfoResponseProviderUserInfo; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRUserInfoImpl : NSObject + +/** @fn userInfoWithGetAccountInfoResponseProviderUserInfo: + @brief A convenience factory method for constructing a @c FIRUserInfo instance from data + returned by the getAccountInfo endpoint. + @param providerUserInfo Data returned by the getAccountInfo endpoint. + @return A new instance of @c FIRUserInfo using data from the getAccountInfo endpoint. + */ ++ (nullable instancetype)userInfoWithGetAccountInfoResponseProviderUserInfo: + (FIRGetAccountInfoResponseProviderUserInfo *)providerUserInfo; + +/** @fn init + @brief This class should not be initialized manually. + @see FIRUser.providerData + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithProviderID:userID:displayName:photoURL:email: + @brief Designated initializer. + @param providerID The provider identifier. + @param userID The unique user ID for the user (the value of the @c uid field in the token.) + @param displayName The name of the user. + @param photoURL The URL of the user's profile photo. + @param email The user's email address. + @param phoneNumber The user's phone number. + */ +- (nullable instancetype)initWithProviderID:(NSString *)providerID + userID:(NSString *)userID + displayName:(nullable NSString *)displayName + photoURL:(nullable NSURL *)photoURL + email:(nullable NSString *)email + phoneNumber:(nullable NSString *)phoneNumber + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.m new file mode 100644 index 0000000..d172481 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserInfoImpl.m @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRUserInfoImpl.h" + +#import "FIRGetAccountInfoResponse.h" + +/** @var kProviderIDCodingKey + @brief The key used to encode the providerID property for NSSecureCoding. + */ +static NSString *const kProviderIDCodingKey = @"providerID"; + +/** @var kUserIDCodingKey + @brief The key used to encode the userID property for NSSecureCoding. + */ +static NSString *const kUserIDCodingKey = @"userID"; + +/** @var kDisplayNameCodingKey + @brief The key used to encode the displayName property for NSSecureCoding. + */ +static NSString *const kDisplayNameCodingKey = @"displayName"; + +/** @var kProfileURLCodingKey + @brief The key used to encode the profileURL property for NSSecureCoding. + */ +static NSString *const kProfileURLCodingKey = @"profileURL"; + +/** @var kPhotoURLCodingKey + @brief The key used to encode the photoURL property for NSSecureCoding. + */ +static NSString *const kPhotoURLCodingKey = @"photoURL"; + +/** @var kEmailCodingKey + @brief The key used to encode the email property for NSSecureCoding. + */ +static NSString *const kEmailCodingKey = @"email"; + +/** @var kPhoneNumberCodingKey + @brief The key used to encode the phoneNumber property for NSSecureCoding. + */ +static NSString *const kPhoneNumberCodingKey = @"phoneNumber"; + +@implementation FIRUserInfoImpl + +@synthesize providerID = _providerID; +@synthesize uid = _userID; +@synthesize displayName = _displayName; +@synthesize photoURL = _photoURL; +@synthesize email = _email; +@synthesize phoneNumber = _phoneNumber; + ++ (nullable instancetype)userInfoWithGetAccountInfoResponseProviderUserInfo: + (FIRGetAccountInfoResponseProviderUserInfo *)providerUserInfo { + return [[self alloc] initWithProviderID:providerUserInfo.providerID + userID:providerUserInfo.federatedID + displayName:providerUserInfo.displayName + photoURL:providerUserInfo.photoURL + email:providerUserInfo.email + phoneNumber:providerUserInfo.phoneNumber]; +} + +- (nullable instancetype)initWithProviderID:(NSString *)providerID + userID:(NSString *)userID + displayName:(nullable NSString *)displayName + photoURL:(nullable NSURL *)photoURL + email:(nullable NSString *)email + phoneNumber:(nullable NSString *)phoneNumber { + self = [super init]; + if (self) { + _providerID = [providerID copy]; + _userID = [userID copy]; + _displayName = [displayName copy]; + _photoURL = [photoURL copy]; + _email = [email copy]; + _phoneNumber = [phoneNumber copy]; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSString *providerID = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kProviderIDCodingKey]; + NSString *userID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserIDCodingKey]; + NSString *displayName = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kDisplayNameCodingKey]; + NSURL *photoURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPhotoURLCodingKey]; + NSString *email = [aDecoder decodeObjectOfClass:[NSString class] forKey:kEmailCodingKey]; + NSString *phoneNumber = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kPhoneNumberCodingKey]; + + return [self initWithProviderID:providerID + userID:userID + displayName:displayName + photoURL:photoURL + email:email + phoneNumber:phoneNumber]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_providerID forKey:kProviderIDCodingKey]; + [aCoder encodeObject:_userID forKey:kUserIDCodingKey]; + [aCoder encodeObject:_displayName forKey:kDisplayNameCodingKey]; + [aCoder encodeObject:_photoURL forKey:kPhotoURLCodingKey]; + [aCoder encodeObject:_email forKey:kEmailCodingKey]; + [aCoder encodeObject:_phoneNumber forKey:kPhoneNumberCodingKey]; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata.m new file mode 100644 index 0000000..8fe6509 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata.m @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRUserMetadata_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRUserMetadata + +/** @var kCreationDateCodingKey + @brief The key used to encode the creationDate property for NSSecureCoding. + */ +static NSString *const kCreationDateCodingKey = @"creationDate"; + +/** @var kLastSignInDateCodingKey + @brief The key used to encode the lastSignInDate property for NSSecureCoding. + */ +static NSString *const kLastSignInDateCodingKey = @"lastSignInDate"; + +- (instancetype)initWithCreationDate:(nullable NSDate *)creationDate + lastSignInDate:(nullable NSDate *)lastSignInDate { + self = [super init]; + if (self) { + _creationDate = [creationDate copy]; + _lastSignInDate = [lastSignInDate copy]; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSDate *creationDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kCreationDateCodingKey]; + NSDate *lastSignInDate = + [aDecoder decodeObjectOfClass:[NSDate class] forKey:kLastSignInDateCodingKey]; + return [self initWithCreationDate:creationDate lastSignInDate:lastSignInDate]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_creationDate forKey:kCreationDateCodingKey]; + [aCoder encodeObject:_lastSignInDate forKey:kLastSignInDateCodingKey]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata_Internal.h new file mode 100644 index 0000000..0b01a03 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUserMetadata_Internal.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRUserMetadata.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @extension FIRUserMetadata + @brief An internal class used to expose internal methods of FIRUserMetadata. + */ +@interface FIRUserMetadata () + +/** @fn initWithCreationDate:lastSignInDate: + @brief Designated initializer. + @param creationDate The creation date of the corresponding user. + @param lastSignInDate The date of the last recorded sign-in of the corresponding user. + */ +- (instancetype)initWithCreationDate:(nullable NSDate *)creationDate + lastSignInDate:(nullable NSDate *)lastSignInDate NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser_Internal.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser_Internal.h new file mode 100644 index 0000000..cf225b1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FIRUser_Internal.h @@ -0,0 +1,86 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRUser.h" + +@class FIRAuth; +@class FIRAuthRequestConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRRetrieveUserCallback + @brief The type of block that is invoked when the construction of a user succeeds or fails. + @param user The user that was constructed, or nil if user construction failed. + @param error The error which occurred, or nil if the request was successful. + */ +typedef void(^FIRRetrieveUserCallback)(FIRUser *_Nullable user, NSError *_Nullable error); + +@interface FIRUser () + +/** @property rawAccessToken + @brief The cached access token. + @remarks This method is specifically for providing the access token to internal clients during + deserialization and sign-in events, and should not be used to retrieve the access token by + anyone else. + */ +@property(nonatomic, copy, readonly) NSString *rawAccessToken; + +/** @property auth + @brief A weak reference to a FIRAuth instance associated with this instance. + */ +@property(nonatomic, weak) FIRAuth *auth; + +/** @property auth + @brief A strong reference to a requestConfiguration instance associated with this user instance. + */ +@property(nonatomic, strong) FIRAuthRequestConfiguration *requestConfiguration; + +/** @var accessTokenExpirationDate + @brief The expiration date of the cached access token. + */ +@property(nonatomic, copy, readonly) NSDate *accessTokenExpirationDate; + +/** @fn retrieveUserWithAuth:accessToken:accessTokenExpirationDate:refreshToken:callback: + @brief Constructs a user with Secure Token Service tokens, and obtains user details from the + getAccountInfo endpoint. + @param auth The associated FIRAuth instance. + @param accessToken The Secure Token Service access token. + @param accessTokenExpirationDate The approximate expiration date of the access token. + @param refreshToken The Secure Token Service refresh token. + @param anonymous Whether or not the user is anonymous. + @param callback A block which is invoked when the construction succeeds or fails. Invoked + asynchronously on the auth global work queue in the future. + */ ++ (void)retrieveUserWithAuth:(FIRAuth *)auth + accessToken:(nullable NSString *)accessToken + accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate + refreshToken:(nullable NSString *)refreshToken + anonymous:(BOOL)anonymous + callback:(FIRRetrieveUserCallback)callback; + +/** @fn internalGetTokenForcingRefresh:callback: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + @param forceRefresh Forces a token refresh. Useful if the token becomes invalid for some reason + other than an expiration. + @param callback The block to invoke when the token is available. Invoked asynchronously on the + global work thread in the future. + */ +- (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh + callback:(nonnull FIRAuthTokenCallback)callback; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FirebaseAuthVersion.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FirebaseAuthVersion.m new file mode 100644 index 0000000..c79d984 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/FirebaseAuthVersion.m @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FirebaseAuthVersion.h" + +// Convert the macro to a string +#define STR(x) STR_EXPAND(x) +#define STR_EXPAND(x) #x + +const double FirebaseAuthVersionNum = FIRAuth_MINOR_VERSION; + +const unsigned char *const FirebaseAuthVersionStr = + (const unsigned char *const)STR(FIRAuth_VERSION); diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.h new file mode 100644 index 0000000..114cbfd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.h @@ -0,0 +1,31 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface NSData (FIRBase64) + +/** @fn fir_base64URLEncodedStringWithOptions: + @brief Get a web safe base64 encoded string + @param options The base64 encoding options + */ +- (NSString *)fir_base64URLEncodedStringWithOptions:(NSDataBase64EncodingOptions)options; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.m new file mode 100644 index 0000000..173ec9b --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/NSData+FIRBase64.m @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "NSData+FIRBase64.h" + +@implementation NSData (FIRBase64) + +- (NSString *)fir_base64URLEncodedStringWithOptions:(NSDataBase64EncodingOptions)options { + NSString *string = [self base64EncodedStringWithOptions:options]; + string = [string stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; + string = [string stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; + string = [string stringByReplacingOccurrencesOfString:@"=" withString:@""]; + return string; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRActionCodeSettings.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRActionCodeSettings.h new file mode 100644 index 0000000..788e060 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRActionCodeSettings.h @@ -0,0 +1,89 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 FIRActionCodeSettings + @brief Used to set and retrieve settings related to handling action codes. + */ + NS_SWIFT_NAME(ActionCodeSettings) + @interface FIRActionCodeSettings : NSObject + + /** @property URL + @brief This URL represents the state/Continue URL in the form of a universal link. + @remarks This URL can should be contructed as a universal link that would either directly open + the app where the action code would be handled or continue to the app after the action code + is handled by Firebase. + */ + @property(nonatomic, copy, nullable) NSURL *URL; + + /** @property handleCodeInApp + @brief Indicates whether the action code link will open the app directly or after being + redirected from a Firebase owned web widget. + */ + @property(assign, nonatomic) BOOL handleCodeInApp; + + /** @property iOSBundleID + @brief The iOS bundle ID, if available. The default value is the current app's bundle ID. + */ + @property(copy, nonatomic, readonly, nullable) NSString *iOSBundleID; + + /** @property androidPackageName + @brief The Android package name, if available. + */ + @property(nonatomic, copy, readonly, nullable) NSString *androidPackageName; + + /** @property androidMinimumVersion + @brief The minimum Android version supported, if available. + */ + @property(nonatomic, copy, readonly, nullable) NSString *androidMinimumVersion; + + /** @property androidInstallIfNotAvailable + @brief Indicates whether the Android app should be installed on a device where it is not + available. + */ + @property(nonatomic, assign, readonly) BOOL androidInstallIfNotAvailable; + + /** @property dynamicLinkDomain + @brief The Firebase Dynamic Link domain used for out of band code flow. + */ + @property (copy, nonatomic, nullable) NSString *dynamicLinkDomain; + + /** @fn setIOSBundleID + @brief Sets the iOS bundle Id. + @param iOSBundleID The iOS bundle ID. + */ + - (void)setIOSBundleID:(NSString *)iOSBundleID; + + /** @fn setAndroidPackageName:installIfNotAvailable:minimumVersion: + @brief Sets the Android package name, the flag to indicate whether or not to install the app and + the minimum Android version supported. + @param androidPackageName The Android package name. + @param installIfNotAvailable Indicates whether or not the app should be installed if not + available. + @param minimumVersion The minimum version of Android supported. + @remarks If installIfNotAvailable is set to YES and the link is opened on an android device, it + will try to install the app if not already available. Otherwise the web URL is used. + */ + - (void)setAndroidPackageName:(NSString *)androidPackageName + installIfNotAvailable:(BOOL)installIfNotAvailable + minimumVersion:(nullable NSString *)minimumVersion; + + @end + + NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAdditionalUserInfo.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAdditionalUserInfo.h new file mode 100644 index 0000000..4f6947a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAdditionalUserInfo.h @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRVerifyAssertionResponse; + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAdditionalUserInfo + @brief Represents additional user data returned from an identity provider. + */ +NS_SWIFT_NAME(AdditionalUserInfo) +@interface FIRAdditionalUserInfo : NSObject + +/** @fn init + @brief This class should not be initialized manually. `FIRAdditionalUserInfo` can be retrieved + from from an instance of `FIRAuthDataResult`. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @property providerID + @brief The provider identifier. + */ +@property(nonatomic, readonly) NSString *providerID; + +/** @property profile + @brief Dictionary containing the additional IdP specific information. + */ +@property(nonatomic, readonly, nullable) NSDictionary *profile; + +/** @property username + @brief username The name of the user. + */ +@property(nonatomic, readonly, nullable) NSString *username; + +/** @property newUser + @brief Indicates whether or not the current user was signed in for the first time. + */ +@property(nonatomic, readonly, getter=isNewUser) BOOL newUser; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuth.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuth.h new file mode 100644 index 0000000..cfc59b1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuth.h @@ -0,0 +1,864 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +#import "FIRAuthErrors.h" + +#if TARGET_OS_IOS +#import "FIRAuthAPNSTokenType.h" +#endif + +@class FIRActionCodeSettings; +@class FIRApp; +@class FIRAuth; +@class FIRAuthCredential; +@class FIRAuthDataResult; +@class FIRAuthSettings; +@class FIRUser; +@protocol FIRAuthStateListener; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRUserUpdateCallback + @brief The type of block invoked when a request to update the current user is completed. + */ +typedef void (^FIRUserUpdateCallback)(NSError *_Nullable error) NS_SWIFT_NAME(UserUpdateCallback); + +/** @typedef FIRAuthStateDidChangeListenerHandle + @brief The type of handle returned by `FIRAuth.addAuthStateDidChangeListener:`. + */ +typedef id FIRAuthStateDidChangeListenerHandle + NS_SWIFT_NAME(AuthStateDidChangeListenerHandle); + +/** @typedef FIRAuthStateDidChangeListenerBlock + @brief The type of block which can be registered as a listener for auth state did change events. + + @param auth The FIRAuth object on which state changes occurred. + @param user Optionally; the current signed in user, if any. + */ +typedef void(^FIRAuthStateDidChangeListenerBlock)(FIRAuth *auth, FIRUser *_Nullable user) + NS_SWIFT_NAME(AuthStateDidChangeListenerBlock); + +/** @typedef FIRIDTokenDidChangeListenerHandle + @brief The type of handle returned by `FIRAuth.addIDTokenDidChangeListener:`. + */ +typedef id FIRIDTokenDidChangeListenerHandle + NS_SWIFT_NAME(IDTokenDidChangeListenerHandle); + +/** @typedef FIRIDTokenDidChangeListenerBlock + @brief The type of block which can be registered as a listener for ID token did change events. + + @param auth The FIRAuth object on which ID token changes occurred. + @param user Optionally; the current signed in user, if any. + */ +typedef void(^FIRIDTokenDidChangeListenerBlock)(FIRAuth *auth, FIRUser *_Nullable user) + NS_SWIFT_NAME(IDTokenDidChangeListenerBlock); + +/** @typedef FIRAuthDataResultCallback + @brief The type of block invoked when sign-in related events complete. + + @param authResult Optionally; Result of sign-in request containing both the user and + the additional user info associated with the user. + @param error Optionally; the error which occurred - or nil if the request was successful. + */ +typedef void (^FIRAuthDataResultCallback)(FIRAuthDataResult *_Nullable authResult, + NSError *_Nullable error) + NS_SWIFT_NAME(AuthDataResultCallback); + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +/** + @brief The name of the `NSNotificationCenter` notification which is posted when the auth state + changes (for example, a new token has been produced, a user signs in or signs out). The + object parameter of the notification is the sender `FIRAuth` instance. + */ +extern const NSNotificationName FIRAuthStateDidChangeNotification + NS_SWIFT_NAME(AuthStateDidChange); +#else +/** + @brief The name of the `NSNotificationCenter` notification which is posted when the auth state + changes (for example, a new token has been produced, a user signs in or signs out). The + object parameter of the notification is the sender `FIRAuth` instance. + */ +extern NSString *const FIRAuthStateDidChangeNotification + NS_SWIFT_NAME(AuthStateDidChangeNotification); +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +/** @typedef FIRAuthResultCallback + @brief The type of block invoked when sign-in related events complete. + + @param user Optionally; the signed in user, if any. + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRAuthResultCallback)(FIRUser *_Nullable user, NSError *_Nullable error) + NS_SWIFT_NAME(AuthResultCallback); + +/** @typedef FIRProviderQueryCallback + @brief The type of block invoked when a list of identity providers for a given email address is + requested. + + @param providers Optionally; a list of provider identifiers, if any. + @see FIRGoogleAuthProviderID etc. + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRProviderQueryCallback)(NSArray *_Nullable providers, + NSError *_Nullable error) + NS_SWIFT_NAME(ProviderQueryCallback); + +/** @typedef FIRSignInMethodQueryCallback + @brief The type of block invoked when a list of sign-in methods for a given email address is + requested. + */ +typedef void (^FIRSignInMethodQueryCallback)(NSArray *_Nullable, + NSError *_Nullable) + NS_SWIFT_NAME(SignInMethodQueryCallback); + +/** @typedef FIRSendPasswordResetCallback + @brief The type of block invoked when sending a password reset email. + + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRSendPasswordResetCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(SendPasswordResetCallback); + +/** @typedef FIRSendSignInLinkToEmailCallback + @brief The type of block invoked when sending an email sign-in link email. + */ +typedef void (^FIRSendSignInLinkToEmailCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(SendSignInLinkToEmailCallback); + +/** @typedef FIRConfirmPasswordResetCallback + @brief The type of block invoked when performing a password reset. + + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRConfirmPasswordResetCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(ConfirmPasswordResetCallback); + +/** @typedef FIRVerifyPasswordResetCodeCallback + @brief The type of block invoked when verifying that an out of band code should be used to + perform password reset. + + @param email Optionally; the email address of the user for which the out of band code applies. + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRVerifyPasswordResetCodeCallback)(NSString *_Nullable email, + NSError *_Nullable error) + NS_SWIFT_NAME(VerifyPasswordResetCodeCallback); + +/** @typedef FIRApplyActionCodeCallback + @brief The type of block invoked when applying an action code. + + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRApplyActionCodeCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(ApplyActionCodeCallback); + +/** + @brief Keys used to retrieve operation data from a `FIRActionCodeInfo` object by the + `dataForKey` method. + */ +typedef NS_ENUM(NSInteger, FIRActionDataKey) { + /** + * The email address to which the code was sent. + * For FIRActionCodeOperationRecoverEmail, the new email address for the account. + */ + FIRActionCodeEmailKey = 0, + + /** For FIRActionCodeOperationRecoverEmail, the current email address for the account. */ + FIRActionCodeFromEmailKey = 1 +} NS_SWIFT_NAME(ActionDataKey); + +/** @class FIRActionCodeInfo + @brief Manages information regarding action codes. + */ +NS_SWIFT_NAME(ActionCodeInfo) +@interface FIRActionCodeInfo : NSObject + +/** + @brief Operations which can be performed with action codes. + */ +typedef NS_ENUM(NSInteger, FIRActionCodeOperation) { + /** Action code for unknown operation. */ + FIRActionCodeOperationUnknown = 0, + + /** Action code for password reset operation. */ + FIRActionCodeOperationPasswordReset = 1, + + /** Action code for verify email operation. */ + FIRActionCodeOperationVerifyEmail = 2, + + /** Action code for recover email operation. */ + FIRActionCodeOperationRecoverEmail = 3, + + /** Action code for email link operation. */ + FIRActionCodeOperationEmailLink = 4, + + +} NS_SWIFT_NAME(ActionCodeOperation); + +/** + @brief The operation being performed. + */ +@property(nonatomic, readonly) FIRActionCodeOperation operation; + +/** @fn dataForKey: + @brief The operation being performed. + + @param key The FIRActionDataKey value used to retrieve the operation data. + + @return The operation data pertaining to the provided action code key. + */ +- (NSString *)dataForKey:(FIRActionDataKey)key; + +/** @fn init + @brief please use initWithOperation: instead. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +/** @typedef FIRCheckActionCodeCallBack + @brief The type of block invoked when performing a check action code operation. + + @param info Metadata corresponding to the action code. + @param error Optionally; if an error occurs, this is the NSError object that describes the + problem. Set to nil otherwise. + */ +typedef void (^FIRCheckActionCodeCallBack)(FIRActionCodeInfo *_Nullable info, + NSError *_Nullable error) + NS_SWIFT_NAME(CheckActionCodeCallback); + +/** @class FIRAuth + @brief Manages authentication for Firebase apps. + @remarks This class is thread-safe. + */ +NS_SWIFT_NAME(Auth) +@interface FIRAuth : NSObject + +/** @fn auth + @brief Gets the auth object for the default Firebase app. + @remarks The default Firebase app must have already been configured or an exception will be + raised. + */ ++ (FIRAuth *)auth NS_SWIFT_NAME(auth()); + +/** @fn authWithApp: + @brief Gets the auth object for a `FIRApp`. + + @param app The FIRApp for which to retrieve the associated FIRAuth instance. + @return The FIRAuth instance associated with the given FIRApp. + */ ++ (FIRAuth *)authWithApp:(FIRApp *)app NS_SWIFT_NAME(auth(app:)); + +/** @property app + @brief Gets the `FIRApp` object that this auth object is connected to. + */ +@property(nonatomic, weak, readonly, nullable) FIRApp *app; + +/** @property currentUser + @brief Synchronously gets the cached current user, or null if there is none. + */ +@property(nonatomic, strong, readonly, nullable) FIRUser *currentUser; + +/** @property languageCode + @brief The current user language code. This property can be set to the app's current language by + calling `useAppLanguage`. + + @remarks The string used to set this property must be a language code that follows BCP 47. + */ +@property (nonatomic, copy, nullable) NSString *languageCode; + +/** @property settings + @brief Contains settings related to the auth object. + */ +@property (nonatomic, copy, nullable) FIRAuthSettings *settings; + +#if TARGET_OS_IOS +/** @property APNSToken + @brief The APNs token used for phone number authentication. The type of the token (production + or sandbox) will be attempted to be automatcially detected. + @remarks If swizzling is disabled, the APNs Token must be set for phone number auth to work, + by either setting this property or by calling `setAPNSToken:type:` + */ +@property(nonatomic, strong, nullable) NSData *APNSToken; +#endif + +/** @fn init + @brief Please access auth instances using `FIRAuth.auth` and `FIRAuth.authForApp:`. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn updateCurrentUser:completion: + @brief Sets the currentUser on the calling Auth instance to the provided user object. + @param user The user object to be set as the current user of the calling Auth instance. + @param completion Optionally; a block invoked after the user of the calling Auth instance has + been updated or an error was encountered. + */ +- (void)updateCurrentUser:(FIRUser *)user completion:(nullable FIRUserUpdateCallback)completion; + +/** @fn fetchProvidersForEmail:completion: + @brief Fetches the list of IdPs that can be used for signing in with the provided email address. + Useful for an "identifier-first" sign-in flow. + + @param email The email address for which to obtain a list of identity providers. + @param completion Optionally; a block which is invoked when the list of providers for the + specified email address is ready or an error was encountered. Invoked asynchronously on the + main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)fetchProvidersForEmail:(NSString *)email + completion:(nullable FIRProviderQueryCallback)completion; + +/** @fn fetchSignInMethodsForEmail:completion: + @brief Fetches the list of all sign-in methods previously used for the provided email address. + + @param email The email address for which to obtain a list of sign-in methods. + @param completion Optionally; a block which is invoked when the list of sign in methods for the + specified email address is ready or an error was encountered. Invoked asynchronously on the + main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + @remarks See @c FIRAuthErrors for a list of error codes that are common to all API methods. + */ + +- (void)fetchSignInMethodsForEmail:(NSString *)email + completion:(nullable FIRSignInMethodQueryCallback)completion; + +/** @fn signInWithEmail:password:completion: + @brief Signs in using an email address and password. + + @param email The user's email address. + @param password The user's password. + @param completion Optionally; a block which is invoked when the sign in flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that email and password + accounts are not enabled. Enable them in the Auth section of the + Firebase console. + + `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. + + `FIRAuthErrorCodeWrongPassword` - Indicates the user attempted + sign in with an incorrect password. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)signInWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn signInWithEmail:link:completion: + @brief Signs in using an email address and email sign-in link. + + @param email The user's email address. + @param link The email sign-in link. + @param completion Optionally; a block which is invoked when the sign in flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that email and email sign-in link + accounts are not enabled. Enable them in the Auth section of the + Firebase console. + + `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is invalid. + + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ + +- (void)signInWithEmail:(NSString *)email + link:(NSString *)link + completion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn signInAndRetrieveDataWithEmail:password:completion: + @brief Please use `signInWithEmail:password:completion:` for Objective-C or + `signIn(withEmail:password:completion:)` for Swift instead. + + @param email The user's email address. + @param password The user's password. + @param completion Optionally; a block which is invoked when the sign in flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + */ +- (void)signInAndRetrieveDataWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRAuthDataResultCallback)completion + DEPRECATED_MSG_ATTRIBUTE( + "Please use signInWithEmail:password:completion: for" + " Objective-C or signIn(withEmail:password:completion:) for" + " Swift instead."); + +/** @fn signInWithCredential:completion: + @brief Please use `signInAndRetrieveDataWithCredential:completion:` for Objective-C or + `signInAndRetrieveData(with:completion:)` for swift instead + + @param credential The credential supplied by the IdP. + @param completion Optionally; a block which is invoked when the sign in flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid. + This could happen if it has expired or it is malformed. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts + with the identity provider represented by the credential are not enabled. + Enable them in the Auth section of the Firebase console. + + `FIRAuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted + by the credential (e.g. the email in a Facebook access token) is already in use by an + existing account, that cannot be authenticated with this sign-in method. Call + fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of + the sign-in providers returned. This error will only be thrown if the "One account per + email address" setting is enabled in the Firebase console, under Auth settings. + + `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. + + `FIRAuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an + incorrect password, if credential is of the type EmailPasswordAuthCredential. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + `FIRAuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was + created with an empty verification ID. + + `FIRAuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential + was created with an empty verification code. + + `FIRAuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential + was created with an invalid verification Code. + + `FIRAuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was + created with an invalid verification ID. + + `FIRAuthErrorCodeSessionExpired` - Indicates that the SMS code has expired. + + + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods + */ +- (void)signInWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthResultCallback)completion DEPRECATED_MSG_ATTRIBUTE( + "Please use signInAndRetrieveDataWithCredential:completion:" + " for Objective-C or signInAndRetrieveData(with:completion:)" + " for Swift instead."); + +/** @fn signInAndRetrieveDataWithCredential:completion: + @brief Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook + login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional + identity provider data. + + @param credential The credential supplied by the IdP. + @param completion Optionally; a block which is invoked when the sign in flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid. + This could happen if it has expired or it is malformed. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts + with the identity provider represented by the credential are not enabled. + Enable them in the Auth section of the Firebase console. + + `FIRAuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted + by the credential (e.g. the email in a Facebook access token) is already in use by an + existing account, that cannot be authenticated with this sign-in method. Call + fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of + the sign-in providers returned. This error will only be thrown if the "One account per + email address" setting is enabled in the Firebase console, under Auth settings. + + `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. + + `FIRAuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an + incorrect password, if credential is of the type EmailPasswordAuthCredential. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + `FIRAuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was + created with an empty verification ID. + + `FIRAuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential + was created with an empty verification code. + + `FIRAuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential + was created with an invalid verification Code. + + `FIRAuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was + created with an invalid verification ID. + + `FIRAuthErrorCodeSessionExpired` - Indicates that the SMS code has expired. + + + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods + */ +- (void)signInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn signInAnonymouslyWithCompletion: + @brief Asynchronously creates and becomes an anonymous user. + @param completion Optionally; a block which is invoked when the sign in finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks If there is already an anonymous user signed in, that user will be returned instead. + If there is any other existing user signed in, that user will be signed out. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are + not enabled. Enable them in the Auth section of the Firebase console. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)signInAnonymouslyWithCompletion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn signInAnonymouslyAndRetrieveDataWithCompletion: + @brief `Please use sign `signInAnonymouslyWithCompletion:` for Objective-C or + `signInAnonymously(Completion:)` for Swift instead. + @param completion Optionally; a block which is invoked when the sign in finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + */ +- (void)signInAnonymouslyAndRetrieveDataWithCompletion: + (nullable FIRAuthDataResultCallback)completion + DEPRECATED_MSG_ATTRIBUTE("Please use signInAnonymouslyWithCompletion: for Objective-C or" + " signInAnonymously(Completion:) for swift instead."); + +/** @fn signInWithCustomToken:completion: + @brief Asynchronously signs in to Firebase with the given Auth token. + + @param token A self-signed custom auth token. + @param completion Optionally; a block which is invoked when the sign in finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidCustomToken` - Indicates a validation error with + the custom token. + + `FIRAuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key + belong to different projects. + + + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)signInWithCustomToken:(NSString *)token + completion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn signInAndRetrieveDataWithCustomToken:completion: + @brief Please use `signInWithCustomToken:completion:` or `signIn(withCustomToken:completion:)` + for Swift instead. + + @param token A self-signed custom auth token. + @param completion Optionally; a block which is invoked when the sign in finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + */ +- (void)signInAndRetrieveDataWithCustomToken:(NSString *)token + completion:(nullable FIRAuthDataResultCallback)completion + DEPRECATED_MSG_ATTRIBUTE( + "Please use signInWithCustomToken:completion:" + "for Objective-C or signIn(withCustomToken:completion:) for" + " Swift instead."); + +/** @fn createUserWithEmail:password:completion: + @brief Creates and, on success, signs in a user with the given email address and password. + + @param email The user's email address. + @param password The user's desired password. + @param completion Optionally; a block which is invoked when the sign up flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + `FIRAuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up + already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user + used, and prompt the user to sign in with one of those. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts + are not enabled. Enable them in the Auth section of the Firebase console. + + `FIRAuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is + considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo + dictionary object will contain more detailed explanation that can be shown to the user. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)createUserWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRAuthDataResultCallback)completion; + +/** @fn createUserAndRetrieveDataWithEmail:password:completion: + @brief Please use `createUserAndRetrieveDataWithEmail:password:completion:` or + `createUser(withEmail:password:completion:)` for Swift instead. + + @param email The user's email address. + @param password The user's desired password. + @param completion Optionally; a block which is invoked when the sign up flow finishes, or is + canceled. Invoked asynchronously on the main thread in the future. + */ +- (void)createUserAndRetrieveDataWithEmail:(NSString *)email + password:(NSString *)password + completion:(nullable FIRAuthDataResultCallback)completion + DEPRECATED_MSG_ATTRIBUTE( + "Please use createUserWithEmail:password:completion: for" + " Objective-C or createUser(withEmail:password:completion:)" + " for Swift instead."); + +/** @fn confirmPasswordResetWithCode:newPassword:completion: + @brief Resets the password given a code sent to the user outside of the app and a new password + for the user. + + @param newPassword The new password. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is + considered too weak. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign + in with the specified identity provider. + + `FIRAuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired. + + `FIRAuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)confirmPasswordResetWithCode:(NSString *)code + newPassword:(NSString *)newPassword + completion:(FIRConfirmPasswordResetCallback)completion; + +/** @fn checkActionCode:completion: + @brief Checks the validity of an out of band code. + + @param code The out of band code to check validity. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + */ +- (void)checkActionCode:(NSString *)code completion:(FIRCheckActionCodeCallBack)completion; + +/** @fn verifyPasswordResetCode:completion: + @brief Checks the validity of a verify password reset code. + + @param code The password reset code to be verified. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + */ +- (void)verifyPasswordResetCode:(NSString *)code + completion:(FIRVerifyPasswordResetCodeCallback)completion; + +/** @fn applyActionCode:completion: + @brief Applies out of band code. + + @param code The out of band code to be applied. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + + @remarks This method will not work for out of band codes which require an additional parameter, + such as password reset code. + */ +- (void)applyActionCode:(NSString *)code + completion:(FIRApplyActionCodeCallback)completion; + +/** @fn sendPasswordResetWithEmail:completion: + @brief Initiates a password reset for the given email address. + + @param email The email address of the user. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was + sent in the request. + + `FIRAuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in + the console for this action. + + `FIRAuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for + sending update email. + + + */ +- (void)sendPasswordResetWithEmail:(NSString *)email + completion:(nullable FIRSendPasswordResetCallback)completion; + +/** @fn sendPasswordResetWithEmail:actionCodeSetting:completion: + @brief Initiates a password reset for the given email address and @FIRActionCodeSettings object. + + @param email The email address of the user. + @param actionCodeSettings An `FIRActionCodeSettings` object containing settings related to + handling action codes. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was + sent in the request. + + `FIRAuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in + the console for this action. + + `FIRAuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for + sending update email. + + `FIRAuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when + `handleCodeInApp` is set to YES. + + `FIRAuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name + is missing when the `androidInstallApp` flag is set to true. + + `FIRAuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the + continue URL is not whitelisted in the Firebase console. + + `FIRAuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the + continue URI is not valid. + + + */ + - (void)sendPasswordResetWithEmail:(NSString *)email + actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendPasswordResetCallback)completion; + +/** @fn sendSignInLinkToEmail:actionCodeSettings:completion: + @brief Sends a sign in with email link to provided email address. + + @param email The email address of the user. + @param actionCodeSettings An `FIRActionCodeSettings` object containing settings related to + handling action codes. + @param completion Optionally; a block which is invoked when the request finishes. Invoked + asynchronously on the main thread in the future. + */ +- (void)sendSignInLinkToEmail:(NSString *)email + actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendSignInLinkToEmailCallback)completion; + +/** @fn signOut: + @brief Signs out the current user. + + @param error Optionally; if an error occurs, upon return contains an NSError object that + describes the problem; is nil otherwise. + @return @YES when the sign out request was successful. @NO otherwise. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeKeychainError` - Indicates an error occurred when accessing the + keychain. The `NSLocalizedFailureReasonErrorKey` field in the `NSError.userInfo` + dictionary will contain more information about the error encountered. + + + + */ +- (BOOL)signOut:(NSError *_Nullable *_Nullable)error; + +/** @fn isSignInWithEmailLink + @brief Checks if link is an email sign-in link. + + @param link The email sign-in link. + @return @YES when the link passed matches the expected format of an email sign-in link. + */ +- (BOOL)isSignInWithEmailLink:(NSString *)link; + +/** @fn addAuthStateDidChangeListener: + @brief Registers a block as an "auth state did change" listener. To be invoked when: + + + The block is registered as a listener, + + A user with a different UID from the current user has signed in, or + + The current user has signed out. + + @param listener The block to be invoked. The block is always invoked asynchronously on the main + thread, even for it's initial invocation after having been added as a listener. + + @remarks The block is invoked immediately after adding it according to it's standard invocation + semantics, asynchronously on the main thread. Users should pay special attention to + making sure the block does not inadvertently retain objects which should not be retained by + the long-lived block. The block itself will be retained by `FIRAuth` until it is + unregistered or until the `FIRAuth` instance is otherwise deallocated. + + @return A handle useful for manually unregistering the block as a listener. + */ +- (FIRAuthStateDidChangeListenerHandle)addAuthStateDidChangeListener: + (FIRAuthStateDidChangeListenerBlock)listener; + +/** @fn removeAuthStateDidChangeListener: + @brief Unregisters a block as an "auth state did change" listener. + + @param listenerHandle The handle for the listener. + */ +- (void)removeAuthStateDidChangeListener:(FIRAuthStateDidChangeListenerHandle)listenerHandle; + +/** @fn addIDTokenDidChangeListener: + @brief Registers a block as an "ID token did change" listener. To be invoked when: + + + The block is registered as a listener, + + A user with a different UID from the current user has signed in, + + The ID token of the current user has been refreshed, or + + The current user has signed out. + + @param listener The block to be invoked. The block is always invoked asynchronously on the main + thread, even for it's initial invocation after having been added as a listener. + + @remarks The block is invoked immediately after adding it according to it's standard invocation + semantics, asynchronously on the main thread. Users should pay special attention to + making sure the block does not inadvertently retain objects which should not be retained by + the long-lived block. The block itself will be retained by `FIRAuth` until it is + unregistered or until the `FIRAuth` instance is otherwise deallocated. + + @return A handle useful for manually unregistering the block as a listener. + */ +- (FIRIDTokenDidChangeListenerHandle)addIDTokenDidChangeListener: + (FIRIDTokenDidChangeListenerBlock)listener; + +/** @fn removeIDTokenDidChangeListener: + @brief Unregisters a block as an "ID token did change" listener. + + @param listenerHandle The handle for the listener. + */ +- (void)removeIDTokenDidChangeListener:(FIRIDTokenDidChangeListenerHandle)listenerHandle; + +/** @fn useAppLanguage + @brief Sets `languageCode` to the app's current language. + */ +- (void)useAppLanguage; + +#if TARGET_OS_IOS + +/** @fn canHandleURL: + @brief Whether the specific URL is handled by `FIRAuth` . + @param URL The URL received by the application delegate from any of the openURL method. + @return Whether or the URL is handled. YES means the URL is for Firebase Auth + so the caller should ignore the URL from further processing, and NO means the + the URL is for the app (or another libaray) so the caller should continue handling + this URL as usual. + @remarks If swizzling is disabled, URLs received by the application delegate must be forwarded + to this method for phone number auth to work. + */ +- (BOOL)canHandleURL:(nonnull NSURL *)URL; + +/** @fn setAPNSToken:type: + @brief Sets the APNs token along with its type. + @remarks If swizzling is disabled, the APNs Token must be set for phone number auth to work, + by either setting calling this method or by setting the `APNSToken` property. + */ +- (void)setAPNSToken:(NSData *)token type:(FIRAuthAPNSTokenType)type; + +/** @fn canHandleNotification: + @brief Whether the specific remote notification is handled by `FIRAuth` . + @param userInfo A dictionary that contains information related to the + notification in question. + @return Whether or the notification is handled. YES means the notification is for Firebase Auth + so the caller should ignore the notification from further processing, and NO means the + the notification is for the app (or another libaray) so the caller should continue handling + this notification as usual. + @remarks If swizzling is disabled, related remote notifications must be forwarded to this method + for phone number auth to work. + */ +- (BOOL)canHandleNotification:(NSDictionary *)userInfo; + +#endif // TARGET_OS_IOS + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthAPNSTokenType.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthAPNSTokenType.h new file mode 100644 index 0000000..4f3c9f6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthAPNSTokenType.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * @brief The APNs token type for the app. + */ +typedef NS_ENUM(NSInteger, FIRAuthAPNSTokenType) { + + /** Unknown token type. + The actual token type will be detected from the provisioning profile in the app's bundle. + */ + FIRAuthAPNSTokenTypeUnknown, + + /** Sandbox token type. + */ + FIRAuthAPNSTokenTypeSandbox, + + /** Production token type. + */ + FIRAuthAPNSTokenTypeProd, +} NS_SWIFT_NAME(AuthAPNSTokenType); + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthCredential.h new file mode 100644 index 0000000..106d844 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthCredential.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthCredential + @brief Represents a credential. + */ +NS_SWIFT_NAME(AuthCredential) +@interface FIRAuthCredential : NSObject + +/** @property provider + @brief Gets the name of the identity provider for the credential. + */ +@property(nonatomic, copy, readonly) NSString *provider; + +/** @fn init + @brief This is an abstract base class. Concrete instances should be created via factory + methods available in the various authentication provider libraries (like the Facebook + provider or the Google provider libraries.) + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthDataResult.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthDataResult.h new file mode 100644 index 0000000..bc4fa4a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthDataResult.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAdditionalUserInfo; +@class FIRUser; + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthDataResult + @brief Helper object that contains the result of a successful sign-in, link and reauthenticate + action. It contains references to a FIRUser instance and a FIRAdditionalUserInfo instance. + */ +NS_SWIFT_NAME(AuthDataResult) +@interface FIRAuthDataResult : NSObject + +/** @fn init + @brief This class should not be initialized manually. `FIRAuthDataResult` instance is + returned as part of `FIRAuthDataResultCallback`. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @property user + @brief The signed in user. + */ +@property(nonatomic, readonly) FIRUser *user; + +/** @property additionalUserInfo + @brief If available contains the additional IdP specific information about signed in user. + */ +@property(nonatomic, readonly, nullable) FIRAdditionalUserInfo *additionalUserInfo; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthErrors.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthErrors.h new file mode 100644 index 0000000..9d177b6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthErrors.h @@ -0,0 +1,330 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** @class FIRAuthErrors + @remarks Error Codes common to all API Methods: + + + `FIRAuthErrorCodeNetworkError` + + `FIRAuthErrorCodeUserNotFound` + + `FIRAuthErrorCodeUserTokenExpired` + + `FIRAuthErrorCodeTooManyRequests` + + `FIRAuthErrorCodeInvalidAPIKey` + + `FIRAuthErrorCodeAppNotAuthorized` + + `FIRAuthErrorCodeKeychainError` + + `FIRAuthErrorCodeInternalError` + + @remarks Common error codes for `FIRUser` operations: + + + `FIRAuthErrorCodeInvalidUserToken` + + `FIRAuthErrorCodeUserDisabled` + + */ +NS_SWIFT_NAME(AuthErrors) +@interface FIRAuthErrors + +/** + @brief The Firebase Auth error domain. + */ +extern NSString *const FIRAuthErrorDomain NS_SWIFT_NAME(AuthErrorDomain); + +/** + @brief The key used to read the updated credential from the userinfo dictionary of the NSError + object returned in the case that the credential being linked in already in use. + */ +extern NSString *const FIRAuthUpdatedCredentialKey NS_SWIFT_NAME(AuthUpdatedCredentialKey); + +/** + @brief The name of the key for the "error_name" string in the NSError userinfo dictionary. + */ +extern NSString *const FIRAuthErrorNameKey NS_SWIFT_NAME(AuthErrorNameKey); + +/** + @brief Errors with the code `FIRAuthErrorCodeAccountExistsWithDifferentCredential` may contain + an `NSError.userInfo` dictinary object which contains this key. The value associated with + this key is an NSString of the email address of the account that already exists. + */ +extern NSString *const FIRAuthErrorUserInfoEmailKey NS_SWIFT_NAME(AuthErrorUserInfoEmailKey); + +/** + @brief Error codes used by Firebase Auth. + */ +typedef NS_ENUM(NSInteger, FIRAuthErrorCode) { + /** Indicates a validation error with the custom token. + */ + FIRAuthErrorCodeInvalidCustomToken = 17000, + + /** Indicates the service account and the API key belong to different projects. + */ + FIRAuthErrorCodeCustomTokenMismatch = 17002, + + /** Indicates the IDP token or requestUri is invalid. + */ + FIRAuthErrorCodeInvalidCredential = 17004, + + /** Indicates the user's account is disabled on the server. + */ + FIRAuthErrorCodeUserDisabled = 17005, + + /** Indicates the administrator disabled sign in with the specified identity provider. + */ + FIRAuthErrorCodeOperationNotAllowed = 17006, + + /** Indicates the email used to attempt a sign up is already in use. + */ + FIRAuthErrorCodeEmailAlreadyInUse = 17007, + + /** Indicates the email is invalid. + */ + FIRAuthErrorCodeInvalidEmail = 17008, + + /** Indicates the user attempted sign in with a wrong password. + */ + FIRAuthErrorCodeWrongPassword = 17009, + + /** Indicates that too many requests were made to a server method. + */ + FIRAuthErrorCodeTooManyRequests = 17010, + + /** Indicates the user account was not found. + */ + FIRAuthErrorCodeUserNotFound = 17011, + + /** Indicates account linking is required. + */ + FIRAuthErrorCodeAccountExistsWithDifferentCredential = 17012, + + /** Indicates the user has attemped to change email or password more than 5 minutes after + signing in. + */ + FIRAuthErrorCodeRequiresRecentLogin = 17014, + + /** Indicates an attempt to link a provider to which the account is already linked. + */ + FIRAuthErrorCodeProviderAlreadyLinked = 17015, + + /** Indicates an attempt to unlink a provider that is not linked. + */ + FIRAuthErrorCodeNoSuchProvider = 17016, + + /** Indicates user's saved auth credential is invalid, the user needs to sign in again. + */ + FIRAuthErrorCodeInvalidUserToken = 17017, + + /** Indicates a network error occurred (such as a timeout, interrupted connection, or + unreachable host). These types of errors are often recoverable with a retry. The + `NSUnderlyingError` field in the `NSError.userInfo` dictionary will contain the error + encountered. + */ + FIRAuthErrorCodeNetworkError = 17020, + + /** Indicates the saved token has expired, for example, the user may have changed account + password on another device. The user needs to sign in again on the device that made this + request. + */ + FIRAuthErrorCodeUserTokenExpired = 17021, + + /** Indicates an invalid API key was supplied in the request. + */ + FIRAuthErrorCodeInvalidAPIKey = 17023, + + /** Indicates that an attempt was made to reauthenticate with a user which is not the current + user. + */ + FIRAuthErrorCodeUserMismatch = 17024, + + /** Indicates an attempt to link with a credential that has already been linked with a + different Firebase account + */ + FIRAuthErrorCodeCredentialAlreadyInUse = 17025, + + /** Indicates an attempt to set a password that is considered too weak. + */ + FIRAuthErrorCodeWeakPassword = 17026, + + /** Indicates the App is not authorized to use Firebase Authentication with the + provided API Key. + */ + FIRAuthErrorCodeAppNotAuthorized = 17028, + + /** Indicates the OOB code is expired. + */ + FIRAuthErrorCodeExpiredActionCode = 17029, + + /** Indicates the OOB code is invalid. + */ + FIRAuthErrorCodeInvalidActionCode = 17030, + + /** Indicates that there are invalid parameters in the payload during a "send password reset + * email" attempt. + */ + FIRAuthErrorCodeInvalidMessagePayload = 17031, + + /** Indicates that the sender email is invalid during a "send password reset email" attempt. + */ + FIRAuthErrorCodeInvalidSender = 17032, + + /** Indicates that the recipient email is invalid. + */ + FIRAuthErrorCodeInvalidRecipientEmail = 17033, + + /** Indicates that an email address was expected but one was not provided. + */ + FIRAuthErrorCodeMissingEmail = 17034, + + // The enum values 17035 is reserved and should NOT be used for new error codes. + + /** Indicates that the iOS bundle ID is missing when a iOS App Store ID is provided. + */ + FIRAuthErrorCodeMissingIosBundleID = 17036, + + /** Indicates that the android package name is missing when the `androidInstallApp` flag is set + to true. + */ + FIRAuthErrorCodeMissingAndroidPackageName = 17037, + + /** Indicates that the domain specified in the continue URL is not whitelisted in the Firebase + console. + */ + FIRAuthErrorCodeUnauthorizedDomain = 17038, + + /** Indicates that the domain specified in the continue URI is not valid. + */ + FIRAuthErrorCodeInvalidContinueURI = 17039, + + /** Indicates that a continue URI was not provided in a request to the backend which requires + one. + */ + FIRAuthErrorCodeMissingContinueURI = 17040, + + /** Indicates that a phone number was not provided in a call to + `verifyPhoneNumber:completion:`. + */ + FIRAuthErrorCodeMissingPhoneNumber = 17041, + + /** Indicates that an invalid phone number was provided in a call to + `verifyPhoneNumber:completion:`. + */ + FIRAuthErrorCodeInvalidPhoneNumber = 17042, + + /** Indicates that the phone auth credential was created with an empty verification code. + */ + FIRAuthErrorCodeMissingVerificationCode = 17043, + + /** Indicates that an invalid verification code was used in the verifyPhoneNumber request. + */ + FIRAuthErrorCodeInvalidVerificationCode = 17044, + + /** Indicates that the phone auth credential was created with an empty verification ID. + */ + FIRAuthErrorCodeMissingVerificationID = 17045, + + /** Indicates that an invalid verification ID was used in the verifyPhoneNumber request. + */ + FIRAuthErrorCodeInvalidVerificationID = 17046, + + /** Indicates that the APNS device token is missing in the verifyClient request. + */ + FIRAuthErrorCodeMissingAppCredential = 17047, + + /** Indicates that an invalid APNS device token was used in the verifyClient request. + */ + FIRAuthErrorCodeInvalidAppCredential = 17048, + + // The enum values between 17048 and 17051 are reserved and should NOT be used for new error + // codes. + + /** Indicates that the SMS code has expired. + */ + FIRAuthErrorCodeSessionExpired = 17051, + + /** Indicates that the quota of SMS messages for a given project has been exceeded. + */ + FIRAuthErrorCodeQuotaExceeded = 17052, + + /** Indicates that the APNs device token could not be obtained. The app may not have set up + remote notification correctly, or may fail to forward the APNs device token to FIRAuth + if app delegate swizzling is disabled. + */ + FIRAuthErrorCodeMissingAppToken = 17053, + + /** Indicates that the app fails to forward remote notification to FIRAuth. + */ + FIRAuthErrorCodeNotificationNotForwarded = 17054, + + /** Indicates that the app could not be verified by Firebase during phone number authentication. + */ + FIRAuthErrorCodeAppNotVerified = 17055, + + /** Indicates that the reCAPTCHA token is not valid. + */ + FIRAuthErrorCodeCaptchaCheckFailed = 17056, + + /** Indicates that an attempt was made to present a new web context while one was already being + presented. + */ + FIRAuthErrorCodeWebContextAlreadyPresented = 17057, + + /** Indicates that the URL presentation was cancelled prematurely by the user. + */ + FIRAuthErrorCodeWebContextCancelled = 17058, + + /** Indicates a general failure during the app verification flow. + */ + FIRAuthErrorCodeAppVerificationUserInteractionFailure = 17059, + + /** Indicates that the clientID used to invoke a web flow is invalid. + */ + FIRAuthErrorCodeInvalidClientID = 17060, + + /** Indicates that a network request within a SFSafariViewController or UIWebview failed. + */ + FIRAuthErrorCodeWebNetworkRequestFailed = 17061, + + /** Indicates that an internal error occurred within a SFSafariViewController or UIWebview. + */ + FIRAuthErrorCodeWebInternalError = 17062, + + /** Indicates that the local player was not authenticated prior to attempting Game Center signin. + */ + FIRAuthErrorCodeLocalPlayerNotAuthenticated = 17066, + + /** Indicates that a non-null user was expected as an argmument to the operation but a null + user was provided. + */ + FIRAuthErrorCodeNullUser = 17067, + + /** Indicates that the Firebase Dynamic Link domain used is either not configured or is unauthorized + for the current project. + */ + FIRAuthErrorCodeInvalidDynamicLinkDomain = 17074, + + /** Indicates an error occurred while attempting to access the keychain. + */ + FIRAuthErrorCodeKeychainError = 17995, + + /** Indicates an internal error occurred. + */ + FIRAuthErrorCodeInternalError = 17999, + + /** Raised when a JWT fails to parse correctly. May be accompanied by an underlying error + describing which step of the JWT parsing process failed. + */ + FIRAuthErrorCodeMalformedJWT = 18000, +} NS_SWIFT_NAME(AuthErrorCode); + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthSettings.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthSettings.h new file mode 100644 index 0000000..d3fee3e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthSettings.h @@ -0,0 +1,30 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** @class FIRAuthSettings + @brief Determines settings related to an auth object. + */ +@interface FIRAuthSettings : NSObject + +/** @property appVerificationDisabledForTesting + @brief Flag to determine whether app verification should be disabled for testing or not. + */ +@property (nonatomic, assign, getter=isAppVerificationDisabledForTesting) BOOL + appVerificationDisabledForTesting; + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthTokenResult.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthTokenResult.h new file mode 100644 index 0000000..82a5f1e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthTokenResult.h @@ -0,0 +1,66 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthTokenResult + @brief A data class containing the ID token JWT string and other properties associated with the + token including the decoded payload claims. + */ +NS_SWIFT_NAME(AuthTokenResult) +@interface FIRAuthTokenResult : NSObject + +/** @property token + @brief Stores the JWT string of the ID token. + */ +@property (nonatomic, readonly) NSString *token; + +/** @property expirationDate + @brief Stores the ID token's expiration date. + */ +@property (nonatomic, readonly) NSDate *expirationDate; + +/** @property authDate + @brief Stores the ID token's authentication date. + @remarks This is the date the user was signed in and NOT the date the token was refreshed. + */ +@property (nonatomic, readonly) NSDate *authDate; + +/** @property issuedAtDate + @brief Stores the date that the ID token was issued. + @remarks This is the date last refreshed and NOT the last authentication date. + */ +@property (nonatomic, readonly) NSDate *issuedAtDate; + +/** @property signInProvider + @brief Stores sign-in provider through which the token was obtained. + @remarks This does not necesssarily map to provider IDs. + */ +@property (nonatomic, readonly) NSString *signInProvider; + +/** @property claims + @brief Stores the entire payload of claims found on the ID token. This includes the standard + reserved claims as well as custom claims set by the developer via the Admin SDK. + */ +@property (nonatomic, readonly) NSDictionary *claims; + + + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthUIDelegate.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthUIDelegate.h new file mode 100644 index 0000000..9b32968 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRAuthUIDelegate.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @protocol FIRAuthUIDelegate + @brief A protocol to handle user interface interactions for Firebase Auth. + */ +NS_SWIFT_NAME(AuthUIDelegate) +@protocol FIRAuthUIDelegate + +/** @fn presentViewController:animated:completion: + @brief If implemented, this method will be invoked when Firebase Auth needs to display a view + controller. + @param viewControllerToPresent The view controller to be presented. + @param flag Decides whether the view controller presentation should be animated or not. + @param completion The block to execute after the presentation finishes. This block has no return + value and takes no parameters. +*/ +- (void)presentViewController:(UIViewController *)viewControllerToPresent + animated:(BOOL)flag + completion:(void (^ _Nullable)(void))completion; + +/** @fn dismissViewControllerAnimated:completion: + @brief If implemented, this method will be invoked when Firebase Auth needs to display a view + controller. + @param flag Decides whether removing the view controller should be animated or not. + @param completion The block to execute after the presentation finishes. This block has no return + value and takes no parameters. +*/ +- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^ _Nullable)(void))completion + NS_SWIFT_NAME(dismiss(animated:completion:)); + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIREmailAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIREmailAuthProvider.h new file mode 100644 index 0000000..b6375bd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIREmailAuthProvider.h @@ -0,0 +1,81 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the email & password identity provider. + */ +extern NSString *const FIREmailAuthProviderID NS_SWIFT_NAME(EmailAuthProviderID); + +/** + @brief A string constant identifying the email-link sign-in method. + */ +extern NSString *const FIREmailLinkAuthSignInMethod NS_SWIFT_NAME(EmailLinkAuthSignInMethod); + +/** + @brief A string constant identifying the email & password sign-in method. + */ +extern NSString *const FIREmailPasswordAuthSignInMethod + NS_SWIFT_NAME(EmailPasswordAuthSignInMethod); + +/** + @brief Please use `FIREmailAuthProviderID` for Objective-C or `EmailAuthProviderID` for Swift instead. + */ +extern NSString *const FIREmailPasswordAuthProviderID __attribute__((deprecated)); + +/** @class FIREmailAuthProvider + @brief A concrete implementation of `FIRAuthProvider` for Email & Password Sign In. + */ +NS_SWIFT_NAME(EmailAuthProvider) +@interface FIREmailAuthProvider : NSObject + +/** @typedef FIREmailPasswordAuthProvider + @brief Please use `FIREmailAuthProvider` instead. + */ +typedef FIREmailAuthProvider FIREmailPasswordAuthProvider __attribute__((deprecated)); + + +/** @fn credentialWithEmail:password: + @brief Creates an `FIRAuthCredential` for an email & password sign in. + + @param email The user's email address. + @param password The user's password. + @return A FIRAuthCredential containing the email & password credential. + */ ++ (FIRAuthCredential *)credentialWithEmail:(NSString *)email password:(NSString *)password; + +/** @fn credentialWithEmail:Link: + @brief Creates an `FIRAuthCredential` for an email & link sign in. + + @param email The user's email address. + @param link The email sign-in link. + @return A FIRAuthCredential containing the email & link credential. + */ ++ (FIRAuthCredential *)credentialWithEmail:(NSString *)email link:(NSString *)link; + +/** @fn init + @brief This class is not meant to be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRFacebookAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRFacebookAuthProvider.h new file mode 100644 index 0000000..75efe13 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRFacebookAuthProvider.h @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the Facebook identity provider. + */ +extern NSString *const FIRFacebookAuthProviderID NS_SWIFT_NAME(FacebookAuthProviderID); + +/** + @brief A string constant identifying the Facebook sign-in method. + */ +extern NSString *const _Nonnull FIRFacebookAuthSignInMethod NS_SWIFT_NAME(FacebookAuthSignInMethod); + +/** @class FIRFacebookAuthProvider + @brief Utility class for constructing Facebook credentials. + */ +NS_SWIFT_NAME(FacebookAuthProvider) +@interface FIRFacebookAuthProvider : NSObject + +/** @fn credentialWithAccessToken: + @brief Creates an `FIRAuthCredential` for a Facebook sign in. + + @param accessToken The Access Token from Facebook. + @return A FIRAuthCredential containing the Facebook credentials. + */ ++ (FIRAuthCredential *)credentialWithAccessToken:(NSString *)accessToken; + +/** @fn init + @brief This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGameCenterAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGameCenterAuthProvider.h new file mode 100644 index 0000000..d49b8f6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGameCenterAuthProvider.h @@ -0,0 +1,62 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the Game Center identity provider. + */ +extern NSString *const FIRGameCenterAuthProviderID NS_SWIFT_NAME(GameCenterAuthProviderID); + +/** + @brief A string constant identifying the Game Center sign-in method. + */ +extern NSString *const _Nonnull FIRGameCenterAuthSignInMethod +NS_SWIFT_NAME(GameCenterAuthSignInMethod); + +/** @typedef FIRGameCenterCredentialCallback + @brief The type of block invoked when the Game Center credential code has finished. + @param credential On success, the credential will be provided, nil otherwise. + @param error On error, the error that occured, nil otherwise. + */ +typedef void (^FIRGameCenterCredentialCallback)(FIRAuthCredential *_Nullable credential, + NSError *_Nullable error) +NS_SWIFT_NAME(GameCenterCredentialCallback); + +/** @class FIRGameCenterAuthProvider + @brief A concrete implementation of @c FIRAuthProvider for Game Center Sign In. + */ +NS_SWIFT_NAME(GameCenterAuthProvider) +@interface FIRGameCenterAuthProvider : NSObject + +/** @fn getCredentialWithCompletion: + @brief Creates a @c FIRAuthCredential for a Game Center sign in. + */ ++ (void)getCredentialWithCompletion:(FIRGameCenterCredentialCallback)completion +NS_SWIFT_NAME(getCredential(completion:)); + +/** @fn init + @brief This class is not meant to be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGitHubAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGitHubAuthProvider.h new file mode 100644 index 0000000..0610427 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGitHubAuthProvider.h @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the GitHub identity provider. + */ +extern NSString *const FIRGitHubAuthProviderID NS_SWIFT_NAME(GitHubAuthProviderID); + +/** + @brief A string constant identifying the GitHub sign-in method. + */ +extern NSString *const _Nonnull FIRGitHubAuthSignInMethod NS_SWIFT_NAME(GitHubAuthSignInMethod); + + +/** @class FIRGitHubAuthProvider + @brief Utility class for constructing GitHub credentials. + */ +NS_SWIFT_NAME(GitHubAuthProvider) +@interface FIRGitHubAuthProvider : NSObject + +/** @fn credentialWithToken: + @brief Creates an `FIRAuthCredential` for a GitHub sign in. + + @param token The GitHub OAuth access token. + @return A FIRAuthCredential containing the GitHub credential. + */ ++ (FIRAuthCredential *)credentialWithToken:(NSString *)token; + +/** @fn init + @brief This class is not meant to be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGoogleAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGoogleAuthProvider.h new file mode 100644 index 0000000..7d6fa22 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRGoogleAuthProvider.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the Google identity provider. + */ +extern NSString *const FIRGoogleAuthProviderID NS_SWIFT_NAME(GoogleAuthProviderID); + +/** + @brief A string constant identifying the Google sign-in method. + */ +extern NSString *const _Nonnull FIRGoogleAuthSignInMethod NS_SWIFT_NAME(GoogleAuthSignInMethod); + +/** @class FIRGoogleAuthProvider + @brief Utility class for constructing Google Sign In credentials. + */ +NS_SWIFT_NAME(GoogleAuthProvider) +@interface FIRGoogleAuthProvider : NSObject + +/** @fn credentialWithIDToken:accessToken: + @brief Creates an `FIRAuthCredential` for a Google sign in. + + @param IDToken The ID Token from Google. + @param accessToken The Access Token from Google. + @return A FIRAuthCredential containing the Google credentials. + */ ++ (FIRAuthCredential *)credentialWithIDToken:(NSString *)IDToken + accessToken:(NSString *)accessToken; + +/** @fn init + @brief This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIROAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIROAuthProvider.h new file mode 100644 index 0000000..cc628f8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIROAuthProvider.h @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIROAuthProvider + @brief A concrete implementation of `FIRAuthProvider` for generic OAuth Providers. + */ +NS_SWIFT_NAME(OAuthProvider) +@interface FIROAuthProvider : NSObject + +/** @fn credentialWithProviderID:IDToken:accessToken: + @brief Creates an `FIRAuthCredential` for that OAuth 2 provider identified by providerID, ID + token and access token. + + @param providerID The provider ID associated with the Auth credential being created. + @param IDToken The IDToken associated with the Auth credential being created. + @param accessToken The accessstoken associated with the Auth credential be created, if + available. + @return A FIRAuthCredential for the specified provider ID, ID token and access token. + */ ++ (FIRAuthCredential *)credentialWithProviderID:(NSString *)providerID + IDToken:(NSString *)IDToken + accessToken:(nullable NSString *)accessToken; + + +/** @fn credentialWithProviderID:accessToken: + @brief Creates an `FIRAuthCredential` for that OAuth 2 provider identified by providerID using + an ID token. + + @param providerID The provider ID associated with the Auth credential being created. + @param accessToken The accessstoken associated with the Auth credential be created + @return A FIRAuthCredential. + */ ++ (FIRAuthCredential *)credentialWithProviderID:(NSString *)providerID + accessToken:(NSString *)accessToken; + +/** @fn init + @brief This class is not meant to be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthCredential.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthCredential.h new file mode 100644 index 0000000..26dfca8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthCredential.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRPhoneAuthCredential + @brief Implementation of FIRAuthCredential for Phone Auth credentials. + */ +NS_SWIFT_NAME(PhoneAuthCredential) +@interface FIRPhoneAuthCredential : FIRAuthCredential + +/** @fn init + @brief This class is not supposed to be instantiated directly. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthProvider.h new file mode 100644 index 0000000..301939e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRPhoneAuthProvider.h @@ -0,0 +1,105 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuth; +@class FIRPhoneAuthCredential; +@protocol FIRAuthUIDelegate; + +NS_ASSUME_NONNULL_BEGIN + +/** @var FIRPhoneAuthProviderID + @brief A string constant identifying the phone identity provider. + */ +extern NSString *const FIRPhoneAuthProviderID NS_SWIFT_NAME(PhoneAuthProviderID); + +/** @var FIRPhoneAuthProviderID + @brief A string constant identifying the phone sign-in method. + */ +extern NSString *const _Nonnull FIRPhoneAuthSignInMethod NS_SWIFT_NAME(PhoneAuthSignInMethod); + +/** @typedef FIRVerificationResultCallback + @brief The type of block invoked when a request to send a verification code has finished. + + @param verificationID On success, the verification ID provided, nil otherwise. + @param error On error, the error that occurred, nil otherwise. + */ +typedef void (^FIRVerificationResultCallback)(NSString *_Nullable verificationID, + NSError *_Nullable error) + NS_SWIFT_NAME(VerificationResultCallback); + +/** @class FIRPhoneAuthProvider + @brief A concrete implementation of `FIRAuthProvider` for phone auth providers. + */ +NS_SWIFT_NAME(PhoneAuthProvider) +@interface FIRPhoneAuthProvider : NSObject + +/** @fn provider + @brief Returns an instance of `FIRPhoneAuthProvider` for the default `FIRAuth` object. + */ ++ (instancetype)provider NS_SWIFT_NAME(provider()); + +/** @fn providerWithAuth: + @brief Returns an instance of `FIRPhoneAuthProvider` for the provided `FIRAuth` object. + + @param auth The auth object to associate with the phone auth provider instance. + */ ++ (instancetype)providerWithAuth:(FIRAuth *)auth NS_SWIFT_NAME(provider(auth:)); + +/** @fn verifyPhoneNumber:UIDelegate:completion: + @brief Starts the phone number authentication flow by sending a verifcation code to the + specified phone number. + @param phoneNumber The phone number to be verified. + @param UIDelegate An object used to present the SFSafariViewController. The object is retained + by this method until the completion block is executed. + @param completion The callback to be invoked when the verification flow is finished. + @remarks Possible error codes: + + + `FIRAuthErrorCodeCaptchaCheckFailed` - Indicates that the reCAPTCHA token obtained by + the Firebase Auth is invalid or has expired. + + `FIRAuthErrorCodeQuotaExceeded` - Indicates that the phone verification quota for this + project has been exceeded. + + `FIRAuthErrorCodeInvalidPhoneNumber` - Indicates that the phone number provided is + invalid. + + `FIRAuthErrorCodeMissingPhoneNumber` - Indicates that a phone number was not provided. + */ +- (void)verifyPhoneNumber:(NSString *)phoneNumber + UIDelegate:(nullable id)UIDelegate + completion:(nullable FIRVerificationResultCallback)completion; + +/** @fn credentialWithVerificationID:verificationCode: + @brief Creates an `FIRAuthCredential` for the phone number provider identified by the + verification ID and verification code. + + @param verificationID The verification ID obtained from invoking + verifyPhoneNumber:completion: + @param verificationCode The verification code obtained from the user. + @return The corresponding phone auth credential for the verification ID and verification code + provided. + */ +- (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode; + +/** @fn init + @brief Please use the `provider` or `providerWithAuth:` methods to obtain an instance of + `FIRPhoneAuthProvider`. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRTwitterAuthProvider.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRTwitterAuthProvider.h new file mode 100644 index 0000000..a0d1166 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRTwitterAuthProvider.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthCredential; + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief A string constant identifying the Twitter identity provider. + */ +extern NSString *const FIRTwitterAuthProviderID NS_SWIFT_NAME(TwitterAuthProviderID); + +/** + @brief A string constant identifying the Twitter sign-in method. + */ +extern NSString *const _Nonnull FIRTwitterAuthSignInMethod NS_SWIFT_NAME(TwitterAuthSignInMethod); + + +/** @class FIRTwitterAuthProvider + @brief Utility class for constructing Twitter credentials. + */ +NS_SWIFT_NAME(TwitterAuthProvider) +@interface FIRTwitterAuthProvider : NSObject + +/** @fn credentialWithToken:secret: + @brief Creates an `FIRAuthCredential` for a Twitter sign in. + + @param token The Twitter OAuth token. + @param secret The Twitter OAuth secret. + @return A FIRAuthCredential containing the Twitter credential. + */ ++ (FIRAuthCredential *)credentialWithToken:(NSString *)token secret:(NSString *)secret; + +/** @fn init + @brief This class is not meant to be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUser.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUser.h new file mode 100644 index 0000000..cc5d0a0 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUser.h @@ -0,0 +1,495 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuth.h" +#import "FIRAuthDataResult.h" +#import "FIRUserInfo.h" + +@class FIRAuthTokenResult; +@class FIRPhoneAuthCredential; +@class FIRUserProfileChangeRequest; +@class FIRUserMetadata; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthTokenCallback + @brief The type of block called when a token is ready for use. + @see FIRUser.getIDTokenWithCompletion: + @see FIRUser.getIDTokenForcingRefresh:withCompletion: + + @param token Optionally; an access token if the request was successful. + @param error Optionally; the error which occurred - or nil if the request was successful. + + @remarks One of: `token` or `error` will always be non-nil. + */ +typedef void (^FIRAuthTokenCallback)(NSString *_Nullable token, NSError *_Nullable error) + NS_SWIFT_NAME(AuthTokenCallback); + +/** @typedef FIRAuthTokenResultCallback + @brief The type of block called when a token is ready for use. + @see FIRUser.getIDTokenResultWithCompletion: + @see FIRUser.getIDTokenResultForcingRefresh:withCompletion: + + @param tokenResult Optionally; an object containing the raw access token string as well as other + useful data pertaining to the token. + @param error Optionally; the error which occurred - or nil if the request was successful. + + @remarks One of: `token` or `error` will always be non-nil. + */ +typedef void (^FIRAuthTokenResultCallback)(FIRAuthTokenResult *_Nullable tokenResult, + NSError *_Nullable error) + NS_SWIFT_NAME(AuthTokenResultCallback); + +/** @typedef FIRUserProfileChangeCallback + @brief The type of block called when a user profile change has finished. + + @param error Optionally; the error which occurred - or nil if the request was successful. + */ +typedef void (^FIRUserProfileChangeCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(UserProfileChangeCallback); + +/** @typedef FIRSendEmailVerificationCallback + @brief The type of block called when a request to send an email verification has finished. + + @param error Optionally; the error which occurred - or nil if the request was successful. + */ +typedef void (^FIRSendEmailVerificationCallback)(NSError *_Nullable error) + NS_SWIFT_NAME(SendEmailVerificationCallback); + +/** @class FIRUser + @brief Represents a user. Firebase Auth does not attempt to validate users + when loading them from the keychain. Invalidated users (such as those + whose passwords have been changed on another client) are automatically + logged out when an auth-dependent operation is attempted or when the + ID token is automatically refreshed. + @remarks This class is thread-safe. + */ +NS_SWIFT_NAME(User) +@interface FIRUser : NSObject + +/** @property anonymous + @brief Indicates the user represents an anonymous user. + */ +@property(nonatomic, readonly, getter=isAnonymous) BOOL anonymous; + +/** @property emailVerified + @brief Indicates the email address associated with this user has been verified. + */ +@property(nonatomic, readonly, getter=isEmailVerified) BOOL emailVerified; + +/** @property refreshToken + @brief A refresh token; useful for obtaining new access tokens independently. + @remarks This property should only be used for advanced scenarios, and is not typically needed. + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/** @property providerData + @brief Profile data for each identity provider, if any. + @remarks This data is cached on sign-in and updated when linking or unlinking. + */ +@property(nonatomic, readonly, nonnull) NSArray> *providerData; + +/** @property metadata + @brief Metadata associated with the Firebase user in question. + */ +@property(nonatomic, readonly, nonnull) FIRUserMetadata *metadata; + +/** @fn init + @brief This class should not be instantiated. + @remarks To retrieve the current user, use `FIRAuth.currentUser`. To sign a user + in or out, use the methods on `FIRAuth`. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn updateEmail:completion: + @brief Updates the email address for the user. On success, the cached user profile data is + updated. + @remarks May fail if there is already an account with this email address that was created using + email and password authentication. + + @param email The email address for the user. + @param completion Optionally; the block invoked when the user profile change has finished. + Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was + sent in the request. + + `FIRAuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in + the console for this action. + + `FIRAuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for + sending update email. + + `FIRAuthErrorCodeEmailAlreadyInUse` - Indicates the email is already in use by another + account. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + `FIRAuthErrorCodeRequiresRecentLogin` - Updating a user’s email is a security + sensitive operation that requires a recent login from the user. This error indicates + the user has not signed in recently enough. To resolve, reauthenticate the user by + invoking reauthenticateWithCredential:completion: on FIRUser. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)updateEmail:(NSString *)email completion:(nullable FIRUserProfileChangeCallback)completion + NS_SWIFT_NAME(updateEmail(to:completion:)); + +/** @fn updatePassword:completion: + @brief Updates the password for the user. On success, the cached user profile data is updated. + + @param password The new password for the user. + @param completion Optionally; the block invoked when the user profile change has finished. + Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled + sign in with the specified identity provider. + + `FIRAuthErrorCodeRequiresRecentLogin` - Updating a user’s password is a security + sensitive operation that requires a recent login from the user. This error indicates + the user has not signed in recently enough. To resolve, reauthenticate the user by + invoking reauthenticateWithCredential:completion: on FIRUser. + + `FIRAuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is + considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo + dictionary object will contain more detailed explanation that can be shown to the user. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)updatePassword:(NSString *)password + completion:(nullable FIRUserProfileChangeCallback)completion + NS_SWIFT_NAME(updatePassword(to:completion:)); + +#if TARGET_OS_IOS +/** @fn updatePhoneNumberCredential:completion: + @brief Updates the phone number for the user. On success, the cached user profile data is + updated. + + @param phoneNumberCredential The new phone number credential corresponding to the phone number + to be added to the Firebase account, if a phone number is already linked to the account this + new phone number will replace it. + @param completion Optionally; the block invoked when the user profile change has finished. + Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeRequiresRecentLogin` - Updating a user’s phone number is a security + sensitive operation that requires a recent login from the user. This error indicates + the user has not signed in recently enough. To resolve, reauthenticate the user by + invoking reauthenticateWithCredential:completion: on FIRUser. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)updatePhoneNumberCredential:(FIRPhoneAuthCredential *)phoneNumberCredential + completion:(nullable FIRUserProfileChangeCallback)completion; +#endif + +/** @fn profileChangeRequest + @brief Creates an object which may be used to change the user's profile data. + + @remarks Set the properties of the returned object, then call + `FIRUserProfileChangeRequest.commitChangesWithCallback:` to perform the updates atomically. + + @return An object which may be used to change the user's profile data atomically. + */ +- (FIRUserProfileChangeRequest *)profileChangeRequest NS_SWIFT_NAME(createProfileChangeRequest()); + +/** @fn reloadWithCompletion: + @brief Reloads the user's profile data from the server. + + @param completion Optionally; the block invoked when the reload has finished. Invoked + asynchronously on the main thread in the future. + + @remarks May fail with a `FIRAuthErrorCodeRequiresRecentLogin` error code. In this case + you should call `FIRUser.reauthenticateWithCredential:completion:` before re-invoking + `FIRUser.updateEmail:completion:`. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)reloadWithCompletion:(nullable FIRUserProfileChangeCallback)completion; + +/** @fn reauthenticateWithCredential:completion: + @brief Please use reauthenticateAndRetrieveDataWithCredential:completion: for Objective-C or + reauthenticateAndRetrieveData(WithCredential:completion:) for Swift instead. + */ +- (void)reauthenticateWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRUserProfileChangeCallback)completion + DEPRECATED_MSG_ATTRIBUTE( "Please use" + " reauthenticateAndRetrieveDataWithCredential:completion: for" + " Objective-C or" + " reauthenticateAndRetrieveData(WithCredential:completion:)" + " for Swift instead."); + +/** @fn reauthenticateAndRetrieveDataWithCredential:completion: + @brief Renews the user's authentication tokens by validating a fresh set of credentials supplied + by the user and returns additional identity provider data. + + @param credential A user-supplied credential, which will be validated by the server. This can be + a successful third-party identity provider sign-in, or an email address and password. + @param completion Optionally; the block invoked when the re-authentication operation has + finished. Invoked asynchronously on the main thread in the future. + + @remarks If the user associated with the supplied credential is different from the current user, + or if the validation of the supplied credentials fails; an error is returned and the current + user remains signed in. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid. + This could happen if it has expired or it is malformed. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts with the + identity provider represented by the credential are not enabled. Enable them in the + Auth section of the Firebase console. + + `FIRAuthErrorCodeEmailAlreadyInUse` - Indicates the email asserted by the credential + (e.g. the email in a Facebook access token) is already in use by an existing account, + that cannot be authenticated with this method. Call fetchProvidersForEmail for + this user’s email and then prompt them to sign in with any of the sign-in providers + returned. This error will only be thrown if the "One account per email address" + setting is enabled in the Firebase console, under Auth settings. Please note that the + error code raised in this specific situation may not be the same on Web and Android. + + `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. + + `FIRAuthErrorCodeWrongPassword` - Indicates the user attempted reauthentication with + an incorrect password, if credential is of the type EmailPasswordAuthCredential. + + `FIRAuthErrorCodeUserMismatch` - Indicates that an attempt was made to + reauthenticate with a user which is not the current user. + + `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)reauthenticateAndRetrieveDataWithCredential:(FIRAuthCredential *) credential + completion:(nullable FIRAuthDataResultCallback) completion; + +/** @fn getIDTokenResultWithCompletion: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + + @param completion Optionally; the block invoked when the token is available. Invoked + asynchronously on the main thread in the future. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)getIDTokenResultWithCompletion:(nullable FIRAuthTokenResultCallback)completion + NS_SWIFT_NAME(getIDTokenResult(completion:)); + +/** @fn getIDTokenResultForcingRefresh:completion: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + + @param forceRefresh Forces a token refresh. Useful if the token becomes invalid for some reason + other than an expiration. + @param completion Optionally; the block invoked when the token is available. Invoked + asynchronously on the main thread in the future. + + @remarks The authentication token will be refreshed (by making a network request) if it has + expired, or if `forceRefresh` is YES. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh + completion:(nullable FIRAuthTokenResultCallback)completion + NS_SWIFT_NAME(getIDTokenResult(forcingRefresh:completion:)); + +/** @fn getIDTokenWithCompletion: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + + @param completion Optionally; the block invoked when the token is available. Invoked + asynchronously on the main thread in the future. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)getIDTokenWithCompletion:(nullable FIRAuthTokenCallback)completion + NS_SWIFT_NAME(getIDToken(completion:)); + +/** @fn getIDTokenForcingRefresh:completion: + @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired. + + @param forceRefresh Forces a token refresh. Useful if the token becomes invalid for some reason + other than an expiration. + @param completion Optionally; the block invoked when the token is available. Invoked + asynchronously on the main thread in the future. + + @remarks The authentication token will be refreshed (by making a network request) if it has + expired, or if `forceRefresh` is YES. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all API methods. + */ +- (void)getIDTokenForcingRefresh:(BOOL)forceRefresh + completion:(nullable FIRAuthTokenCallback)completion; + +/** @fn linkWithCredential:completion: + @brief Please use linkAndRetrieveDataWithCredential:completion: for Objective-C or + linkAndRetrieveData(WithCredential:completion:) for Swift instead. + */ +- (void)linkWithCredential:(FIRAuthCredential *)credential + completion:(nullable FIRAuthResultCallback)completion DEPRECATED_MSG_ATTRIBUTE( + "Please use linkAndRetrieveDataWithCredential:completion: for" + " Objective-C or" + " linkAndRetrieveData(WithCredential:completion:) for" + " Swift instead."); + +/** @fn linkAndRetrieveDataWithCredential:completion: + @brief Associates a user account from a third-party identity provider with this user and + returns additional identity provider data. + + @param credential The credential for the identity provider. + @param completion Optionally; the block invoked when the unlinking is complete, or fails. + Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeProviderAlreadyLinked` - Indicates an attempt to link a provider of a + type already linked to this account. + + `FIRAuthErrorCodeCredentialAlreadyInUse` - Indicates an attempt to link with a + credential + that has already been linked with a different Firebase account. + + `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts with the identity + provider represented by the credential are not enabled. Enable them in the Auth section + of the Firebase console. + + @remarks This method may also return error codes associated with updateEmail:completion: and + updatePassword:completion: on FIRUser. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)linkAndRetrieveDataWithCredential:(FIRAuthCredential *) credential + completion:(nullable FIRAuthDataResultCallback) completion; + +/** @fn unlinkFromProvider:completion: + @brief Disassociates a user account from a third-party identity provider with this user. + + @param provider The provider ID of the provider to unlink. + @param completion Optionally; the block invoked when the unlinking is complete, or fails. + Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeNoSuchProvider` - Indicates an attempt to unlink a provider + that is not linked to the account. + + `FIRAuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive + operation that requires a recent login from the user. This error indicates the user + has not signed in recently enough. To resolve, reauthenticate the user by invoking + reauthenticateWithCredential:completion: on FIRUser. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)unlinkFromProvider:(NSString *)provider + completion:(nullable FIRAuthResultCallback)completion; + +/** @fn sendEmailVerificationWithCompletion: + @brief Initiates email verification for the user. + + @param completion Optionally; the block invoked when the request to send an email verification + is complete, or fails. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was + sent in the request. + + `FIRAuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in + the console for this action. + + `FIRAuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for + sending update email. + + `FIRAuthErrorCodeUserNotFound` - Indicates the user account was not found. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + */ +- (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion; + +/** @fn sendEmailVerificationWithActionCodeSettings:completion: + @brief Initiates email verification for the user. + + @param actionCodeSettings An `FIRActionCodeSettings` object containing settings related to + handling action codes. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was + sent in the request. + + `FIRAuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in + the console for this action. + + `FIRAuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for + sending update email. + + `FIRAuthErrorCodeUserNotFound` - Indicates the user account was not found. + + `FIRAuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing when + a iOS App Store ID is provided. + + `FIRAuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name + is missing when the `androidInstallApp` flag is set to true. + + `FIRAuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the + continue URL is not whitelisted in the Firebase console. + + `FIRAuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the + continue URI is not valid. + */ +- (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings + completion:(nullable FIRSendEmailVerificationCallback) + completion; + +/** @fn deleteWithCompletion: + @brief Deletes the user account (also signs out the user, if this was the current user). + + @param completion Optionally; the block invoked when the request to delete the account is + complete, or fails. Invoked asynchronously on the main thread in the future. + + @remarks Possible error codes: + + + `FIRAuthErrorCodeRequiresRecentLogin` - Updating email is a security sensitive + operation that requires a recent login from the user. This error indicates the user + has not signed in recently enough. To resolve, reauthenticate the user by invoking + reauthenticateWithCredential:completion: on FIRUser. + + @remarks See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. + + */ +- (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion; + +@end + +/** @class FIRUserProfileChangeRequest + @brief Represents an object capable of updating a user's profile data. + @remarks Properties are marked as being part of a profile update when they are set. Setting a + property value to nil is not the same as leaving the property unassigned. + */ +NS_SWIFT_NAME(UserProfileChangeRequest) +@interface FIRUserProfileChangeRequest : NSObject + +/** @fn init + @brief Please use `FIRUser.profileChangeRequest` + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @property displayName + @brief The user's display name. + @remarks It is an error to set this property after calling + `FIRUserProfileChangeRequest.commitChangesWithCallback:` + */ +@property(nonatomic, copy, nullable) NSString *displayName; + +/** @property photoURL + @brief The user's photo URL. + @remarks It is an error to set this property after calling + `FIRUserProfileChangeRequest.commitChangesWithCallback:` + */ +@property(nonatomic, copy, nullable) NSURL *photoURL; + +/** @fn commitChangesWithCompletion: + @brief Commits any pending changes. + @remarks This method should only be called once. Once called, property values should not be + changed. + + @param completion Optionally; the block invoked when the user profile change has been applied. + Invoked asynchronously on the main thread in the future. + */ +- (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserInfo.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserInfo.h new file mode 100644 index 0000000..04eca49 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserInfo.h @@ -0,0 +1,60 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + @brief Represents user data returned from an identity provider. + */ +NS_SWIFT_NAME(UserInfo) +@protocol FIRUserInfo + +/** @property providerID + @brief The provider identifier. + */ +@property(nonatomic, copy, readonly) NSString *providerID; + +/** @property uid + @brief The provider's user ID for the user. + */ +@property(nonatomic, copy, readonly) NSString *uid; + +/** @property displayName + @brief The name of the user. + */ +@property(nonatomic, copy, readonly, nullable) NSString *displayName; + +/** @property photoURL + @brief The URL of the user's profile photo. + */ +@property(nonatomic, copy, readonly, nullable) NSURL *photoURL; + +/** @property email + @brief The user's email address. + */ +@property(nonatomic, copy, readonly, nullable) NSString *email; + +/** @property phoneNumber + @brief A phone number associated with the user. + @remarks This property is only available for users authenticated via phone number auth. + */ +@property(nonatomic, readonly, nullable) NSString *phoneNumber; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserMetadata.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserMetadata.h new file mode 100644 index 0000000..2533171 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FIRUserMetadata.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRUserMetdata + @brief A data class representing the metadata corresponding to a Firebase user. + */ +NS_SWIFT_NAME(UserMetadata) +@interface FIRUserMetadata : NSObject + +/** @property lastSignInDate + @brief Stores the last sign in date for the corresponding Firebase user. + */ +@property (copy, nonatomic, readonly, nullable) NSDate *lastSignInDate; + +/** @property creationDate + @brief Stores the creation date for the corresponding Firebase user. + */ +@property (copy, nonatomic, readonly, nullable) NSDate *creationDate; + +/** @fn init + @brief This class should not be initialized manually, an instance of this class can be obtained + from a Firebase user object. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuth.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuth.h new file mode 100644 index 0000000..15693fe --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuth.h @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRActionCodeSettings.h" +#import "FIRAdditionalUserInfo.h" +#import "FIRAuth.h" +#import "FIRAuthCredential.h" +#import "FIRAuthDataResult.h" +#import "FIRAuthErrors.h" +#import "FIRAuthTokenResult.h" +#import "FirebaseAuthVersion.h" +#import "FIREmailAuthProvider.h" +#import "FIRFacebookAuthProvider.h" +#import "FIRGameCenterAuthProvider.h" +#import "FIRGitHubAuthProvider.h" +#import "FIRGoogleAuthProvider.h" +#import "FIROAuthProvider.h" +#import "FIRTwitterAuthProvider.h" +#import "FIRUser.h" +#import "FIRUserInfo.h" +#import "FIRUserMetadata.h" + +#if TARGET_OS_IOS +#import "FIRAuthUIDelegate.h" +#import "FIRPhoneAuthCredential.h" +#import "FIRPhoneAuthProvider.h" +#import "FIRAuthAPNSTokenType.h" +#import "FIRAuthSettings.h" +#endif diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuthVersion.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuthVersion.h new file mode 100644 index 0000000..2999384 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/Public/FirebaseAuthVersion.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + Version number for FirebaseAuth. + */ +extern const double FirebaseAuthVersionNum; + +/** + Version string for FirebaseAuth. + */ +extern const unsigned char *const FirebaseAuthVersionStr; diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.h new file mode 100644 index 0000000..9ced6a3 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.h @@ -0,0 +1,599 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthRequestConfiguration; +@class FIRCreateAuthURIRequest; +@class FIRCreateAuthURIResponse; +@class FIRDeleteAccountRequest; +@class FIRDeleteAccountResponse; +@class FIREmailLinkSignInRequest; +@class FIREmailLinkSignInResponse; +@class FIRGetAccountInfoRequest; +@class FIRGetAccountInfoResponse; +@class FIRGetProjectConfigRequest; +@class FIRGetProjectConfigResponse; +@class FIRGetOOBConfirmationCodeRequest; +@class FIRGetOOBConfirmationCodeResponse; +@class FIRResetPasswordRequest; +@class FIRResetPasswordResponse; +@class FIRSecureTokenRequest; +@class FIRSecureTokenResponse; +@class FIRSetAccountInfoRequest; +@class FIRSetAccountInfoResponse; +@class FIRVerifyAssertionRequest; +@class FIRVerifyAssertionResponse; +@class FIRVerifyClientRequest; +@class FIRVerifyClientResponse; +@class FIRVerifyCustomTokenRequest; +@class FIRVerifyCustomTokenResponse; +@class FIRVerifyPasswordRequest; +@class FIRVerifyPasswordResponse; +@class FIRVerifyPhoneNumberRequest; +@class FIRVerifyPhoneNumberResponse; +@class FIRSendVerificationCodeRequest; +@class FIRSendVerificationCodeResponse; +@class FIRSignInWithGameCenterRequest; +@class FIRSignInWithGameCenterResponse; +@class FIRSignUpNewUserRequest; +@class FIRSignUpNewUserResponse; + +@protocol FIRAuthBackendImplementation; +@protocol FIRAuthBackendRPCIssuer; + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRAuthBackendRPCIssuerCompletionHandler + @brief The type of block used to return the result of a call to an endpoint. + @param data The HTTP response body. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRAuthBackendRPCIssuerCompletionHandler)(NSData *_Nullable data, + NSError *_Nullable error); + +/** @typedef FIRCreateAuthURIResponseCallback + @brief The type of block used to return the result of a call to the createAuthURI + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRCreateAuthURIResponseCallback) + (FIRCreateAuthURIResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRGetAccountInfoResponseCallback + @brief The type of block used to return the result of a call to the getAccountInfo + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRGetAccountInfoResponseCallback) + (FIRGetAccountInfoResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRGetProjectConfigResponseCallback + @brief The type of block used to return the result of a call to the getProjectInfo + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRGetProjectConfigResponseCallback) + (FIRGetProjectConfigResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRSetAccountInfoResponseCallback + @brief The type of block used to return the result of a call to the setAccountInfo + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRSetAccountInfoResponseCallback) + (FIRSetAccountInfoResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRSecureTokenResponseCallback + @brief The type of block used to return the result of a call to the token endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRSecureTokenResponseCallback) + (FIRSecureTokenResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRVerifyAssertionResponseCallback + @brief The type of block used to return the result of a call to the verifyAssertion + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRVerifyAssertionResponseCallback) + (FIRVerifyAssertionResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRVerifyPasswordResponseCallback + @brief The type of block used to return the result of a call to the verifyPassword + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRVerifyPasswordResponseCallback) + (FIRVerifyPasswordResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIREmailLinkSigninResponseCallback + @brief The type of block used to return the result of a call to the emailLinkSignin + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIREmailLinkSigninResponseCallback) + (FIREmailLinkSignInResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRVerifyCustomTokenResponseCallback + @brief The type of block used to return the result of a call to the verifyCustomToken + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRVerifyCustomTokenResponseCallback) + (FIRVerifyCustomTokenResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRDeleteCallBack + @brief The type of block called when a request delete account has finished. + @param error The error which occurred, or nil if the request was successful. + */ +typedef void (^FIRDeleteCallBack)(NSError *_Nullable error); + +/** @typedef FIRGetOOBConfirmationCodeResponseCallback + @brief The type of block used to return the result of a call to the getOOBConfirmationCode + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRGetOOBConfirmationCodeResponseCallback) + (FIRGetOOBConfirmationCodeResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRSignupNewUserCallback + @brief The type of block used to return the result of a call to the signupNewUser endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRSignupNewUserCallback) + (FIRSignUpNewUserResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRResetPasswordCallback + @brief The type of block used to return the result of a call to the resetPassword endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRResetPasswordCallback) + (FIRResetPasswordResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRSendVerificationCodeResponseCallback + @brief The type of block used to return the result of a call to the sendVerificationCode + endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRSendVerificationCodeResponseCallback) + (FIRSendVerificationCodeResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRVerifyPhoneNumberResponseCallback + @brief The type of block used to return the result of a call to the verifyPhoneNumber endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRVerifyPhoneNumberResponseCallback) + (FIRVerifyPhoneNumberResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRVerifyClientResponseCallback + @brief The type of block used to return the result of a call to the verifyClient endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRVerifyClientResponseCallback) + (FIRVerifyClientResponse *_Nullable response, NSError *_Nullable error); + +/** @typedef FIRSignInWithGameCenterResponseCallback + @brief The type of block used to return the result of a call to the SignInWithGameCenter endpoint. + @param response The received response, if any. + @param error The error which occurred, if any. + @remarks One of response or error will be non-nil. + */ +typedef void (^FIRSignInWithGameCenterResponseCallback) + (FIRSignInWithGameCenterResponse *_Nullable response, NSError *_Nullable error); + +/** @class FIRAuthBackend + @brief Simple static class with methods representing the backend RPCs. + @remarks All callback blocks passed as method parameters are invoked asynchronously on the + global work queue in the future. See + https://github.com/firebase/firebase-ios-sdk/tree/master/Firebase/Auth/Docs/threading.ml + */ +@interface FIRAuthBackend : NSObject + +/** @fn authUserAgent + @brief Retrieves the Firebase Auth user agent. + @return The Firebase Auth user agent. + */ ++ (NSString *)authUserAgent; + +/** @fn setBackendImplementation: + @brief Changes the default backend implementation to something else. + @param backendImplementation The backend implementation to use. + @remarks This is not, generally, safe to call in a scenario where other backend requests may + be occuring. This is specifically to help mock the backend for testing purposes. + */ ++ (void)setBackendImplementation:(id)backendImplementation; + +/** @fn setDefaultBackendImplementationWithRPCIssuer: + @brief Uses the default backend implementation, but with a custom RPC issuer. + @param RPCIssuer The RPC issuer to use. If @c nil, will use the default implementation. + @remarks This is not, generally, safe to call in a scenario where other backend requests may + be occuring. This is specifically to help test the backend interfaces (requests, responses, + and shared FIRAuthBackend logic.) + */ ++ (void)setDefaultBackendImplementationWithRPCIssuer: + (nullable id)RPCIssuer; + +/** @fn createAuthURI:callback: + @brief Calls the createAuthURI endpoint, which is responsible for creating the URI used by the + IdP to authenticate the user. + @param request The request parameters. + @param callback The callback. + */ ++ (void)createAuthURI:(FIRCreateAuthURIRequest *)request + callback:(FIRCreateAuthURIResponseCallback)callback; + +/** @fn getAccountInfo:callback: + @brief Calls the getAccountInfo endpoint, which returns account info for a given account. + @param request The request parameters. + @param callback The callback. + */ ++ (void)getAccountInfo:(FIRGetAccountInfoRequest *)request + callback:(FIRGetAccountInfoResponseCallback)callback; + +/** @fn getProjectConfig:callback: + @brief Calls the getProjectConfig endpoint, which returns configuration information for a given + project. + @param request An object wrapping the backend get request. + @param callback The callback. + */ ++ (void)getProjectConfig:(FIRGetProjectConfigRequest *)request + callback:(FIRGetProjectConfigResponseCallback)callback; + +/** @fn setAccountInfo:callback: + @brief Calls the setAccountInfo endpoint, which is responsible for setting account info for a + user, for example, to sign up a new user with email and password. + @param request The request parameters. + @param callback The callback. + */ ++ (void)setAccountInfo:(FIRSetAccountInfoRequest *)request + callback:(FIRSetAccountInfoResponseCallback)callback; + +/** @fn verifyAssertion:callback: + @brief Calls the verifyAssertion endpoint, which is responsible for authenticating a + user who has IDP-related credentials (an ID Token, an Access Token, etc.) + @param request The request parameters. + @param callback The callback. + */ ++ (void)verifyAssertion:(FIRVerifyAssertionRequest *)request + callback:(FIRVerifyAssertionResponseCallback)callback; + +/** @fn verifyCustomToken:callback: + @brief Calls the verifyCustomToken endpoint, which is responsible for authenticating a + user who has BYOAuth credentials (a self-signed token using their BYOAuth private key.) + @param request The request parameters. + @param callback The callback. + */ ++ (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request + callback:(FIRVerifyCustomTokenResponseCallback)callback; + +/** @fn verifyPassword:callback: + @brief Calls the verifyPassword endpoint, which is responsible for authenticating a + user who has email and password credentials. + @param request The request parameters. + @param callback The callback. + */ ++ (void)verifyPassword:(FIRVerifyPasswordRequest *)request + callback:(FIRVerifyPasswordResponseCallback)callback; + +/** @fn emailLinkSignin:callback: + @brief Calls the emailLinkSignin endpoint, which is responsible for authenticating a + user through passwordless sign-in. + @param request The request parameters. + @param callback The callback. + */ ++ (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request + callback:(FIREmailLinkSigninResponseCallback)callback; + +/** @fn secureToken:callback: + @brief Calls the token endpoint, which is responsible for performing STS token exchanges and + token refreshes. + @param request The request parameters. + @param callback The callback. + */ ++ (void)secureToken:(FIRSecureTokenRequest *)request + callback:(FIRSecureTokenResponseCallback)callback; + +/** @fn getOOBConfirmationCode:callback: + @brief Calls the getOOBConfirmationCode endpoint, which is responsible for sending email change + request emails, and password reset emails. + @param request The request parameters. + @param callback The callback. + */ ++ (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request + callback:(FIRGetOOBConfirmationCodeResponseCallback)callback; + +/** @fn signUpNewUser: + @brief Calls the signUpNewUser endpoint, which is responsible anonymously signing up a user + or signing in a user anonymously. + @param request The request parameters. + @param callback The callback. + */ ++ (void)signUpNewUser:(FIRSignUpNewUserRequest *)request + callback:(FIRSignupNewUserCallback)callback; + +/** @fn resetPassword:callback + @brief Calls the resetPassword endpoint, which is responsible for resetting a user's password + given an OOB code and new password. + @param request The request parameters. + @param callback The callback. + */ ++ (void)resetPassword:(FIRResetPasswordRequest *)request + callback:(FIRResetPasswordCallback)callback; + +/** @fn deleteAccount: + @brief Calls the DeleteAccount endpoint, which is responsible for deleting a user. + @param request The request parameters. + @param callback The callback. + */ ++ (void)deleteAccount:(FIRDeleteAccountRequest *)request + callback:(FIRDeleteCallBack)callback; + +/** @fn SignInWithGameCenter:callback: + @brief Calls the SignInWithGameCenter endpoint, which is responsible for authenticating a user + who has Game Center credentials. + @param request The request parameters. + @param callback The callback. + */ ++ (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request + callback:(FIRSignInWithGameCenterResponseCallback)callback; + +#if TARGET_OS_IOS +/** @fn sendVerificationCode:callback: + @brief Calls the sendVerificationCode endpoint, which is responsible for sending the + verification code to a phone number specified in the request parameters. + @param request The request parameters. + @param callback The callback. + */ ++ (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request + callback:(FIRSendVerificationCodeResponseCallback)callback; + +/** @fn verifyPhoneNumber:callback: + @brief Calls the verifyPhoneNumber endpoint, which is responsible for sending the verification + code to a phone number specified in the request parameters. + @param request The request parameters. + @param callback The callback. + */ ++ (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request + callback:(FIRVerifyPhoneNumberResponseCallback)callback; + +/** @fn verifyClient:callback: + @brief Calls the verifyClient endpoint, which is responsible for sending the silent push + notification used for app validation to the device provided in the request parameters. + @param request The request parameters. + @param callback The callback. + */ ++ (void)verifyClient:(FIRVerifyClientRequest *)request + callback:(FIRVerifyClientResponseCallback)callback; +#endif + +@end + +/** @protocol FIRAuthBackendRPCIssuer + @brief Used to make FIRAuthBackend + */ +@protocol FIRAuthBackendRPCIssuer + +/** @fn asyncPostToURLWithRequestConfiguration:URL:body:contentType:completionHandler: + @brief Asynchronously seXnds a POST request. + @param requestConfiguration The request to be made. + @param URL The request URL. + @param body Request body. + @param contentType Content type of the body. + @param handler provided that handles POST response. Invoked asynchronously on the auth global + work queue in the future. + */ +- (void)asyncPostToURLWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + URL:(NSURL *)URL + body:(nullable NSData *)body + contentType:(NSString *)contentType + completionHandler:(FIRAuthBackendRPCIssuerCompletionHandler)handler; + +@end + +/** @protocol FIRAuthBackendImplementation + @brief Used to make FIRAuthBackend provide a layer of indirection to an actual RPC-based backend + or a mock backend. + */ +@protocol FIRAuthBackendImplementation + +/** @fn createAuthURI:callback: + @brief Calls the createAuthURI endpoint, which is responsible for creating the URI used by the + IdP to authenticate the user. + @param request The request parameters. + @param callback The callback. + */ +- (void)createAuthURI:(FIRCreateAuthURIRequest *)request + callback:(FIRCreateAuthURIResponseCallback)callback; + +/** @fn getAccountInfo:callback: + @brief Calls the getAccountInfo endpoint, which returns account info for a given account. + @param request The request parameters. + @param callback The callback. + */ +- (void)getAccountInfo:(FIRGetAccountInfoRequest *)request + callback:(FIRGetAccountInfoResponseCallback)callback; + +/** @fn getProjectConfig:callback: + @brief Calls the getProjectInfo endpoint, which returns configuration information for a given + project. + @param request The request parameters. + @param callback The callback. + */ +- (void)getProjectConfig:(FIRGetProjectConfigRequest *)request + callback:(FIRGetProjectConfigResponseCallback)callback; + +/** @fn setAccountInfo:callback: + @brief Calls the setAccountInfo endpoint, which is responsible for setting account info for a + user, for example, to sign up a new user with email and password. + @param request The request parameters. + @param callback The callback. + */ +- (void)setAccountInfo:(FIRSetAccountInfoRequest *)request + callback:(FIRSetAccountInfoResponseCallback)callback; + +/** @fn verifyAssertion:callback: + @brief Calls the verifyAssertion endpoint, which is responsible for authenticating a + user who has IDP-related credentials (an ID Token, an Access Token, etc.) + @param request The request parameters. + @param callback The callback. + */ +- (void)verifyAssertion:(FIRVerifyAssertionRequest *)request + callback:(FIRVerifyAssertionResponseCallback)callback; + +/** @fn verifyCustomToken:callback: + @brief Calls the verifyCustomToken endpoint, which is responsible for authenticating a + user who has BYOAuth credentials (a self-signed token using their BYOAuth private key.) + @param request The request parameters. + @param callback The callback. + */ +- (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request + callback:(FIRVerifyCustomTokenResponseCallback)callback; + +/** @fn verifyPassword:callback: + @brief Calls the verifyPassword endpoint, which is responsible for authenticating a + user who has email and password credentials. + @param request The request parameters. + @param callback The callback. + */ +- (void)verifyPassword:(FIRVerifyPasswordRequest *)request + callback:(FIRVerifyPasswordResponseCallback)callback; + +/** @fn emailLinkSignin:callback: + @brief Calls the emailLinkSignin endpoint, which is responsible for authenticating a + user through passwordless sign-in. + @param request The request parameters. + @param callback The callback. + */ +- (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request + callback:(FIREmailLinkSigninResponseCallback)callback; + +/** @fn secureToken:callback: + @brief Calls the token endpoint, which is responsible for performing STS token exchanges and + token refreshes. + @param request The request parameters. + @param callback The callback. + */ +- (void)secureToken:(FIRSecureTokenRequest *)request + callback:(FIRSecureTokenResponseCallback)callback; + +/** @fn getOOBConfirmationCode:callback: + @brief Calls the getOOBConfirmationCode endpoint, which is responsible for sending email change + request emails, email sign-in link emails, and password reset emails. + @param request The request parameters. + @param callback The callback. + */ +- (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request + callback:(FIRGetOOBConfirmationCodeResponseCallback)callback; + +/** @fn signUpNewUser: + @brief Calls the signUpNewUser endpoint, which is responsible anonymously signing up a user + or signing in a user anonymously. + @param request The request parameters. + @param callback The callback. + */ +- (void)signUpNewUser:(FIRSignUpNewUserRequest *)request + callback:(FIRSignupNewUserCallback)callback; + +/** @fn deleteAccount: + @brief Calls the DeleteAccount endpoint, which is responsible for deleting a user. + @param request The request parameters. + @param callback The callback. + */ +- (void)deleteAccount:(FIRDeleteAccountRequest *)request + callback:(FIRDeleteCallBack)callback; + +#if TARGET_OS_IOS +/** @fn sendVerificationCode:callback: + @brief Calls the sendVerificationCode endpoint, which is responsible for sending the + verification code to a phone number specified in the request parameters. + @param request The request parameters. + @param callback The callback. + */ +- (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request + callback:(FIRSendVerificationCodeResponseCallback)callback; + +/** @fn verifyPhoneNumber:callback: + @brief Calls the verifyPhoneNumber endpoint, which is responsible for sending the verification + code to a phone number specified in the request parameters. + @param request The request parameters. + @param callback The callback. + */ +- (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request + callback:(FIRVerifyPhoneNumberResponseCallback)callback; + +/** @fn verifyClient:callback: + @brief Calls the verifyClient endpoint, which is responsible for sending the silent push + notification used for app validation to the device provided in the request parameters. + @param request The request parameters. + @param callback The callback. + */ +- (void)verifyClient:(FIRVerifyClientRequest *)request + callback:(FIRVerifyClientResponseCallback)callback; +#endif + +/** @fn SignInWithGameCenter:callback: + @brief Calls the SignInWithGameCenter endpoint, which is responsible for authenticating a user + who has Game Center credentials. + @param request The request parameters. + @param callback The callback. + */ +- (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request + callback:(FIRSignInWithGameCenterResponseCallback)callback; + +/** @fn resetPassword:callback + @brief Calls the resetPassword endpoint, which is responsible for resetting a user's password + given an OOB code and new password. + @param request The request parameters. + @param callback The callback. + */ +- (void)resetPassword:(FIRResetPasswordRequest *)request + callback:(FIRResetPasswordCallback)callback; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.m new file mode 100644 index 0000000..d254174 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthBackend.m @@ -0,0 +1,1154 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthBackend.h" + +#import +#import + +#import "FIRAuthErrorUtils.h" +#import "FIRAuthGlobalWorkQueue.h" +#import "FirebaseAuth.h" +#import "FIRAuthRPCRequest.h" +#import "FIRAuthRPCResponse.h" +#import "FIRCreateAuthURIRequest.h" +#import "FIRCreateAuthURIResponse.h" +#import "FIRDeleteAccountRequest.h" +#import "FIRDeleteAccountResponse.h" +#import "FIRGetAccountInfoRequest.h" +#import "FIRGetAccountInfoResponse.h" +#import "FIRSignInWithGameCenterRequest.h" +#import "FIRSignInWithGameCenterResponse.h" +#import "FIRGetOOBConfirmationCodeRequest.h" +#import "FIRGetOOBConfirmationCodeResponse.h" +#import "FIRGetProjectConfigRequest.h" +#import "FIRGetProjectConfigResponse.h" +#import "FIRResetPasswordRequest.h" +#import "FIRResetPasswordResponse.h" +#import "FIRSendVerificationCodeRequest.h" +#import "FIRSendVerificationCodeResponse.h" +#import "FIRSecureTokenRequest.h" +#import "FIRSecureTokenResponse.h" +#import "FIRSetAccountInfoRequest.h" +#import "FIRSetAccountInfoResponse.h" +#import "FIRSignUpNewUserRequest.h" +#import "FIRSignUpNewUserResponse.h" +#import "FIRVerifyAssertionRequest.h" +#import "FIRVerifyAssertionResponse.h" +#import "FIRVerifyClientRequest.h" +#import "FIRVerifyClientResponse.h" +#import "FIRVerifyCustomTokenRequest.h" +#import "FIRVerifyCustomTokenResponse.h" +#import "FIRVerifyPasswordRequest.h" +#import "FIRVerifyPasswordResponse.h" +#import "FIREmailLinkSignInRequest.h" +#import "FIREmailLinkSignInResponse.h" +#import "FIRVerifyPhoneNumberRequest.h" +#import "FIRVerifyPhoneNumberResponse.h" + +#if TARGET_OS_IOS +#import "../AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h" +#import "FIRPhoneAuthProvider.h" +#endif + +/** @var kClientVersionHeader + @brief HTTP header name for the client version. + */ +static NSString *const kClientVersionHeader = @"X-Client-Version"; + +/** @var kIosBundleIdentifierHeader + @brief HTTP header name for iOS bundle ID. + */ +static NSString *const kIosBundleIdentifierHeader = @"X-Ios-Bundle-Identifier"; + +/** @var kFirebaseLocalHeader + @brief HTTP header name for the firebase locale. + */ +static NSString *const kFirebaseLocalHeader = @"X-Firebase-Locale"; + +/** @var kFirebaseAuthCoreFrameworkMarker + @brief The marker in the HTTP header that indicates the request comes from Firebase Auth Core. + */ +static NSString *const kFirebaseAuthCoreFrameworkMarker = @"FirebaseCore-iOS"; + +/** @var kJSONContentType + @brief The value of the HTTP content-type header for JSON payloads. + */ +static NSString *const kJSONContentType = @"application/json"; + +/** @var kErrorDataKey + @brief Key for error data in NSError returned by @c GTMSessionFetcher. + */ +static NSString * const kErrorDataKey = @"data"; + +/** @var kErrorKey + @brief The key for the "error" value in JSON responses from the server. + */ +static NSString *const kErrorKey = @"error"; + +/** @var kErrorsKey + @brief The key for the "errors" value in JSON responses from the server. + */ +static NSString *const kErrorsKey = @"errors"; + +/** @var kReasonKey + @brief The key for the "reason" value in JSON responses from the server. + */ +static NSString *const kReasonKey = @"reason"; + +/** @var kInvalidKeyReasonValue + @brief The value for the "reason" key indicating an invalid API Key was received by the server. + */ +static NSString *const kInvalidKeyReasonValue = @"keyInvalid"; + +/** @var kAppNotAuthorizedReasonValue + @brief The value for the "reason" key indicating the App is not authorized to use Firebase + Authentication. + */ +static NSString *const kAppNotAuthorizedReasonValue = @"ipRefererBlocked"; + +/** @var kErrorMessageKey + @brief The key for an error's "message" value in JSON responses from the server. + */ +static NSString *const kErrorMessageKey = @"message"; + +/** @var kUserNotFoundErrorMessage + @brief This is the error message returned when the user is not found, which means the user + account has been deleted given the token was once valid. + */ +static NSString *const kUserNotFoundErrorMessage = @"USER_NOT_FOUND"; + +/** @var kUserDeletedErrorMessage + @brief This is the error message the server will respond with if the user entered an invalid + email address. + */ +static NSString *const kUserDeletedErrorMessage = @"EMAIL_NOT_FOUND"; + +/** @var kInvalidLocalIDErrorMessage + @brief This is the error message the server responds with if the user local id in the id token + does not exit. + */ +static NSString *const kInvalidLocalIDErrorMessage = @"INVALID_LOCAL_ID"; + +/** @var kUserTokenExpiredErrorMessage + @brief The error returned by the server if the token issue time is older than the account's + valid_since time. + */ +static NSString *const kUserTokenExpiredErrorMessage = @"TOKEN_EXPIRED"; + +/** @var kTooManyRequestsErrorMessage + @brief This is the error message the server will respond with if too many requests were made to + a server method. + */ +static NSString *const kTooManyRequestsErrorMessage = @"TOO_MANY_ATTEMPTS_TRY_LATER"; + +/** @var kInvalidTokenCustomErrorMessage + @brief This is the error message the server will respond with if there is a validation error + with the custom token. + */ +static NSString *const kInvalidCustomTokenErrorMessage = @"INVALID_CUSTOM_TOKEN"; + +/** @var kCustomTokenMismatch + @brief This is the error message the server will respond with if the service account and API key + belong to different projects. + */ +static NSString *const kCustomTokenMismatch = @"CREDENTIAL_MISMATCH"; + +/** @var kInvalidCredentialErrorMessage + @brief This is the error message the server responds with if the IDP token or requestUri is + invalid. + */ +static NSString *const kInvalidCredentialErrorMessage = @"INVALID_IDP_RESPONSE"; + +/** @var kUserDisabledErrorMessage + @brief The error returned by the server if the user account is diabled. + */ +static NSString *const kUserDisabledErrorMessage = @"USER_DISABLED"; + +/** @var kOperationNotAllowedErrorMessage + @brief This is the error message the server will respond with if Admin disables IDP specified by + provider. + */ +static NSString *const kOperationNotAllowedErrorMessage = @"OPERATION_NOT_ALLOWED"; + +/** @var kPasswordLoginDisabledErrorMessage + @brief This is the error message the server responds with if password login is disabled. + */ +static NSString *const kPasswordLoginDisabledErrorMessage = @"PASSWORD_LOGIN_DISABLED"; + +/** @var kEmailAlreadyInUseErrorMessage + @brief This is the error message the server responds with if the email address already exists. + */ +static NSString *const kEmailAlreadyInUseErrorMessage = @"EMAIL_EXISTS"; + +/** @var kInvalidEmailErrorMessage + @brief The error returned by the server if the email is invalid. + */ +static NSString *const kInvalidEmailErrorMessage = @"INVALID_EMAIL"; + +/** @var kInvalidIdentifierErrorMessage + @brief The error returned by the server if the identifier is invalid. + */ +static NSString *const kInvalidIdentifierErrorMessage = @"INVALID_IDENTIFIER"; + +/** @var kWrongPasswordErrorMessage + @brief This is the error message the server will respond with if the user entered a wrong + password. + */ +static NSString *const kWrongPasswordErrorMessage = @"INVALID_PASSWORD"; + +/** @var kCredentialTooOldErrorMessage + @brief This is the error message the server responds with if account change is attempted 5 + minutes after signing in. + */ +static NSString *const kCredentialTooOldErrorMessage = @"CREDENTIAL_TOO_OLD_LOGIN_AGAIN"; + +/** @var kFederatedUserIDAlreadyLinkedMessage + @brief This is the error message the server will respond with if the federated user ID has been + already linked with another account. + */ +static NSString *const kFederatedUserIDAlreadyLinkedMessage = @"FEDERATED_USER_ID_ALREADY_LINKED"; + +/** @var kInvalidUserTokenErrorMessage + @brief This is the error message the server responds with if user's saved auth credential is + invalid, and the user needs to sign in again. + */ +static NSString *const kInvalidUserTokenErrorMessage = @"INVALID_ID_TOKEN"; + +/** @var kWeakPasswordErrorMessagePrefix + @brief This is the prefix for the error message the server responds with if user's new password + to be set is too weak. + */ +static NSString *const kWeakPasswordErrorMessagePrefix = @"WEAK_PASSWORD"; + +/** @var kExpiredActionCodeErrorMessage + @brief This is the error message the server will respond with if the action code is expired. + */ +static NSString *const kExpiredActionCodeErrorMessage = @"EXPIRED_OOB_CODE"; + +/** @var kInvalidActionCodeErrorMessage + @brief This is the error message the server will respond with if the action code is invalid. + */ +static NSString *const kInvalidActionCodeErrorMessage = @"INVALID_OOB_CODE"; + +/** @var kMissingEmailErrorMessage + @brief This is the error message the server will respond with if the email address is missing + during a "send password reset email" attempt. + */ +static NSString *const kMissingEmailErrorMessage = @"MISSING_EMAIL"; + +/** @var kInvalidSenderEmailErrorMessage + @brief This is the error message the server will respond with if the sender email is invalid + during a "send password reset email" attempt. + */ +static NSString *const kInvalidSenderEmailErrorMessage = @"INVALID_SENDER"; + +/** @var kInvalidMessagePayloadErrorMessage + @brief This is the error message the server will respond with if there are invalid parameters in + the payload during a "send password reset email" attempt. + */ +static NSString *const kInvalidMessagePayloadErrorMessage = @"INVALID_MESSAGE_PAYLOAD"; + +/** @var kInvalidRecipientEmailErrorMessage + @brief This is the error message the server will respond with if the recipient email is invalid. + */ +static NSString *const kInvalidRecipientEmailErrorMessage = @"INVALID_RECIPIENT_EMAIL"; + +/** @var kMissingIosBundleIDErrorMessage + @brief This is the error message the server will respond with if iOS bundle ID is missing but + the iOS App store ID is provided. + */ +static NSString *const kMissingIosBundleIDErrorMessage = @"MISSING_IOS_BUNDLE_ID"; + +/** @var kMissingAndroidPackageNameErrorMessage + @brief This is the error message the server will respond with if Android Package Name is missing + but the flag indicating the app should be installed is set to true. + */ +static NSString *const kMissingAndroidPackageNameErrorMessage = @"MISSING_ANDROID_PACKAGE_NAME"; + +/** @var kUnauthorizedDomainErrorMessage + @brief This is the error message the server will respond with if the domain of the continue URL + specified is not whitelisted in the firebase console. + */ +static NSString *const kUnauthorizedDomainErrorMessage = @"UNAUTHORIZED_DOMAIN"; + +/** @var kInvalidDynamicLinkDomainErrorMessage + @brief This is the error message the server will respond with if the dynamic link domain provided + in the request is invalid. + */ +static NSString *const kInvalidDynamicLinkDomainErrorMessage = @"INVALID_DYNAMIC_LINK_DOMAIN"; + +/** @var kInvalidContinueURIErrorMessage + @brief This is the error message the server will respond with if the continue URL provided in + the request is invalid. + */ +static NSString *const kInvalidContinueURIErrorMessage = @"INVALID_CONTINUE_URI"; + +/** @var kMissingContinueURIErrorMessage + @brief This is the error message the server will respond with if there was no continue URI + present in a request that required one. + */ +static NSString *const kMissingContinueURIErrorMessage = @"MISSING_CONTINUE_URI"; + +/** @var kInvalidPhoneNumberErrorMessage + @brief This is the error message the server will respond with if an incorrectly formatted phone + number is provided. + */ +static NSString *const kInvalidPhoneNumberErrorMessage = @"INVALID_PHONE_NUMBER"; + +/** @var kInvalidVerificationCodeErrorMessage + @brief This is the error message the server will respond with if an invalid verification code is + provided. + */ +static NSString *const kInvalidVerificationCodeErrorMessage = @"INVALID_CODE"; + +/** @var kInvalidSessionInfoErrorMessage + @brief This is the error message the server will respond with if an invalid session info + (verification ID) is provided. + */ +static NSString *const kInvalidSessionInfoErrorMessage = @"INVALID_SESSION_INFO"; + +/** @var kSessionExpiredErrorMessage + @brief This is the error message the server will respond with if the SMS code has expired before + it is used. + */ +static NSString *const kSessionExpiredErrorMessage = @"SESSION_EXPIRED"; + +/** @var kMissingAppTokenErrorMessage + @brief This is the error message the server will respond with if the APNS token is missing in a + verifyClient request. + */ +static NSString *const kMissingAppTokenErrorMessage = @"MISSING_IOS_APP_TOKEN"; + +/** @var kMissingAppCredentialErrorMessage + @brief This is the error message the server will respond with if the app token is missing in a + sendVerificationCode request. + */ +static NSString *const kMissingAppCredentialErrorMessage = @"MISSING_APP_CREDENTIAL"; + +/** @var kInvalidAppCredentialErrorMessage + @brief This is the error message the server will respond with if the app credential in a + sendVerificationCode request is invalid. + */ +static NSString *const kInvalidAppCredentialErrorMessage = @"INVALID_APP_CREDENTIAL"; + +/** @var kQuoutaExceededErrorMessage + @brief This is the error message the server will respond with if the quota for SMS text messages + has been exceeded for the project. + */ +static NSString *const kQuoutaExceededErrorMessage = @"QUOTA_EXCEEDED"; + +/** @var kAppNotVerifiedErrorMessage + @brief This is the error message the server will respond with if Firebase could not verify the + app during a phone authentication flow. + */ +static NSString *const kAppNotVerifiedErrorMessage = @"APP_NOT_VERIFIED"; + +/** @var kMissingClientIdentifier + @brief This is the error message the server will respond with if Firebase could not verify the + app during a phone authentication flow when a real phone number is used and app verification + is disabled for testing. + */ +static NSString *const kMissingClientIdentifier = @"MISSING_CLIENT_IDENTIFIER"; + +/** @var kCaptchaCheckFailedErrorMessage + @brief This is the error message the server will respond with if the reCAPTCHA token provided is + invalid. + */ +static NSString *const kCaptchaCheckFailedErrorMessage = @"CAPTCHA_CHECK_FAILED"; + +/** @var gBackendImplementation + @brief The singleton FIRAuthBackendImplementation instance to use. + */ +static id gBackendImplementation; + +/** @class FIRAuthBackendRPCImplementation + @brief The default RPC-based backend implementation. + */ +@interface FIRAuthBackendRPCImplementation : NSObject + +/** @property RPCIssuer + @brief An instance of FIRAuthBackendRPCIssuer for making RPC requests. Allows the RPC + requests/responses to be easily faked. + */ +@property(nonatomic, strong) id RPCIssuer; + +@end + +@implementation FIRAuthBackend + ++ (id)implementation { + if (!gBackendImplementation) { + gBackendImplementation = [[FIRAuthBackendRPCImplementation alloc] init]; + } + return gBackendImplementation; +} + ++ (void)setBackendImplementation:(id)backendImplementation { + gBackendImplementation = backendImplementation; +} + ++ (void)setDefaultBackendImplementationWithRPCIssuer: + (nullable id)RPCIssuer { + FIRAuthBackendRPCImplementation *defaultImplementation = + [[FIRAuthBackendRPCImplementation alloc] init]; + if (RPCIssuer) { + defaultImplementation.RPCIssuer = RPCIssuer; + } + gBackendImplementation = defaultImplementation; +} + ++ (void)createAuthURI:(FIRCreateAuthURIRequest *)request + callback:(FIRCreateAuthURIResponseCallback)callback { + [[self implementation] createAuthURI:request callback:callback]; +} + ++ (void)getAccountInfo:(FIRGetAccountInfoRequest *)request + callback:(FIRGetAccountInfoResponseCallback)callback { + [[self implementation] getAccountInfo:request callback:callback]; +} + ++ (void)getProjectConfig:(FIRGetProjectConfigRequest *)request + callback:(FIRGetProjectConfigResponseCallback)callback { + [[self implementation] getProjectConfig:request callback:callback]; +} + ++ (void)setAccountInfo:(FIRSetAccountInfoRequest *)request + callback:(FIRSetAccountInfoResponseCallback)callback { + [[self implementation] setAccountInfo:request callback:callback]; +} + ++ (void)verifyAssertion:(FIRVerifyAssertionRequest *)request + callback:(FIRVerifyAssertionResponseCallback)callback { + [[self implementation] verifyAssertion:request callback:callback]; +} + ++ (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request + callback:(FIRVerifyCustomTokenResponseCallback)callback { + [[self implementation] verifyCustomToken:request callback:callback]; +} + ++ (void)verifyPassword:(FIRVerifyPasswordRequest *)request + callback:(FIRVerifyPasswordResponseCallback)callback { + [[self implementation] verifyPassword:request callback:callback]; +} + ++ (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request + callback:(FIREmailLinkSigninResponseCallback)callback { + [[self implementation] emailLinkSignin:request callback:callback]; +} + ++ (void)secureToken:(FIRSecureTokenRequest *)request + callback:(FIRSecureTokenResponseCallback)callback { + [[self implementation] secureToken:request callback:callback]; +} + ++ (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request + callback:(FIRGetOOBConfirmationCodeResponseCallback)callback { + [[self implementation] getOOBConfirmationCode:request callback:callback]; +} + ++ (void)signUpNewUser:(FIRSignUpNewUserRequest *)request + callback:(FIRSignupNewUserCallback)callback { + [[self implementation] signUpNewUser:request callback:callback]; +} + ++ (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback { + [[self implementation] deleteAccount:request callback:callback]; +} + ++ (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request + callback:(FIRSignInWithGameCenterResponseCallback)callback { + [[self implementation] signInWithGameCenter:request callback:callback]; +} + +#if TARGET_OS_IOS ++ (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request + callback:(FIRSendVerificationCodeResponseCallback)callback { + [[self implementation] sendVerificationCode:request callback:callback]; +} + ++ (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request + callback:(FIRVerifyPhoneNumberResponseCallback)callback { + [[self implementation] verifyPhoneNumber:request callback:callback]; +} + ++ (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback { + [[self implementation] verifyClient:request callback:callback]; +} +#endif + ++ (void)resetPassword:(FIRResetPasswordRequest *)request + callback:(FIRResetPasswordCallback)callback { + [[self implementation] resetPassword:request callback:callback]; +} + ++ (NSString *)authUserAgent { + return [NSString stringWithFormat:@"FirebaseAuth.iOS/%s %@", + FirebaseAuthVersionStr, GTMFetcherStandardUserAgentString(nil)]; +} + +@end + +@interface FIRAuthBackendRPCIssuerImplementation : NSObject +@end + +@implementation FIRAuthBackendRPCIssuerImplementation { + /** @var The session fetcher service. + */ + GTMSessionFetcherService *_fetcherService; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _fetcherService = [[GTMSessionFetcherService alloc] init]; + _fetcherService.userAgent = [FIRAuthBackend authUserAgent]; + _fetcherService.callbackQueue = FIRAuthGlobalWorkQueue(); + + // Avoid reusing the session to prevent + // https://github.com/firebase/firebase-ios-sdk/issues/1261 + _fetcherService.reuseSession = NO; + } + return self; +} + +- (void)asyncPostToURLWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + URL:(NSURL *)URL + body:(nullable NSData *)body + contentType:(NSString *)contentType + completionHandler:(void (^)(NSData *_Nullable, + NSError *_Nullable))handler { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; + [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; + NSString *additionalFrameworkMarker = requestConfiguration.additionalFrameworkMarker ?: + kFirebaseAuthCoreFrameworkMarker; + NSString *clientVersion = [NSString stringWithFormat:@"iOS/FirebaseSDK/%s/%@", + FirebaseAuthVersionStr, + additionalFrameworkMarker]; + [request setValue:clientVersion forHTTPHeaderField:kClientVersionHeader]; + NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier]; + [request setValue:bundleID forHTTPHeaderField:kIosBundleIdentifierHeader]; + + NSArray *preferredLocalizations = [NSBundle mainBundle].preferredLocalizations; + if (preferredLocalizations.count) { + NSString *acceptLanguage = preferredLocalizations.firstObject; + [request setValue:acceptLanguage forHTTPHeaderField:@"Accept-Language"]; + } + NSString *languageCode = requestConfiguration.languageCode; + if (languageCode.length) { + [request setValue:languageCode forHTTPHeaderField:kFirebaseLocalHeader]; + } + GTMSessionFetcher *fetcher = [_fetcherService fetcherWithRequest:request]; + fetcher.bodyData = body; + [fetcher beginFetchWithCompletionHandler:handler]; +} + +@end + +@implementation FIRAuthBackendRPCImplementation + +- (instancetype)init { + self = [super init]; + if (self) { + _RPCIssuer = [[FIRAuthBackendRPCIssuerImplementation alloc] init]; + } + return self; +} + +- (void)createAuthURI:(FIRCreateAuthURIRequest *)request + callback:(FIRCreateAuthURIResponseCallback)callback { + FIRCreateAuthURIResponse *response = [[FIRCreateAuthURIResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)getAccountInfo:(FIRGetAccountInfoRequest *)request + callback:(FIRGetAccountInfoResponseCallback)callback { + FIRGetAccountInfoResponse *response = [[FIRGetAccountInfoResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)getProjectConfig:(FIRGetProjectConfigRequest *)request + callback:(FIRGetProjectConfigResponseCallback)callback { + FIRGetProjectConfigResponse *response = [[FIRGetProjectConfigResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)setAccountInfo:(FIRSetAccountInfoRequest *)request + callback:(FIRSetAccountInfoResponseCallback)callback { + FIRSetAccountInfoResponse *response = [[FIRSetAccountInfoResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)verifyAssertion:(FIRVerifyAssertionRequest *)request + callback:(FIRVerifyAssertionResponseCallback)callback { + FIRVerifyAssertionResponse *response = [[FIRVerifyAssertionResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + return; + } + callback(response, nil); + }]; +} + +- (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request + callback:(FIRVerifyCustomTokenResponseCallback)callback { + FIRVerifyCustomTokenResponse *response = [[FIRVerifyCustomTokenResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)verifyPassword:(FIRVerifyPasswordRequest *)request + callback:(FIRVerifyPasswordResponseCallback)callback { + FIRVerifyPasswordResponse *response = [[FIRVerifyPasswordResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request + callback:(FIREmailLinkSigninResponseCallback)callback { + FIREmailLinkSignInResponse *response = [[FIREmailLinkSignInResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)secureToken:(FIRSecureTokenRequest *)request + callback:(FIRSecureTokenResponseCallback)callback { + FIRSecureTokenResponse *response = [[FIRSecureTokenResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request + callback:(FIRGetOOBConfirmationCodeResponseCallback)callback { + FIRGetOOBConfirmationCodeResponse *response = [[FIRGetOOBConfirmationCodeResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)signUpNewUser:(FIRSignUpNewUserRequest *)request + callback:(FIRSignupNewUserCallback)callback{ + FIRSignUpNewUserResponse *response = [[FIRSignUpNewUserResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, nil); + } + }]; +} + +- (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback { + FIRDeleteAccountResponse *response = [[FIRDeleteAccountResponse alloc] init]; + [self postWithRequest:request response:response callback:callback]; +} + +#if TARGET_OS_IOS +- (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request + callback:(FIRSendVerificationCodeResponseCallback)callback { + FIRSendVerificationCodeResponse *response = [[FIRSendVerificationCodeResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + } else { + callback(response, error); + } + }]; +} + +- (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request + callback:(FIRVerifyPhoneNumberResponseCallback)callback { + FIRVerifyPhoneNumberResponse *response = [[FIRVerifyPhoneNumberResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + return; + } + // Check whether or not the successful response is actually the special case phone auth flow + // that returns a temporary proof and phone number. + if (response.phoneNumber.length && response.temporaryProof.length) { + FIRPhoneAuthCredential *credential = + [[FIRPhoneAuthCredential alloc] initWithTemporaryProof:response.temporaryProof + phoneNumber:response.phoneNumber + providerID:FIRPhoneAuthProviderID]; + callback(nil, + [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:nil + credential:credential]); + return; + } + callback(response, nil); + }]; +} + +- (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback { + FIRVerifyClientResponse *response = [[FIRVerifyClientResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + return; + } + callback(response, nil); + }]; +} +#endif + +- (void)resetPassword:(FIRResetPasswordRequest *)request + callback:(FIRResetPasswordCallback)callback { + FIRResetPasswordResponse *response = [[FIRResetPasswordResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + callback(nil, error); + return; + } + callback(response, nil); + }]; +} + +- (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request + callback:(FIRSignInWithGameCenterResponseCallback)callback { + FIRSignInWithGameCenterResponse *response = [[FIRSignInWithGameCenterResponse alloc] init]; + [self postWithRequest:request response:response callback:^(NSError *error) { + if (error) { + if (callback) { + callback(nil, error); + } + } else { + if (callback) { + callback(response, nil); + } + } + }]; +} + +#pragma mark - Generic RPC handling methods + +/** @fn postWithRequest:response:callback: + @brief Calls the RPC using HTTP POST. + @remarks Possible error responses: + @see FIRAuthInternalErrorCodeRPCRequestEncodingError + @see FIRAuthInternalErrorCodeJSONSerializationError + @see FIRAuthInternalErrorCodeNetworkError + @see FIRAuthInternalErrorCodeUnexpectedErrorResponse + @see FIRAuthInternalErrorCodeUnexpectedResponse + @see FIRAuthInternalErrorCodeRPCResponseDecodingError + @param request The request. + @param response The empty response to be filled. + @param callback The callback for both success and failure. + */ +- (void)postWithRequest:(id)request + response:(id)response + callback:(void (^)(NSError *error))callback { + NSError *error; + NSData *bodyData; + if ([request containsPostBody]) { + id postBody = [request unencodedHTTPRequestBodyWithError:&error]; + if (!postBody) { + callback([FIRAuthErrorUtils RPCRequestEncodingErrorWithUnderlyingError:error]); + return; + } + + NSJSONWritingOptions JSONWritingOptions = 0; + #if DEBUG + JSONWritingOptions |= NSJSONWritingPrettyPrinted; + #endif + + if ([NSJSONSerialization isValidJSONObject:postBody]) { + bodyData = [NSJSONSerialization dataWithJSONObject:postBody + options:JSONWritingOptions + error:&error]; + if (!bodyData) { + // This is an untested case. This happens exclusively when there is an error in the framework + // implementation of dataWithJSONObject:options:error:. This shouldn't normally occur as + // isValidJSONObject: should return NO in any case we should encounter an error. + error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:error]; + } + } else { + error = [FIRAuthErrorUtils JSONSerializationErrorForUnencodableType]; + } + if (!bodyData) { + callback(error); + return; + } + } + + [_RPCIssuer asyncPostToURLWithRequestConfiguration:[request requestConfiguration] + URL:[request requestURL] + body:bodyData + contentType:kJSONContentType + completionHandler:^(NSData *data, NSError *error) { + // If there is an error with no body data at all, then this must be a network error. + if (error && !data) { + callback([FIRAuthErrorUtils networkErrorWithUnderlyingError:error]); + return; + } + + // Try to decode the HTTP response data which may contain either a successful response or error + // message. + NSError *jsonError; + NSDictionary * dictionary = + [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingMutableLeaves + error:&jsonError]; + if (!dictionary) { + if (error) { + // We have an error, but we couldn't decode the body, so we have no additional information + // other than the raw response and the original NSError (the jsonError is infered by the + // error code (FIRAuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.) + callback([FIRAuthErrorUtils unexpectedErrorResponseWithData:data underlyingError:error]); + } else { + // This is supposed to be a "successful" response, but we couldn't deserialize the body. + callback([FIRAuthErrorUtils unexpectedResponseWithData:data underlyingError:jsonError]); + } + return; + } + if (![dictionary isKindOfClass:[NSDictionary class]]) { + if (error) { + callback([FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:dictionary]); + } else { + callback([FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:dictionary]); + } + return; + } + + // At this point we either have an error with successfully decoded details in the body, or we + // have a response which must pass further validation before we know it's truly successful. + // We deal with the case where we have an error with successfully decoded error details first: + if (error) { + NSDictionary *errorDictionary = dictionary[kErrorKey]; + if ([errorDictionary isKindOfClass:[NSDictionary class]]) { + id errorMessage = errorDictionary[kErrorMessageKey]; + if ([errorMessage isKindOfClass:[NSString class]]) { + NSString *errorMessageString = (NSString *)errorMessage; + + // Contruct client error. + NSError *clientError = [[self class] clientErrorWithServerErrorMessage:errorMessageString + errorDictionary:errorDictionary + response:response]; + if (clientError) { + callback(clientError); + return; + } + } + // Not a message we know, return the message directly. + if (errorMessage) { + NSError *unexpecterErrorResponse = + [FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:errorDictionary]; + callback(unexpecterErrorResponse); + return; + } + } + // No error message at all, return the decoded response. + callback([FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:dictionary]); + return; + } + + // Finally, we try to populate the response object with the JSON values. + if (![response setWithDictionary:dictionary error:&error]) { + callback([FIRAuthErrorUtils RPCResponseDecodingErrorWithDeserializedResponse:dictionary + underlyingError:error]); + return; + } + + // Success! The response object originally passed in can be used by the caller. + callback(nil); + }]; +} + +/** @fn clientErrorWithServerErrorMessage:errorDictionary: + @brief Translates known server errors to client errors. + @param serverErrorMessage The error message from the server. + @param errorDictionary The error part of the response from the server. + @param response The response from the server RPC. + @return A client error, if any. + */ ++ (nullable NSError *)clientErrorWithServerErrorMessage:(NSString *)serverErrorMessage + errorDictionary:(NSDictionary *)errorDictionary + response:(id)response { + NSString *shortErrorMessage = serverErrorMessage; + NSString *serverDetailErrorMessage; + NSRange colonRange = [serverErrorMessage rangeOfString:@":"]; + if (colonRange.location != NSNotFound) { + shortErrorMessage = [serverErrorMessage substringToIndex:colonRange.location]; + shortErrorMessage = + [shortErrorMessage stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; + serverDetailErrorMessage = [serverErrorMessage substringFromIndex:colonRange.location + 1]; + serverDetailErrorMessage = [serverDetailErrorMessage stringByTrimmingCharactersInSet: + [NSCharacterSet whitespaceCharacterSet]]; + } + + // Delegate the responsibility for constructing the client error to the response object, + // if possible. + SEL clientErrorWithServerErrorMessageSelector = + @selector(clientErrorWithShortErrorMessage:detailErrorMessage:); + if ([response respondsToSelector:clientErrorWithServerErrorMessageSelector]) { + NSError *error = [response clientErrorWithShortErrorMessage:shortErrorMessage + detailErrorMessage:serverDetailErrorMessage]; + if (error) { + return error; + } + } + + if ([shortErrorMessage isEqualToString:kUserNotFoundErrorMessage]) { + return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kUserDeletedErrorMessage]) { + return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidLocalIDErrorMessage]) { + // This case shouldn't be necessary but it is for now: b/27908364 . + return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kUserTokenExpiredErrorMessage]) { + return [FIRAuthErrorUtils userTokenExpiredErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kTooManyRequestsErrorMessage]) { + return [FIRAuthErrorUtils tooManyRequestsErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidCustomTokenErrorMessage]) { + return [FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kCustomTokenMismatch]) { + return [FIRAuthErrorUtils customTokenMistmatchErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidCredentialErrorMessage]) { + return [FIRAuthErrorUtils invalidCredentialErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kUserDisabledErrorMessage]) { + return [FIRAuthErrorUtils userDisabledErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kOperationNotAllowedErrorMessage]) { + return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kPasswordLoginDisabledErrorMessage]) { + return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kEmailAlreadyInUseErrorMessage]) { + return [FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:nil]; + } + + if ([shortErrorMessage isEqualToString:kInvalidEmailErrorMessage]) { + return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage]; + } + + // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are + // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in this + // case. + if ([shortErrorMessage isEqualToString:kInvalidIdentifierErrorMessage]) { + return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kWrongPasswordErrorMessage]) { + return [FIRAuthErrorUtils wrongPasswordErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kCredentialTooOldErrorMessage]) { + return [FIRAuthErrorUtils requiresRecentLoginErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidUserTokenErrorMessage]) { + return [FIRAuthErrorUtils invalidUserTokenErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kFederatedUserIDAlreadyLinkedMessage]) { + return [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:serverDetailErrorMessage + credential:nil]; + } + + if ([shortErrorMessage isEqualToString:kWeakPasswordErrorMessagePrefix]) { + return [FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kExpiredActionCodeErrorMessage]) { + return [FIRAuthErrorUtils expiredActionCodeErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidActionCodeErrorMessage]) { + return [FIRAuthErrorUtils invalidActionCodeErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingEmailErrorMessage]) { + return [FIRAuthErrorUtils missingEmailErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidSenderEmailErrorMessage]) { + return [FIRAuthErrorUtils invalidSenderErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidMessagePayloadErrorMessage]) { + return [FIRAuthErrorUtils invalidMessagePayloadErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidRecipientEmailErrorMessage]) { + return [FIRAuthErrorUtils invalidRecipientEmailErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingIosBundleIDErrorMessage]) { + return [FIRAuthErrorUtils missingIosBundleIDErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingAndroidPackageNameErrorMessage]) { + return [FIRAuthErrorUtils missingAndroidPackageNameErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kUnauthorizedDomainErrorMessage]) { + return [FIRAuthErrorUtils unauthorizedDomainErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidContinueURIErrorMessage]) { + return [FIRAuthErrorUtils invalidContinueURIErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidDynamicLinkDomainErrorMessage]) { + return [FIRAuthErrorUtils invalidDynamicLinkDomainErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingContinueURIErrorMessage]) { + return [FIRAuthErrorUtils missingContinueURIErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidPhoneNumberErrorMessage]) { + return [FIRAuthErrorUtils invalidPhoneNumberErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidSessionInfoErrorMessage]) { + return [FIRAuthErrorUtils invalidVerificationIDErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidVerificationCodeErrorMessage]) { + return [FIRAuthErrorUtils invalidVerificationCodeErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kSessionExpiredErrorMessage]) { + return [FIRAuthErrorUtils sessionExpiredErrorWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingAppTokenErrorMessage]) { + return [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:nil]; + } + + if ([shortErrorMessage isEqualToString:kMissingAppCredentialErrorMessage]) { + return [FIRAuthErrorUtils missingAppCredentialWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kInvalidAppCredentialErrorMessage]) { + return [FIRAuthErrorUtils invalidAppCredentialWithMessage:serverDetailErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kQuoutaExceededErrorMessage]) { + return [FIRAuthErrorUtils quotaExceededErrorWithMessage:serverErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kAppNotVerifiedErrorMessage]) { + return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:serverErrorMessage]; + } + + if ([shortErrorMessage isEqualToString:kMissingClientIdentifier]) { + return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:@"Missing app verification via" + " reCAPTCHA or APNS token. Please verify that appVerificationDisabledForTesting is not" + " enabled when testing with a phone number that is not marked as a test Phone number in the" + " app console."]; + } + + if ([shortErrorMessage isEqualToString:kCaptchaCheckFailedErrorMessage]) { + return [FIRAuthErrorUtils captchaCheckFailedErrorWithMessage:serverErrorMessage]; + } + + // In this case we handle an error that might be specified in the underlying errors dictionary, + // the error message in determined based on the @c reason key in the dictionary. + if (errorDictionary[kErrorsKey]) { + // Check for underlying error with reason = keyInvalid; + id underlyingErrors = errorDictionary[kErrorsKey]; + if ([underlyingErrors isKindOfClass:[NSArray class]]) { + NSArray *underlyingErrorsArray = (NSArray *)underlyingErrors; + for (id underlyingError in underlyingErrorsArray) { + if ([underlyingError isKindOfClass:[NSDictionary class]]) { + NSDictionary *underlyingErrorDictionary = (NSDictionary *)underlyingError; + NSString *reason = underlyingErrorDictionary[kReasonKey]; + if ([reason hasPrefix:kInvalidKeyReasonValue]) { + return [FIRAuthErrorUtils invalidAPIKeyError]; + } + if ([reason isEqualToString:kAppNotAuthorizedReasonValue]) { + return [FIRAuthErrorUtils appNotAuthorizedError]; + } + } + } + } + } + return nil; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCRequest.h new file mode 100644 index 0000000..9ca4f44 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCRequest.h @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRAuthRequestConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/** @protocol FIRAuthRPCRequest + @brief The generic interface for an RPC request needed by @c FIRAuthBackend. + */ +@protocol FIRAuthRPCRequest + +/** @fn requestURL + @brief Gets the request's full URL. + */ +- (NSURL *)requestURL; + +@optional + +/** @fn containsPostBody + @brief Returns whether the request contains a post body or not. Requests without a post body + are get requests. + @remarks The default implementation returns YES. + */ +- (BOOL)containsPostBody; + +/** @fn UnencodedHTTPRequestBodyWithError: + @brief Creates unencoded HTTP body representing the request. + @param error An out field for an error which occurred constructing the request. + @return The HTTP body data representing the request before any encoding, or nil for error. + */ +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error; + +/** @fn requestConfiguration + @brief Obtains the request configurations if available. + @return Returns the request configurations. + */ +- (FIRAuthRequestConfiguration *)requestConfiguration; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCResponse.h new file mode 100644 index 0000000..2b26161 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRPCResponse.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** @protocol FIRAuthRPCResponse + @brief The generic interface for an RPC response needed by @c FIRAuthBackend. + */ +@protocol FIRAuthRPCResponse + +/** @fn setFieldsWithDictionary:error: + @brief Sets the response instance from the decoded JSON response. + @param dictionary The dictionary decoded from HTTP JSON response. + @param error An out field for an error which occurred constructing the request. + @return Whether the operation was successful or not. + */ +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error; + +@optional + +/** @fn clientErrorWithshortErrorMessage:detailErrorMessage + @brief This optional method allows response classes to create client errors given a short error + message and a detail error message from the server. + @param shortErrorMessage The short error message from the server. + @param detailErrorMessage The detailed error message from the server. + @return A client error, if any. + */ +- (nullable NSError *)clientErrorWithShortErrorMessage:(NSString *)shortErrorMessage + detailErrorMessage:(nullable NSString *)detailErrorMessage; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.h new file mode 100644 index 0000000..f24f23a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthRequestConfiguration + @brief Defines configurations to be added to a request to Firebase Auth's backend. + */ +@interface FIRAuthRequestConfiguration : NSObject + +/** @property APIKey + @brief The Firebase Auth API key used in the request. + */ +@property(nonatomic, copy, readonly) NSString *APIKey; + +/** @property LanguageCode + @brief The language code used in the request. + */ +@property(nonatomic, copy, nullable) NSString *languageCode; + +/** @property additionalFrameworkMarker + @brief Additional framework marker that will be added as part of the header of every request. + */ +@property(nonatomic, copy, nullable) NSString *additionalFrameworkMarker; + +- (nullable instancetype)init NS_UNAVAILABLE; + +/** @fn initWithRequestClass:APIKey:authLanguage: + @brief Designated initializer. + @param APIKey The API key to be used in the request. + */ +- (nullable instancetype)initWithAPIKey:(NSString *)APIKey NS_DESIGNATED_INITIALIZER; +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.m new file mode 100644 index 0000000..a4ee5dd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.m @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAuthRequestConfiguration.h" +#import "FIRAuthExceptionUtils.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRAuthRequestConfiguration + +- (nullable instancetype)initWithAPIKey:(NSString *)APIKey { + self = [super init]; + if (self) { + _APIKey = [APIKey copy]; + } + return self; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.h new file mode 100644 index 0000000..a4fb6f5 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.h @@ -0,0 +1,88 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRCreateAuthURIRequest + @brief Represents the parameters for the createAuthUri endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/createAuthUri + */ +@interface FIRCreateAuthURIRequest : FIRIdentityToolkitRequest + +/** @property identifier + @brief The email or federated ID of the user. + */ +@property(nonatomic, copy) NSString *identifier; + +/** @property continueURI + @brief The URI to which the IDP redirects the user after the federated login flow. + */ +@property(nonatomic, copy) NSString *continueURI; + +/** @property openIDRealm + @brief Optional realm for OpenID protocol. The sub string "scheme://domain:port" of the param + "continueUri" is used if this is not set. + */ +@property(nonatomic, copy, nullable) NSString *openIDRealm; + +/** @property providerID + @brief The IdP ID. For white listed IdPs it's a short domain name e.g. google.com, aol.com, + live.net and yahoo.com. For other OpenID IdPs it's the OP identifier. + */ +@property(nonatomic, copy, nullable) NSString *providerID; + +/** @property clientID + @brief The relying party OAuth client ID. + */ +@property(nonatomic, copy, nullable) NSString *clientID; + +/** @property context + @brief The opaque value used by the client to maintain context info between the authentication + request and the IDP callback. + */ +@property(nonatomic, copy, nullable) NSString *context; + +/** @property appID + @brief The iOS client application's bundle identifier. + */ +@property(nonatomic, copy, nullable) NSString *appID; + +/** @fn initWithEndpoint:requestConfiguration:requestConfiguration. + @brief Please use initWithIdentifier:continueURI:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithIdentifier:continueURI:requestConfiguration: + @brief Designated initializer. + @param identifier The email or federated ID of the user. + @param continueURI The URI to which the IDP redirects the user after the federated login flow. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithIdentifier:(NSString *)identifier + continueURI:(NSString *)continueURI + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.m new file mode 100644 index 0000000..dae46fb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.m @@ -0,0 +1,95 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRCreateAuthURIRequest.h" + +/** @var kCreateAuthURIEndpoint + @brief The "createAuthUri" endpoint. + */ +static NSString *const kCreateAuthURIEndpoint = @"createAuthUri"; + +/** @var kProviderIDKey + @brief The key for the "providerId" value in the request. + */ +static NSString *const kProviderIDKey = @"providerId"; + +/** @var kIdentifierKey + @brief The key for the "identifier" value in the request. + */ +static NSString *const kIdentifierKey = @"identifier"; + +/** @var kContinueURIKey + @brief The key for the "continueUri" value in the request. + */ +static NSString *const kContinueURIKey = @"continueUri"; + +/** @var kOpenIDRealmKey + @brief The key for the "openidRealm" value in the request. + */ +static NSString *const kOpenIDRealmKey = @"openidRealm"; + +/** @var kClientIDKey + @brief The key for the "clientId" value in the request. + */ +static NSString *const kClientIDKey = @"clientId"; + +/** @var kContextKey + @brief The key for the "context" value in the request. + */ +static NSString *const kContextKey = @"context"; + +/** @var kAppIDKey + @brief The key for the "appId" value in the request. + */ +static NSString *const kAppIDKey = @"appId"; + +@implementation FIRCreateAuthURIRequest + +- (nullable instancetype)initWithIdentifier:(NSString *)identifier + continueURI:(NSString *)continueURI + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kCreateAuthURIEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _identifier = [identifier copy]; + _continueURI = [continueURI copy]; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [@{ + kIdentifierKey : _identifier, + kContinueURIKey : _continueURI + } mutableCopy]; + if (_providerID) { + postBody[kProviderIDKey] = _providerID; + } + if (_openIDRealm) { + postBody[kOpenIDRealmKey] = _openIDRealm; + } + if (_clientID) { + postBody[kClientIDKey] = _clientID; + } + if (_context) { + postBody[kContextKey] = _context; + } + if (_appID) { + postBody[kAppIDKey] = _appID; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.h new file mode 100644 index 0000000..8e8f7b0 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.h @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRCreateAuthURIResponse + @brief Represents the parameters for the createAuthUri endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/createAuthUri + */ +@interface FIRCreateAuthURIResponse : NSObject + +/** @property authUri + @brief The URI used by the IDP to authenticate the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *authURI; + +/** @property registered + @brief Whether the user is registered if the identifier is an email. + */ +@property(nonatomic, assign, readonly) BOOL registered; + +/** @property providerId + @brief The provider ID of the auth URI. + */ +@property(nonatomic, strong, readonly, nullable) NSString *providerID; + +/** @property forExistingProvider + @brief True if the authUri is for user's existing provider. + */ +@property(nonatomic, assign, readonly) BOOL forExistingProvider; + +/** @property allProviders + @brief A list of provider IDs the passed @c identifier could use to sign in with. + */ +@property(nonatomic, copy, readonly, nullable) NSArray *allProviders; + +/** @property signinMethods + @brief A list of sign-in methods available for the passed @c identifier. + */ +@property(nonatomic, copy, readonly, nullable) NSArray *signinMethods; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.m new file mode 100644 index 0000000..6f2937f --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.m @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRCreateAuthURIResponse.h" + +@implementation FIRCreateAuthURIResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _providerID = [dictionary[@"providerId"] copy]; + _authURI = [dictionary[@"authUri"] copy]; + _registered = [dictionary[@"registered"] boolValue]; + _forExistingProvider = [dictionary[@"forExistingProvider"] boolValue]; + _allProviders = [dictionary[@"allProviders"] copy]; + _signinMethods = [dictionary[@"signinMethods"] copy]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.h new file mode 100644 index 0000000..89a7d26 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRDeleteAccountRequest + @brief Represents the parameters for the deleteAccount endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/deleteAccount + */ +@interface FIRDeleteAccountRequest : FIRIdentityToolkitRequest + +/** @fn initWithEndpoint:requestConfiguration:requestConfiguration. + @brief Please use initWitLocalID:accessToken:requestConfiguration instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWitLocalID:accessToken:requestConfiguration. + @brief Designated initializer. + @param localID The local ID. + @param accessToken The access token. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWitLocalID:(NSString *)localID + accessToken:(NSString *)accessToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.m new file mode 100644 index 0000000..2222210 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.m @@ -0,0 +1,65 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDeleteAccountRequest.h" + +/** @var kCreateAuthURIEndpoint + @brief The "deleteAccount" endpoint. + */ +static NSString *const kDeleteAccountEndpoint = @"deleteAccount"; + +/** @var kIDTokenKey + @brief The key for the "idToken" value in the request. This is actually the STS Access Token, + despite it's confusing (backwards compatiable) parameter name. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kLocalIDKey + @brief The key for the "localID" value in the request. + */ +static NSString *const kLocalIDKey = @"localId"; + +@implementation FIRDeleteAccountRequest { + /** @var _accessToken + @brief The STS Access Token of the authenticated user. + */ + NSString *_accessToken; + + /** @var _localID + @brief The localID of the user. + */ + NSString *_localID; +} + +- (nullable instancetype)initWitLocalID:(NSString *)localID + accessToken:(NSString *)accessToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kDeleteAccountEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _localID = [localID copy]; + _accessToken = [accessToken copy]; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + postBody[kIDTokenKey] = _accessToken; + postBody[kLocalIDKey] = _localID; + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.h new file mode 100644 index 0000000..59226d6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +/** @class FIRDeleteAccountResponse + @brief Represents the response from the deleteAccount endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/deleteAccount + */ +@interface FIRDeleteAccountResponse : NSObject +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.m new file mode 100644 index 0000000..ae98175 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.m @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDeleteAccountResponse.h" + +@implementation FIRDeleteAccountResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.h new file mode 100644 index 0000000..e1b10d8 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.h @@ -0,0 +1,66 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIREmailLinkSignInRequest + @brief Represents the parameters for the emailLinkSignin endpoint. + */ +@interface FIREmailLinkSignInRequest : FIRIdentityToolkitRequest + +#pragma mark - Components of "postBody" + +/** @property email + @brief The email identifier used to complete the email link sign-in. + */ +@property(nonatomic, copy, readonly) NSString *email; + +/** @property oobCode + @brief The OOB code used to complete the email link sign-in flow. + */ +@property(nonatomic, copy, readonly) NSString *oobCode; + +/** @property idToken + @brief The ID Token code potentially used to complete the email link sign-in flow. + */ +@property(nonatomic, copy) NSString *IDToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithProviderID:requestConfifuration instead. + */ +- (instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration NS_UNAVAILABLE; + +/** @fn initWithProviderID:requestConfifuration + @brief Designated initializer. + @param email The email identifier used to complete hte email link sign-in flow. + @param oobCode The OOB code used to complete the email link sign-in flow. + @param requestConfiguration An object containing configurations to be added to the request. + + */ +- (instancetype)initWithEmail:(NSString *)email + oobCode:(NSString *)oobCode + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.m new file mode 100644 index 0000000..9787e8e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.m @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIREmailLinkSignInRequest.h" + +/** @var kEmailLinkSigninEndpoint + @brief The "EmailLinkSignin" endpoint. + */ +static NSString *const kEmailLinkSigninEndpoint = @"emailLinkSignin"; + +/** @var kEmailKey + @brief The key for the "identifier" value in the request. + */ +static NSString *const kEmailKey = @"email"; + +/** @var kEmailLinkKey + @brief The key for the "emailLink" value in the request. + */ +static NSString *const kOOBCodeKey = @"oobCode"; + +/** @var kIDTokenKey + @brief The key for the "IDToken" value in the request. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kPostBodyKey + @brief The key for the "postBody" value in the request. + */ +static NSString *const kPostBodyKey = @"postBody"; + +@implementation FIREmailLinkSignInRequest + +- (instancetype)initWithEmail:(NSString *)email + oobCode:(NSString *)oobCode + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kEmailLinkSigninEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _email = email; + _oobCode = oobCode; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [@{ + kEmailKey : _email, + kOOBCodeKey : _oobCode, + } mutableCopy]; + + if (_IDToken) { + postBody[kIDTokenKey] = _IDToken; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.h new file mode 100644 index 0000000..df0a127 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.h @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyAssertionResponse + @brief Represents the response from the emailLinkSignin endpoint. + */ +@interface FIREmailLinkSignInResponse : NSObject + +/** @property IDToken + @brief The ID token in the email link sign-in response. + */ +@property(nonatomic, copy, readonly) NSString *IDToken; + +/** @property email + @brief The email returned by the IdP. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property refreshToken + @brief The refreshToken returned by the server. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property isNewUser + @brief Flag indicating that the user signing in is a new user and not a returning user. + */ +@property(nonatomic, assign) BOOL isNewUser; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.m new file mode 100644 index 0000000..cd36d41 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.m @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIREmailLinkSignInResponse.h" + +@implementation FIREmailLinkSignInResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _email = [dictionary[@"email"] copy]; + _IDToken = [dictionary[@"idToken"] copy]; + _isNewUser = [dictionary[@"isNewUser"] boolValue]; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.h new file mode 100644 index 0000000..a5a8a20 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGetAccountInfoRequest + @brief Represents the parameters for the getAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/getAccountInfo + */ +@interface FIRGetAccountInfoRequest : FIRIdentityToolkitRequest + +/** @property accessToken + @brief The STS Access Token for the authenticated user. + */ +@property(nonatomic, copy) NSString *accessToken; + +/** @fn initWithEndpoint:requestConfiguration:requestConfiguration + @brief Please use initWithAccessToken:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithAccessToken:requestConfiguration + @brief Designated initializer. + @param accessToken The Access Token of the authenticated user. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithAccessToken:(NSString *)accessToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.m new file mode 100644 index 0000000..fde79fb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.m @@ -0,0 +1,48 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetAccountInfoRequest.h" + +/** @var kGetAccountInfoEndpoint + @brief The "getAccountInfo" endpoint. + */ +static NSString *const kGetAccountInfoEndpoint = @"getAccountInfo"; + +/** @var kIDTokenKey + @brief The key for the "idToken" value in the request. This is actually the STS Access Token, + despite it's confusing (backwards compatiable) parameter name. + */ +static NSString *const kIDTokenKey = @"idToken"; + +@implementation FIRGetAccountInfoRequest + +- (nullable instancetype)initWithAccessToken:(NSString *)accessToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kGetAccountInfoEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _accessToken = [accessToken copy]; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + return @{ + kIDTokenKey : _accessToken + }; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.h new file mode 100644 index 0000000..6c30dbe --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.h @@ -0,0 +1,156 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGetAccountInfoResponseProviderUserInfo + @brief Represents the provider user info part of the response from the getAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/getAccountInfo + */ +@interface FIRGetAccountInfoResponseProviderUserInfo : NSObject + +/** @property providerID + @brief The ID of the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *providerID; + +/** @property displayName + @brief The user's display name at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property photoURL + @brief The user's photo URL at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSURL *photoURL; + +/** @property federatedID + @brief The user's identifier at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *federatedID; + +/** @property email + @brief The user's email at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property phoneNumber + @brief A phone number associated with the user. + */ +@property(nonatomic, readonly, nullable) NSString *phoneNumber; + +/** @fn init + @brief Please use initWithDictionary: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithAPIKey: + @brief Designated initializer. + @param dictionary The provider user info data from endpoint. + */ +- (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; + +@end + +/** @class FIRGetAccountInfoResponseUser + @brief Represents the firebase user info part of the response from the getAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/getAccountInfo + */ +@interface FIRGetAccountInfoResponseUser : NSObject + +/** @property localID + @brief The ID of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *localID; + +/** @property email + @brief The email or the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property emailVerified + @brief Whether the email has been verified. + */ +@property(nonatomic, assign, readonly) BOOL emailVerified; + +/** @property displayName + @brief The display name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property photoURL + @brief The user's photo URL. + */ +@property(nonatomic, strong, readonly, nullable) NSURL *photoURL; + +/** @property creationDate + @brief The user's creation date. + */ +@property(nonatomic, strong, readonly, nullable) NSDate *creationDate; + +/** @property lastSignInDate + @brief The user's last login date. + */ +@property(nonatomic, strong, readonly, nullable) NSDate *lastLoginDate; + +/** @property providerUserInfo + @brief The user's profiles at the associated identity providers. + */ +@property(nonatomic, strong, readonly, nullable) + NSArray *providerUserInfo; + +/** @property passwordHash + @brief Information about user's password. + @remarks This is not necessarily the hash of user's actual password. + */ +@property(nonatomic, strong, readonly, nullable) NSString *passwordHash; + +/** @property phoneNumber + @brief A phone number associated with the user. + */ +@property(nonatomic, readonly, nullable) NSString *phoneNumber; + +/** @fn init + @brief Please use initWithDictionary: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithAPIKey: + @brief Designated initializer. + @param dictionary The provider user info data from endpoint. + */ +- (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; + +@end + +/** @class FIRGetAccountInfoResponse + @brief Represents the response from the setAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/getAccountInfo + */ +@interface FIRGetAccountInfoResponse : NSObject + +/** @property providerUserInfo + @brief The requested users' profiles. + */ +@property(nonatomic, strong, readonly, nullable) NSArray *users; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.m new file mode 100644 index 0000000..19ab64a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.m @@ -0,0 +1,104 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetAccountInfoResponse.h" + +#import "FIRAuthErrorUtils.h" + +/** @var kErrorKey + @brief The key for the "error" value in JSON responses from the server. + */ +static NSString *const kErrorKey = @"error"; + +@implementation FIRGetAccountInfoResponseProviderUserInfo + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary { + self = [super init]; + if (self) { + _providerID = [dictionary[@"providerId"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + NSString *photoURL = dictionary[@"photoUrl"]; + if (photoURL) { + _photoURL = [NSURL URLWithString:photoURL]; + } + _federatedID = [dictionary[@"federatedId"] copy]; + _email = [dictionary[@"email"] copy]; + _phoneNumber = [dictionary[@"phoneNumber"] copy]; + } + return self; +} + +@end + +@implementation FIRGetAccountInfoResponseUser + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary { + self = [super init]; + if (self) { + NSArray *providerUserInfoData = dictionary[@"providerUserInfo"]; + if (providerUserInfoData) { + NSMutableArray *providerUserInfoArray = + [NSMutableArray arrayWithCapacity:providerUserInfoData.count]; + for (NSDictionary *dictionary in providerUserInfoData) { + [providerUserInfoArray addObject: + [[FIRGetAccountInfoResponseProviderUserInfo alloc] initWithDictionary:dictionary]]; + } + _providerUserInfo = [providerUserInfoArray copy]; + } + _localID = [dictionary[@"localId"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + _email = [dictionary[@"email"] copy]; + NSString *photoURL = dictionary[@"photoUrl"]; + if (photoURL) { + _photoURL = [NSURL URLWithString:photoURL]; + } + if ([dictionary[@"createdAt"] isKindOfClass:[NSString class]]) { + // Divide by 1000 in order to convert miliseconds to seconds. + NSTimeInterval creationDateTimeInterval = [dictionary[@"createdAt"] doubleValue] / 1000; + _creationDate = [NSDate dateWithTimeIntervalSince1970:creationDateTimeInterval]; + } + if ([dictionary[@"lastLoginAt"] isKindOfClass:[NSString class]]) { + // Divide by 1000 in order to convert miliseconds to seconds + NSTimeInterval creationDateTimeInterval = [dictionary[@"lastLoginAt"] doubleValue] / 1000; + _lastLoginDate = [NSDate dateWithTimeIntervalSince1970:creationDateTimeInterval]; + } + _emailVerified = [dictionary[@"emailVerified"] boolValue]; + _passwordHash = [dictionary[@"passwordHash"] copy]; + _phoneNumber = [dictionary[@"phoneNumber"] copy]; + } + return self; +} + +@end + +@implementation FIRGetAccountInfoResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + NSArray *usersData = dictionary[@"users"]; + // The client side never sends a getAccountInfo request with multiple localID, so only one user + // data is expected in the response. + if (![usersData isKindOfClass:[NSArray class]] || usersData.count != 1) { + if (error) { + *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:dictionary]; + } + return NO; + } + _users = @[ [[FIRGetAccountInfoResponseUser alloc] initWithDictionary:usersData.firstObject] ]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.h new file mode 100644 index 0000000..3130c78 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.h @@ -0,0 +1,153 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +@class FIRActionCodeSettings; + +NS_ASSUME_NONNULL_BEGIN + +/** @enum FIRGetOOBConfirmationCodeRequestType + @brief Types of OOB Confirmation Code requests. + */ +typedef NS_ENUM(NSInteger, FIRGetOOBConfirmationCodeRequestType) { + /** @var FIRGetOOBConfirmationCodeRequestTypePasswordReset + @brief Requests a password reset code. + */ + FIRGetOOBConfirmationCodeRequestTypePasswordReset, + + /** @var FIRGetOOBConfirmationCodeRequestTypeVerifyEmail + @brief Requests an email verification code. + */ + FIRGetOOBConfirmationCodeRequestTypeVerifyEmail, + + /** @var FIRGetOOBConfirmationCodeRequestTypeEmailLink + @brief Requests an email sign-in link. + */ + FIRGetOOBConfirmationCodeRequestTypeEmailLink, +}; + +/** @enum FIRGetOOBConfirmationCodeRequest + @brief Represents the parameters for the getOOBConfirmationCode endpoint. + */ +@interface FIRGetOOBConfirmationCodeRequest : FIRIdentityToolkitRequest + +/** @property requestType + @brief The types of OOB Confirmation Code to request. + */ +@property(nonatomic, assign, readonly) FIRGetOOBConfirmationCodeRequestType requestType; + +/** @property email + @brief The email of the user. + @remarks For password reset. + */ +@property(nonatomic, copy, nullable, readonly) NSString *email; + +/** @property accessToken + @brief The STS Access Token of the authenticated user. + @remarks For email change. + */ +@property(nonatomic, copy, nullable, readonly) NSString *accessToken; + +/** @property continueURL + @brief This URL represents the state/Continue URL in the form of a universal link. + */ +@property(nonatomic, copy, nullable, readonly) NSString *continueURL; + +/** @property iOSBundleID + @brief The iOS bundle Identifier, if available. + */ +@property(nonatomic, copy, nullable, readonly) NSString *iOSBundleID; + +/** @property androidPackageName + @brief The Android package name, if available. + */ +@property(nonatomic, copy, nullable, readonly) NSString *androidPackageName; + +/** @property androidMinimumVersion + @brief The minimum Android version supported, if available. + */ +@property(nonatomic, copy, nullable, readonly) NSString *androidMinimumVersion; + +/** @property androidInstallIfNotAvailable + @brief Indicates whether or not the Android app should be installed if not already available. + */ +@property(nonatomic, assign, readonly) BOOL androidInstallApp; + +/** @property handleCodeInApp + @brief Indicates whether the action code link will open the app directly or after being + redirected from a Firebase owned web widget. + */ +@property(assign, nonatomic) BOOL handleCodeInApp; + +/** @property dynamicLinkDomain + @brief The Firebase Dynamic Link domain used for out of band code flow. + */ +@property (copy, nonatomic, nullable) NSString *dynamicLinkDomain; + + +/** @fn passwordResetRequestWithEmail:actionCodeSettings:requestConfiguration: + @brief Creates a password reset request. + @param email The user's email address. + @param actionCodeSettings An object of FIRActionCodeSettings which specifies action code + settings to be applied to the password reset request. + @param requestConfiguration An object containing configurations to be added to the request. + @return A password reset request. + */ ++ (nullable FIRGetOOBConfirmationCodeRequest *) + passwordResetRequestWithEmail:(NSString *)email + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration; + +/** @fn verifyEmailRequestWithAccessToken:actionCodeSettings:requestConfiguration: + @brief Creates a password reset request. + @param accessToken The user's STS Access Token. + @param actionCodeSettings An object of FIRActionCodeSettings which specifies action code + settings to be applied to the email verification request. + @param requestConfiguration An object containing configurations to be added to the request. + @return A password reset request. + */ ++ (nullable FIRGetOOBConfirmationCodeRequest *) + verifyEmailRequestWithAccessToken:(NSString *)accessToken + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration; + +/** @fn signInWithEmailLinkRequest:actionCodeSettings:requestConfiguration: + @brief Creates a sign-in with email link. + @param email The user's email address. + @param actionCodeSettings An object of FIRActionCodeSettings which specifies action code + settings to be applied to the email sign-in link. + @param requestConfiguration An object containing configurations to be added to the request. + @return An email sign-in link request. + */ ++ (nullable FIRGetOOBConfirmationCodeRequest *) + signInWithEmailLinkRequest:(NSString *)email + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration; + +/** @fn init + @brief Please use a factory method. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.m new file mode 100644 index 0000000..82f1a27 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.m @@ -0,0 +1,244 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetOOBConfirmationCodeRequest.h" + +#import "FIRActionCodeSettings.h" + +#import "FIRAuthErrorUtils.h" +#import "FIRAuth_Internal.h" + +/** @var kEndpoint + @brief The getOobConfirmationCode endpoint name. + */ +static NSString *const kGetOobConfirmationCodeEndpoint = @"getOobConfirmationCode"; + +/** @var kRequestTypeKey + @brief The name of the required "requestType" property in the request. + */ +static NSString *const kRequestTypeKey = @"requestType"; + +/** @var kEmailKey + @brief The name of the "email" property in the request. + */ +static NSString *const kEmailKey = @"email"; + +/** @var kIDTokenKey + @brief The key for the "idToken" value in the request. This is actually the STS Access Token, + despite it's confusing (backwards compatiable) parameter name. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kContinueURLKey + @brief The key for the "continue URL" value in the request. + */ +static NSString *const kContinueURLKey = @"continueUrl"; + +/** @var kIosBundeIDKey + @brief The key for the "iOS Bundle Identifier" value in the request. + */ +static NSString *const kIosBundleIDKey = @"iOSBundleId"; + +/** @var kAndroidPackageNameKey + @brief The key for the "Android Package Name" value in the request. + */ +static NSString *const kAndroidPackageNameKey = @"androidPackageName"; + +/** @var kAndroidInstallAppKey + @brief The key for the request parameter indicating whether the android app should be installed + or not. + */ +static NSString *const kAndroidInstallAppKey = @"androidInstallApp"; + +/** @var kAndroidMinimumVersionKey + @brief The key for the "minimum Android version supported" value in the request. + */ +static NSString *const kAndroidMinimumVersionKey = @"androidMinimumVersion"; + +/** @var kCanHandleCodeInAppKey + @brief The key for the request parameter indicating whether the action code can be handled in + the app or not. + */ +static NSString *const kCanHandleCodeInAppKey = @"canHandleCodeInApp"; + +/** @var kDynamicLinkDomainKey + @brief The key for the "dynamic link domain" value in the request. + */ +static NSString *const kDynamicLinkDomainKey = @"dynamicLinkDomain"; + +/** @var kPasswordResetRequestTypeValue + @brief The value for the "PASSWORD_RESET" request type. + */ +static NSString *const kPasswordResetRequestTypeValue = @"PASSWORD_RESET"; + +/** @var kEmailLinkSignInTypeValue + @brief The value for the "EMAIL_SIGNIN" request type. + */ +static NSString *const kEmailLinkSignInTypeValue= @"EMAIL_SIGNIN"; + +/** @var kVerifyEmailRequestTypeValue + @brief The value for the "VERIFY_EMAIL" request type. + */ +static NSString *const kVerifyEmailRequestTypeValue = @"VERIFY_EMAIL"; + +@interface FIRGetOOBConfirmationCodeRequest () + +/** @fn initWithRequestType:email:APIKey: + @brief Designated initializer. + @param requestType The types of OOB Confirmation Code to request. + @param email The email of the user. + @param accessToken The STS Access Token of the currently signed in user. + @param actionCodeSettings An object of FIRActionCodeSettings which specifies action code + settings to be applied to the OOB code request. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithRequestType:(FIRGetOOBConfirmationCodeRequestType)requestType + email:(nullable NSString *)email + accessToken:(nullable NSString *)accessToken + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +@implementation FIRGetOOBConfirmationCodeRequest + +/** @var requestTypeStringValueForRequestType: + @brief Returns the string equivilent for an @c FIRGetOOBConfirmationCodeRequestType value. + */ ++ (NSString *)requestTypeStringValueForRequestType: + (FIRGetOOBConfirmationCodeRequestType)requestType { + switch (requestType) { + case FIRGetOOBConfirmationCodeRequestTypePasswordReset: + return kPasswordResetRequestTypeValue; + case FIRGetOOBConfirmationCodeRequestTypeVerifyEmail: + return kVerifyEmailRequestTypeValue; + case FIRGetOOBConfirmationCodeRequestTypeEmailLink: + return kEmailLinkSignInTypeValue; + // No default case so that we get a compiler warning if a new value was added to the enum. + } +} + ++ (FIRGetOOBConfirmationCodeRequest *) + passwordResetRequestWithEmail:(NSString *)email + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + return [[self alloc] initWithRequestType:FIRGetOOBConfirmationCodeRequestTypePasswordReset + email:email + accessToken:nil + actionCodeSettings:actionCodeSettings + requestConfiguration:requestConfiguration]; +} + ++ (FIRGetOOBConfirmationCodeRequest *) + verifyEmailRequestWithAccessToken:(NSString *)accessToken + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + return [[self alloc] initWithRequestType:FIRGetOOBConfirmationCodeRequestTypeVerifyEmail + email:nil + accessToken:accessToken + actionCodeSettings:actionCodeSettings + requestConfiguration:requestConfiguration]; +} + ++ (FIRGetOOBConfirmationCodeRequest *) + signInWithEmailLinkRequest:(NSString *)email + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + return [[self alloc] initWithRequestType:FIRGetOOBConfirmationCodeRequestTypeEmailLink + email:email + accessToken:nil + actionCodeSettings:actionCodeSettings + requestConfiguration:requestConfiguration]; +} + +- (nullable instancetype)initWithRequestType:(FIRGetOOBConfirmationCodeRequestType)requestType + email:(nullable NSString *)email + accessToken:(nullable NSString *)accessToken + actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kGetOobConfirmationCodeEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _requestType = requestType; + _email = email; + _accessToken = accessToken; + _continueURL = actionCodeSettings.URL.absoluteString; + _iOSBundleID = actionCodeSettings.iOSBundleID; + _androidPackageName = actionCodeSettings.androidPackageName; + _androidMinimumVersion = actionCodeSettings.androidMinimumVersion; + _androidInstallApp = actionCodeSettings.androidInstallIfNotAvailable; + _handleCodeInApp = actionCodeSettings.handleCodeInApp; + _dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *body = [@{ + kRequestTypeKey : [[self class] requestTypeStringValueForRequestType:_requestType] + } mutableCopy]; + + // For password reset requests, we only need an email address in addition to the already required + // fields. + if (_requestType == FIRGetOOBConfirmationCodeRequestTypePasswordReset) { + body[kEmailKey] = _email; + } + + // For verify email requests, we only need an STS Access Token in addition to the already required + // fields. + if (_requestType == FIRGetOOBConfirmationCodeRequestTypeVerifyEmail) { + body[kIDTokenKey] = _accessToken; + } + + // For email sign-in link requests, we only need an email address in addition to the already + // required fields. + if (_requestType == FIRGetOOBConfirmationCodeRequestTypeEmailLink) { + body[kEmailKey] = _email; + } + + if (_continueURL) { + body[kContinueURLKey] = _continueURL; + } + + if (_iOSBundleID) { + body[kIosBundleIDKey] = _iOSBundleID; + } + + if (_androidPackageName) { + body[kAndroidPackageNameKey] = _androidPackageName; + } + + if (_androidMinimumVersion) { + body[kAndroidMinimumVersionKey] = _androidMinimumVersion; + } + + if (_androidInstallApp) { + body[kAndroidInstallAppKey] = @YES; + } + + if (_handleCodeInApp) { + body[kCanHandleCodeInAppKey] = @YES; + } + + if (_dynamicLinkDomain) { + body[kDynamicLinkDomainKey] = _dynamicLinkDomain; + } + + return body; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.h new file mode 100644 index 0000000..69aa458 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRGetOOBConfirmationCodeResponse + @brief Represents the response from the getOobConfirmationCode endpoint. + */ +@interface FIRGetOOBConfirmationCodeResponse : NSObject + +/** @property OOBCode + @brief The OOB code returned by the server in some cases. + */ +@property(nonatomic, copy, readonly, nullable) NSString *OOBCode; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.m new file mode 100644 index 0000000..0b6c416 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetOOBConfirmationCodeResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kOOBCodeKey + @brief The name of the field in the response JSON for the OOB code. + */ +static NSString *const kOOBCodeKey = @"oobCode"; + +@implementation FIRGetOOBConfirmationCodeResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _OOBCode = [dictionary[kOOBCodeKey] copy]; + return YES; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.h new file mode 100644 index 0000000..7c37e8d --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRIdentityToolkitRequest.h" + +#import "FIRAuthRPCRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRGetProjectConfigRequest : FIRIdentityToolkitRequest + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithRequestConfiguration: + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithTemporaryProof:phoneNumberAPIKey + @brief Designated initializer. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.m new file mode 100644 index 0000000..acfcc02 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.m @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetProjectConfigRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kGetProjectConfigEndPoint + @brief The "getProjectConfig" endpoint. + */ +static NSString *const kGetProjectConfigEndPoint = @"getProjectConfig"; + +@implementation FIRGetProjectConfigRequest + +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration { + return [super initWithEndpoint:kGetProjectConfigEndPoint + requestConfiguration:requestConfiguration]; +} + +- (BOOL)containsPostBody { + return NO; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.h new file mode 100644 index 0000000..317ec81 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +/** @class FIRGetProjectConfigResponse + @brief Represents the response from the getProjectConfig endpoint. + */ +@interface FIRGetProjectConfigResponse : NSObject + +/** @property projectID + @brief The unique ID pertaining to the current project. + */ +@property(nonatomic, strong, readonly, nullable) NSString *projectID; + +/** @property authorizedDomains + @brief A list of domains whitelisted for the current project. + */ +@property(nonatomic, strong, readonly, nullable) NSArray *authorizedDomains; + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.m new file mode 100644 index 0000000..259a4fb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.m @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRGetProjectConfigResponse.h" + +@implementation FIRGetProjectConfigResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _projectID = [dictionary[@"projectId"] copy]; + id authorizedDomains = dictionary[@"authorizedDomains"]; + if ([authorizedDomains isKindOfClass:[NSString class]]) { + NSData *data = [authorizedDomains dataUsingEncoding:NSUTF8StringEncoding]; + authorizedDomains = [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingMutableLeaves + error:nil]; + } + if ([authorizedDomains isKindOfClass:[NSArray class]]) { + _authorizedDomains = [[NSArray alloc] initWithArray:authorizedDomains + copyItems:YES]; + } + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.h new file mode 100644 index 0000000..b5ca726 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.h @@ -0,0 +1,66 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRequestConfiguration.h" + +@class FIRAuthRequestConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRIdentityToolkitRequest + @brief Represents a request to an identity toolkit endpoint. + */ +@interface FIRIdentityToolkitRequest : NSObject + +/** @property endpoint + @brief Gets the RPC's endpoint. + */ +@property(nonatomic, copy, readonly) NSString *endpoint; + +/** @property APIKey + @brief Gets the client's API key used for the request. + */ +@property(nonatomic, copy, readonly) NSString *APIKey; + +/** @fn init + @brief Please use initWithEndpoint:APIKey: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithEndpoint:APIKey: + @brief Designated initializer. + @param endpoint The endpoint name. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +/** @fn requestURL + @brief Gets the request's full URL. + */ +- (NSURL *)requestURL; + +/** @fn requestConfiguration + @brief Gets the request's configuration. + */ +- (FIRAuthRequestConfiguration *)requestConfiguration; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.m new file mode 100644 index 0000000..a1ab482 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.m @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kAPIURLFormat + @brief URL format for server API calls. + */ +static NSString *const kAPIURLFormat = @"https://%@/identitytoolkit/v3/relyingparty/%@?key=%@"; + +/** @var gAPIHost + @brief Host for server API calls. + */ +static NSString *gAPIHost = @"www.googleapis.com"; + +@implementation FIRIdentityToolkitRequest { + FIRAuthRequestConfiguration *_requestConfiguration; +} + +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super init]; + if (self) { + _endpoint = [endpoint copy]; + _APIKey = [requestConfiguration.APIKey copy]; + _requestConfiguration = requestConfiguration; + } + return self; +} + +- (BOOL)containsPostBody { + return YES; +} + +- (NSURL *)requestURL { + NSString *URLString = [NSString stringWithFormat:kAPIURLFormat, gAPIHost, _endpoint, _APIKey]; + NSURL *URL = [NSURL URLWithString:URLString]; + return URL; +} + +- (FIRAuthRequestConfiguration *)requestConfiguration { + return _requestConfiguration; +} + +#pragma mark - Internal API for development + ++ (NSString *)host { + return gAPIHost; +} + ++ (void)setHost:(NSString *)host { + gAPIHost = host; +} + +NS_ASSUME_NONNULL_END + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.h new file mode 100644 index 0000000..701e305 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.h @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRResetPasswordRequest : FIRIdentityToolkitRequest + +/** @property oobCode + @brief The oobCode sent in the request. + */ +@property(nonatomic, copy, readonly) NSString *oobCode; + +/** @property updatedPassword + @brief The new password sent in the request. + */ +@property(nonatomic, copy, readonly) NSString *updatedPassword; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithOobCode:newPassword:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithOobCode:newPassword:requestConfiguration: + @brief Designated initializer. + @param oobCode The OOB Code. + @param newPassword The new password. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithOobCode:(NSString *)oobCode + newPassword:(nullable NSString *)newPassword + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.m new file mode 100644 index 0000000..27d6d8c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.m @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRResetPasswordRequest.h" + +/** @var kResetPasswordEndpoint + @brief The "resetPassword" endpoint. + */ +static NSString *const kResetPasswordEndpoint = @"resetPassword"; + +/** @var kOOBCodeKey + @brief The "resetPassword" key. + */ +static NSString *const kOOBCodeKey = @"oobCode"; + +/** @var kCurrentPasswordKey + @brief The "newPassword" key. + */ +static NSString *const kCurrentPasswordKey = @"newPassword"; + +@implementation FIRResetPasswordRequest + +- (instancetype)initWithOobCode:(NSString *)oobCode + newPassword:(NSString *)newPassword + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kResetPasswordEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _oobCode = oobCode; + _updatedPassword = newPassword; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + postBody[kOOBCodeKey] = _oobCode; + if (_updatedPassword) { + postBody[kCurrentPasswordKey] = _updatedPassword; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.h new file mode 100644 index 0000000..28eb5f4 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRAuthResetPasswordResponse + @brief Represents the response from the resetPassword endpoint. + @remarks Possible error codes: + - FIRAuthErrorCodeWeakPassword + - FIRAuthErrorCodeUserDisabled + - FIRAuthErrorCodeOperationNotAllowed + - FIRAuthErrorCodeExpiredActionCode + - FIRAuthErrorCodeInvalidActionCode + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/resetPassword + */ +@interface FIRResetPasswordResponse : NSObject + +/** @property email + @brief The email address corresponding to the reset password request. + */ +@property(nonatomic, strong, readonly) NSString *email; + +/** @property verifiedEmail + @brief The verified email returned from the backend. + */ +@property(nonatomic, strong, readonly) NSString *verifiedEmail; + +/** @property requestType + @brief The tpye of request as returned by the backend. + */ +@property(nonatomic, strong, readonly) NSString *requestType; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.m new file mode 100644 index 0000000..6092cfe --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.m @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRResetPasswordResponse.h" + +@implementation FIRResetPasswordResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _email = [dictionary[@"email"] copy]; + _requestType = [dictionary[@"requestType"] copy]; + _verifiedEmail = [dictionary[@"newEmail"] copy]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.h new file mode 100644 index 0000000..14722fa --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.h @@ -0,0 +1,113 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @enum FIRSecureTokenRequestGrantType + @brief Represents the possible grant types for a token request. + */ +typedef NS_ENUM(NSUInteger, FIRSecureTokenRequestGrantType) { + /** @var FIRSecureTokenRequestGrantTypeAuthorizationCode + @brief Indicates an authorization code request. + @remarks Exchanges a Gitkit "ID Token" for an STS Access Token and Refresh Token. + */ + FIRSecureTokenRequestGrantTypeAuthorizationCode, + + /** @var FIRSecureTokenRequestGrantTypeRefreshToken + @brief Indicates an refresh token request. + @remarks Uses an existing Refresh Token to create a new Access Token. + */ + FIRSecureTokenRequestGrantTypeRefreshToken, +}; + +/** @class FIRSecureTokenRequest + @brief Represents the parameters for the token endpoint. + */ +@interface FIRSecureTokenRequest : NSObject + +/** @property grantType + @brief The type of grant requested. + @see FIRSecureTokenRequestGrantType + */ +@property(nonatomic, assign, readonly) FIRSecureTokenRequestGrantType grantType; + +/** @property scope + @brief The scopes requested (a comma-delimited list of scope strings.) + */ +@property(nonatomic, copy, readonly, nullable) NSString *scope; + +/** @property refreshToken + @brief The client's refresh token. + */ +@property(nonatomic, copy, readonly, nullable) NSString *refreshToken; + +/** @property code + @brief The client's authorization code (legacy Gitkit "ID Token"). + */ +@property(nonatomic, copy, readonly, nullable) NSString *code; + +/** @property APIKey + @brief The client's API Key. + */ +@property(nonatomic, copy, readonly) NSString *APIKey; + +/** @fn authCodeRequestWithCode: + @brief Creates an authorization code request with the given code (legacy Gitkit "ID Token"). + @param code The authorization code (legacy Gitkit "ID Token"). + @param requestConfiguration An object containing configurations to be added to the request. + @return An authorization request. + */ ++ (FIRSecureTokenRequest *)authCodeRequestWithCode:(NSString *)code + requestConfiguration:(FIRAuthRequestConfiguration *) + requestConfiguration; + +/** @fn refreshRequestWithCode: + @brief Creates a refresh request with the given refresh token. + @param refreshToken The refresh token. + @param requestConfiguration An object containing configurations to be added to the request. + @return A refresh request. + */ ++ (FIRSecureTokenRequest *)refreshRequestWithRefreshToken:(NSString *)refreshToken + requestConfiguration:(FIRAuthRequestConfiguration *) + requestConfiguration; + +/** @fn init + @brief Please use initWithGrantType:scope:refreshToken:code: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithGrantType:scope:refreshToken:code:APIKey: + @brief Designated initializer. + @param grantType The type of request. + @param scope The scopes requested. + @param refreshToken The client's refresh token (for refresh requests.) + @param code The client's authorization code (Gitkit ID Token) (for authorization code requests.) + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithGrantType:(FIRSecureTokenRequestGrantType)grantType + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + code:(nullable NSString *)code + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.m new file mode 100644 index 0000000..786ea6c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.m @@ -0,0 +1,159 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSecureTokenRequest.h" +#import "FIRAuthRequestConfiguration.h" + +/** @var kFIRSecureTokenServiceGetTokenURLFormat + @brief The format of the secure token service URLs. Requires string format substitution with + the client's API Key. + */ +static NSString *const kFIRSecureTokenServiceGetTokenURLFormat = @"https://%@/v1/token?key=%@"; + +/** @var kFIRSecureTokenServiceGrantTypeRefreshToken + @brief The string value of the @c FIRSecureTokenRequestGrantTypeRefreshToken request type. + */ +static NSString *const kFIRSecureTokenServiceGrantTypeRefreshToken = @"refresh_token"; + +/** @var kFIRSecureTokenServiceGrantTypeAuthorizationCode + @brief The string value of the @c FIRSecureTokenRequestGrantTypeAuthorizationCode request type. + */ +static NSString *const kFIRSecureTokenServiceGrantTypeAuthorizationCode = @"authorization_code"; + +/** @var kGrantTypeKey + @brief The key for the "grantType" parameter in the request. + */ +static NSString *const kGrantTypeKey = @"grantType"; + +/** @var kScopeKey + @brief The key for the "scope" parameter in the request. + */ +static NSString *const kScopeKey = @"scope"; + +/** @var kRefreshTokenKey + @brief The key for the "refreshToken" parameter in the request. + */ +static NSString *const kRefreshTokenKey = @"refreshToken"; + +/** @var kCodeKey + @brief The key for the "code" parameter in the request. + */ +static NSString *const kCodeKey = @"code"; + +/** @var gAPIHost + @brief Host for server API calls. + */ +static NSString *gAPIHost = @"securetoken.googleapis.com"; + +@implementation FIRSecureTokenRequest { + /** @var _requestConfiguration + @brief Contains configuration relevant to the request. + */ + FIRAuthRequestConfiguration *_requestConfiguration; +} + ++ (FIRSecureTokenRequest *)authCodeRequestWithCode:(NSString *)code + requestConfiguration:(FIRAuthRequestConfiguration *) + requestConfiguration { + return [[self alloc] initWithGrantType:FIRSecureTokenRequestGrantTypeAuthorizationCode + scope:nil + refreshToken:nil + code:code + requestConfiguration:requestConfiguration]; +} + ++ (FIRSecureTokenRequest *)refreshRequestWithRefreshToken:(NSString *)refreshToken + requestConfiguration:(FIRAuthRequestConfiguration *) + requestConfiguration { + return [[self alloc] initWithGrantType:FIRSecureTokenRequestGrantTypeRefreshToken + scope:nil + refreshToken:refreshToken + code:nil + requestConfiguration:requestConfiguration]; +} + +/** @fn grantTypeStringWithGrantType: + @brief Converts a @c FIRSecureTokenRequestGrantType to it's @c NSString equivilent. + */ ++ (NSString *)grantTypeStringWithGrantType:(FIRSecureTokenRequestGrantType)grantType { + switch (grantType) { + case FIRSecureTokenRequestGrantTypeAuthorizationCode: + return kFIRSecureTokenServiceGrantTypeAuthorizationCode; + case FIRSecureTokenRequestGrantTypeRefreshToken: + return kFIRSecureTokenServiceGrantTypeRefreshToken; + // No Default case so we will notice if new grant types are added to the enum. + } +} + +- (nullable instancetype)initWithGrantType:(FIRSecureTokenRequestGrantType)grantType + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + code:(nullable NSString *)code + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super init]; + if (self) { + _grantType = grantType; + _scope = [scope copy]; + _refreshToken = [refreshToken copy]; + _code = [code copy]; + _APIKey = [requestConfiguration.APIKey copy]; + _requestConfiguration = requestConfiguration; + } + return self; +} + +- (FIRAuthRequestConfiguration *)requestConfiguration { + return _requestConfiguration; +} + +- (NSURL *)requestURL { + NSString *URLString = + [NSString stringWithFormat:kFIRSecureTokenServiceGetTokenURLFormat, gAPIHost, _APIKey]; + NSURL *URL = [NSURL URLWithString:URLString]; + return URL; +} + +- (BOOL)containsPostBody { + return YES; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [@{ + kGrantTypeKey : [[self class] grantTypeStringWithGrantType:_grantType] + } mutableCopy]; + if (_scope) { + postBody[kScopeKey] = _scope; + } + if (_refreshToken) { + postBody[kRefreshTokenKey] = _refreshToken; + } + if (_code) { + postBody[kCodeKey] = _code; + } + return postBody; +} + +#pragma mark - Internal API for development + ++ (NSString *)host { + return gAPIHost; +} + ++ (void)setHost:(NSString *)host { + gAPIHost = host; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.h new file mode 100644 index 0000000..0dd4a20 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRSecureTokenResponse + @brief Represents the response from the token endpoint. + */ +@interface FIRSecureTokenResponse : NSObject + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token. (Possibly an updated one for refresh requests.) + */ +@property(nonatomic, copy, readonly, nullable) NSString *refreshToken; + +/** @property accessToken + @brief The new access token. + */ +@property(nonatomic, copy, readonly, nullable) NSString *accessToken; + +/** @property IDToken + @brief The new ID Token. + */ +@property(nonatomic, copy, readonly, nullable) NSString *IDToken; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.m new file mode 100644 index 0000000..b97fda5 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.m @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSecureTokenResponse.h" + +#import "FIRAuthErrorUtils.h" + +/** @var kExpiresInKey + @brief The key for the number of seconds till the access token expires. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/** @var kRefreshTokenKey + @brief The key for the refresh token. + */ +static NSString *const kRefreshTokenKey = @"refresh_token"; + +/** @var kAccessTokenKey + @brief The key for the access token. + */ +static NSString *const kAccessTokenKey = @"access_token"; + +/** @var kIDTokenKey + @brief The key for the "id_token" value in the response. + */ +static NSString *const kIDTokenKey = @"id_token"; + +@implementation FIRSecureTokenResponse + +- (nullable NSString *)expectedKind { + return nil; +} + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _refreshToken = dictionary[kRefreshTokenKey]; + _accessToken = dictionary[kAccessTokenKey]; + _IDToken = dictionary[kIDTokenKey]; + if (!_accessToken.length) { + if (error) { + *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:dictionary]; + } + return NO; + } + id expiresIn = dictionary[kExpiresInKey]; + if (![expiresIn isKindOfClass:[NSString class]]) { + if (error) { + *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:dictionary]; + } + return NO; + } + + _approximateExpirationDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn doubleValue]]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.h new file mode 100644 index 0000000..af6cc93 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.h @@ -0,0 +1,67 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRIdentityToolkitRequest.h" + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +@class FIRAuthAppCredential; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRSendVerificationCodeRequest : FIRIdentityToolkitRequest + +/** @property phoneNumber + @brief The phone number to which the verification code should be sent. + */ +@property(nonatomic, strong, readonly) NSString *phoneNumber; + +/** @property appCredential + @brief The credential to prove the identity of the app in order to send the verification code. + */ +@property(nonatomic, strong, readonly, nullable) FIRAuthAppCredential *appCredential; + +/** @property reCAPTCHAToken + @brief The reCAPTCHA token to prove the identity of the app in order to send the verification + code. + */ +@property(nonatomic, strong, readonly, nullable) NSString *reCAPTCHAToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithPhoneNumber:appCredentials:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithPhoneNumber:appCredentials:requestConfiguration: + @brief Designated initializer. + @param phoneNumber The phone number to which the verification code is to be sent. + @param appCredential The credential that proves the identity of the app. + @param reCAPTCHAToken The reCAPTCHA token that proves the identity of the app. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithPhoneNumber:(NSString *)phoneNumber + appCredential:(nullable FIRAuthAppCredential *)appCredential + reCAPTCHAToken:(nullable NSString *)reCAPTCHAToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.m new file mode 100644 index 0000000..38ad8cf --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.m @@ -0,0 +1,84 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSendVerificationCodeRequest.h" + +#import "FIRAuthAppCredential.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kSendVerificationCodeEndPoint + @brief The "sendVerificationCodeEnd" endpoint. + */ +static NSString *const kSendVerificationCodeEndPoint = @"sendVerificationCode"; + +/** @var kPhoneNumberKey + @brief The key for the Phone Number parameter in the request. + */ +static NSString *const kPhoneNumberKey = @"phoneNumber"; + +/** @var kReceiptKey + @brief The key for the receipt parameter in the request. + */ +static NSString *const kReceiptKey = @"iosReceipt"; + +/** @var kSecretKey + @brief The key for the Secret parameter in the request. + */ +static NSString *const kSecretKey = @"iosSecret"; + +/** @var kreCAPTCHATokenKey + @brief The key for the reCAPTCHAToken parameter in the request. + */ +static NSString *const kreCAPTCHATokenKey = @"recaptchaToken"; + +@implementation FIRSendVerificationCodeRequest { +} + +- (nullable instancetype)initWithPhoneNumber:(NSString *)phoneNumber + appCredential:(nullable FIRAuthAppCredential *)appCredential + reCAPTCHAToken:(nullable NSString *)reCAPTCHAToken + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kSendVerificationCodeEndPoint + requestConfiguration:requestConfiguration]; + if (self) { + _phoneNumber = [phoneNumber copy]; + _appCredential = appCredential; + _reCAPTCHAToken = [reCAPTCHAToken copy]; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_phoneNumber) { + postBody[kPhoneNumberKey] = _phoneNumber; + } + if (_appCredential.receipt) { + postBody[kReceiptKey] = _appCredential.receipt; + } + if (_appCredential.secret) { + postBody[kSecretKey] = _appCredential.secret; + } + if (_reCAPTCHAToken) { + postBody[kreCAPTCHATokenKey] = _reCAPTCHAToken; + } + return postBody; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.h new file mode 100644 index 0000000..1a49ec2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.h @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRSendVerificationCodeResponse : NSObject + +/** @property verificationID + @brief Encrypted session information returned by the backend. + */ +@property(nonatomic, readonly) NSString *verificationID; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.m new file mode 100644 index 0000000..9e47b6e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSendVerificationCodeResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRSendVerificationCodeResponse + +// TODO: remove when resolving b/37169084 . +- (nullable NSString *)expectedKind { + return nil; +} + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _verificationID = [dictionary[@"sessionInfo"] copy]; + return YES; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.h new file mode 100644 index 0000000..0e0e18f --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.h @@ -0,0 +1,151 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +@class FIRGetAccountInfoResponse; + +NS_ASSUME_NONNULL_BEGIN + +/** @var FIRSetAccountInfoUserAttributeEmail + @brief Constant for email attribute used in "deleteAttributes". + */ +extern NSString *const FIRSetAccountInfoUserAttributeEmail; + +/** @var FIRSetAccountInfoUserAttributeDisplayName + @brief Constant for displayName attribute used in "deleteAttributes". + */ +extern NSString *const FIRSetAccountInfoUserAttributeDisplayName; + +/** @var FIRSetAccountInfoUserAttributeProvider + @brief Constant for provider attribute used in "deleteAttributes". + */ +extern NSString *const FIRSetAccountInfoUserAttributeProvider; + +/** @var FIRSetAccountInfoUserAttributePhotoURL + @brief Constant for photoURL attribute used in "deleteAttributes". + */ +extern NSString *const FIRSetAccountInfoUserAttributePhotoURL; + +/** @var FIRSetAccountInfoUserAttributePassword + @brief Constant for password attribute used in "deleteAttributes". + */ +extern NSString *const FIRSetAccountInfoUserAttributePassword; + +/** @class FIRSetAccountInfoRequest + @brief Represents the parameters for the setAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/setAccountInfo + */ +@interface FIRSetAccountInfoRequest : FIRIdentityToolkitRequest + +/** @property accessToken + @brief The STS Access Token of the authenticated user. + */ +@property(nonatomic, copy, nullable) NSString *accessToken; + +/** @property displayName + @brief The name of the user. + */ +@property(nonatomic, copy, nullable) NSString *displayName; + +/** @property localID + @brief The local ID of the user. + */ +@property(nonatomic, copy, nullable) NSString *localID; + +/** @property email + @brief The email of the user. + */ +@property(nonatomic, copy, nullable) NSString *email; + +/** @property photoURL + @brief The photoURL of the user. + */ +@property(nonatomic, copy, nullable) NSURL *photoURL; + +/** @property password + @brief The new password of the user. + */ +@property(nonatomic, copy, nullable) NSString *password; + +/** @property providers + @brief The associated identity providers of the user. + */ +@property(nonatomic, copy, nullable) NSArray *providers; + +/** @property OOBCode + @brief The out-of-band code of the change email request. + */ +@property(nonatomic, copy, nullable) NSString *OOBCode; + +/** @property emailVerified + @brief Whether to mark the email as verified or not. + */ +@property(nonatomic, assign) BOOL emailVerified; + +/** @property upgradeToFederatedLogin + @brief Whether to mark the user to upgrade to federated login. + */ +@property(nonatomic, assign) BOOL upgradeToFederatedLogin; + +/** @property captchaChallenge + @brief The captcha challenge. + */ +@property(nonatomic, copy, nullable) NSString *captchaChallenge; + +/** @property captchaResponse + @brief Response to the captcha. + */ +@property(nonatomic, copy, nullable) NSString *captchaResponse; + +/** @property deleteAttributes + @brief The list of user attributes to delete. + @remarks Every element of the list must be one of the predefined constant starts with + "FIRSetAccountInfoUserAttribute". + */ +@property(nonatomic, copy, nullable) NSArray *deleteAttributes; + +/** @property deleteProviders + @brief The list of identity providers to delete. + */ +@property(nonatomic, copy, nullable) NSArray *deleteProviders; + +/** @property returnSecureToken + @brief Whether the response should return access token and refresh token directly. + @remarks The default value is @c YES . + */ +@property(nonatomic, assign) BOOL returnSecureToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithAPIKey:email:password:displayName:requestConfiguration instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithRequestConfiguration: + @brief Designated initializer. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.m new file mode 100644 index 0000000..f455d47 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.m @@ -0,0 +1,175 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSetAccountInfoRequest.h" + +#import "FIRAuthErrorUtils.h" +#import "FIRAuth_Internal.h" +#import "FIRGetAccountInfoResponse.h" + +NSString *const FIRSetAccountInfoUserAttributeEmail = @"EMAIL"; + +NSString *const FIRSetAccountInfoUserAttributeDisplayName = @"DISPLAY_NAME"; + +NSString *const FIRSetAccountInfoUserAttributeProvider = @"PROVIDER"; + +NSString *const FIRSetAccountInfoUserAttributePhotoURL = @"PHOTO_URL"; + +NSString *const FIRSetAccountInfoUserAttributePassword = @"PASSWORD"; + +/** @var kCreateAuthURIEndpoint + @brief The "setAccountInfo" endpoint. + */ +static NSString *const kSetAccountInfoEndpoint = @"setAccountInfo"; + +/** @var kIDTokenKey + @brief The key for the "idToken" value in the request. This is actually the STS Access Token, + despite it's confusing (backwards compatiable) parameter name. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kDisplayNameKey + @brief The key for the "displayName" value in the request. + */ +static NSString *const kDisplayNameKey = @"displayName"; + +/** @var kLocalIDKey + @brief The key for the "localID" value in the request. + */ +static NSString *const kLocalIDKey = @"localId"; + +/** @var kEmailKey + @brief The key for the "email" value in the request. + */ +static NSString *const kEmailKey = @"email"; + +/** @var kPasswordKey + @brief The key for the "password" value in the request. + */ +static NSString *const kPasswordKey = @"password"; + +/** @var kPhotoURLKey + @brief The key for the "photoURL" value in the request. + */ +static NSString *const kPhotoURLKey = @"photoUrl"; + +/** @var kProvidersKey + @brief The key for the "providers" value in the request. + */ +static NSString *const kProvidersKey = @"provider"; + +/** @var kOOBCodeKey + @brief The key for the "OOBCode" value in the request. + */ +static NSString *const kOOBCodeKey = @"oobCode"; + +/** @var kEmailVerifiedKey + @brief The key for the "emailVerified" value in the request. + */ +static NSString *const kEmailVerifiedKey = @"emailVerified"; + +/** @var kUpgradeToFederatedLoginKey + @brief The key for the "upgradeToFederatedLogin" value in the request. + */ +static NSString *const kUpgradeToFederatedLoginKey = @"upgradeToFederatedLogin"; + +/** @var kCaptchaChallengeKey + @brief The key for the "captchaChallenge" value in the request. + */ +static NSString *const kCaptchaChallengeKey = @"captchaChallenge"; + +/** @var kCaptchaResponseKey + @brief The key for the "captchaResponse" value in the request. + */ +static NSString *const kCaptchaResponseKey = @"captchaResponse"; + +/** @var kDeleteAttributesKey + @brief The key for the "deleteAttribute" value in the request. + */ +static NSString *const kDeleteAttributesKey = @"deleteAttribute"; + +/** @var kDeleteProvidersKey + @brief The key for the "deleteProvider" value in the request. + */ +static NSString *const kDeleteProvidersKey = @"deleteProvider"; + +/** @var kReturnSecureTokenKey + @brief The key for the "returnSecureToken" value in the request. + */ +static NSString *const kReturnSecureTokenKey = @"returnSecureToken"; + +@implementation FIRSetAccountInfoRequest + +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kSetAccountInfoEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _returnSecureToken = YES; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_accessToken) { + postBody[kIDTokenKey] = _accessToken; + } + if (_displayName) { + postBody[kDisplayNameKey] = _displayName; + } + if (_localID) { + postBody[kLocalIDKey] = _localID; + } + if (_email) { + postBody[kEmailKey] = _email; + } + if (_password) { + postBody[kPasswordKey] = _password; + } + if (_photoURL) { + postBody[kPhotoURLKey] = _photoURL.absoluteString; + } + if (_providers) { + postBody[kProvidersKey] = _providers; + } + if (_OOBCode) { + postBody[kOOBCodeKey] = _OOBCode; + } + if (_emailVerified) { + postBody[kEmailVerifiedKey] = @YES; + } + if (_upgradeToFederatedLogin) { + postBody[kUpgradeToFederatedLoginKey] = @YES; + } + if (_captchaChallenge) { + postBody[kCaptchaChallengeKey] = _captchaChallenge; + } + if (_captchaResponse) { + postBody[kCaptchaResponseKey] = _captchaResponse; + } + if (_deleteAttributes) { + postBody[kDeleteAttributesKey] = _deleteAttributes; + } + if (_deleteProviders) { + postBody[kDeleteProvidersKey] = _deleteProviders; + } + if (_returnSecureToken) { + postBody[kReturnSecureTokenKey] = @YES; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.h new file mode 100644 index 0000000..92895c0 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.h @@ -0,0 +1,98 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRSetAccountInfoResponseProviderUserInfo + @brief Represents the provider user info part of the response from the setAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/setAccountInfo + */ +@interface FIRSetAccountInfoResponseProviderUserInfo : NSObject + +/** @property providerID + @brief The ID of the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *providerID; + +/** @property displayName + @brief The user's display name at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property photoURL + @brief The user's photo URL at the identity provider. + */ +@property(nonatomic, strong, readonly, nullable) NSURL *photoURL; + +/** @fn init + @brief Please use initWithDictionary: + */ +- (instancetype)init NS_UNAVAILABLE; + +/** @fn initWithAPIKey: + @brief Designated initializer. + @param dictionary The provider user info data from endpoint. + */ +- (instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; + +@end + +/** @class FIRSetAccountInfoResponse + @brief Represents the response from the setAccountInfo endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/setAccountInfo + */ +@interface FIRSetAccountInfoResponse : NSObject + +/** @property email + @brief The email or the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property displayName + @brief The display name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property providerUserInfo + @brief The user's profiles at the associated identity providers. + */ +@property(nonatomic, strong, readonly, nullable) + NSArray *providerUserInfo; + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.m new file mode 100644 index 0000000..ff9c7a6 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.m @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSetAccountInfoResponse.h" + +@implementation FIRSetAccountInfoResponseProviderUserInfo + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary { + self = [super init]; + if (self) { + _providerID = [dictionary[@"providerId"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + NSString *photoURL = dictionary[@"photoUrl"]; + if (photoURL) { + _photoURL = [NSURL URLWithString:photoURL]; + } + } + return self; +} + +@end + +@implementation FIRSetAccountInfoResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _email = [dictionary[@"email"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + _IDToken = [dictionary[@"idToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + _refreshToken = [dictionary[@"refreshToken"] copy]; + NSArray *providerUserInfoData = dictionary[@"providerUserInfo"]; + if (providerUserInfoData) { + NSMutableArray *providerUserInfoArray = + [NSMutableArray arrayWithCapacity:providerUserInfoData.count]; + for (NSDictionary *dictionary in providerUserInfoData) { + [providerUserInfoArray addObject: + [[FIRSetAccountInfoResponseProviderUserInfo alloc] initWithDictionary:dictionary]]; + } + _providerUserInfo = [providerUserInfoArray copy]; + } + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.h new file mode 100644 index 0000000..52720cb --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.h @@ -0,0 +1,91 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRSignInWithGameCenterRequest + @brief The request to sign in with Game Center account + */ +@interface FIRSignInWithGameCenterRequest : FIRIdentityToolkitRequest + +/** @property playerID + @brief The playerID to verify. + */ +@property(nonatomic, copy) NSString *playerID; + +/** @property publicKeyURL + @brief The URL for the public encryption key. + */ +@property(nonatomic, copy) NSURL *publicKeyURL; + +/** @property signature + @brief The verification signature data generated by Game Center. + */ +@property(nonatomic, copy) NSData *signature; + +/** @property salt + @brief A random strong used to compute the hash and keep it randomized. + */ +@property(nonatomic, copy) NSData *salt; + +/** @property timestamp + @brief The date and time that the signature was created. + */ +@property(nonatomic, assign) uint64_t timestamp; + +/** @property accessToken + @brief The STS Access Token for the authenticated user, only needed for linking the user. + */ +@property(nonatomic, copy, nullable) NSString *accessToken; + +/** @property displayName + @brief The display name of the local Game Center player. + */ +@property(nonatomic, copy, nullable) NSString *displayName; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithPlayerID:publicKeyURL:signature:salt:timestamp:requestConfiguration:. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithPlayerID:publicKeyURL:signature:salt:timestamp:displayName:requestConfiguration: + @brief Designated initializer. + @param playerID The ID of the Game Center player. + @param publicKeyURL The URL for the public encryption key. + @param signature The verification signature generated. + @param salt A random string used to compute the hash and keep it randomized. + @param timestamp The date and time that the signature was created. + @param displayName The display name of the Game Center player. + */ +- (nullable instancetype)initWithPlayerID:(NSString *)playerID + publicKeyURL:(NSURL *)publicKeyURL + signature:(NSData *)signature + salt:(NSData *)salt + timestamp:(uint64_t)timestamp + displayName:(NSString *)displayName + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.m new file mode 100644 index 0000000..35fb754 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.m @@ -0,0 +1,80 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSignInWithGameCenterRequest.h" + +#import "NSData+FIRBase64.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kSignInWithGameCenterEndPoint + @brief The "SignInWithGameCenter" endpoint. + */ +static NSString *const kSignInWithGameCenterEndPoint = @"signInWithGameCenter"; + +@implementation FIRSignInWithGameCenterRequest + +- (nullable instancetype)initWithPlayerID:(NSString *)playerID + publicKeyURL:(NSURL *)publicKeyURL + signature:(NSData *)signature + salt:(NSData *)salt + timestamp:(uint64_t)timestamp + displayName:(NSString *)displayName + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kSignInWithGameCenterEndPoint + requestConfiguration:requestConfiguration]; + if (self) { + _playerID = playerID; + _publicKeyURL = [publicKeyURL copy]; + _signature = [signature copy]; + _salt = [salt copy]; + _timestamp = timestamp; + _displayName = displayName; + } + return self; +} + +#pragma mark - FIRAuthRPCRequest + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *__autoreleasing _Nullable *)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_playerID) { + postBody[@"playerId"] = _playerID; + } + if (_publicKeyURL) { + postBody[@"publicKeyUrl"] = _publicKeyURL.absoluteString; + } + if (_signature) { + postBody[@"signature"] = [_signature fir_base64URLEncodedStringWithOptions:0]; + } + if (_salt) { + postBody[@"salt"] = [_salt fir_base64URLEncodedStringWithOptions:0]; + } + if (_timestamp != 0) { + postBody[@"timestamp"] = [NSNumber numberWithUnsignedLongLong:_timestamp]; + } + if (_accessToken) { + postBody[@"idToken"] = _accessToken; + } + if (_displayName) { + postBody[@"displayName"] = _displayName; + } + return postBody; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.h new file mode 100644 index 0000000..75dbd75 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.h @@ -0,0 +1,64 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRSignInWithGameCenterResponse : NSObject + +/** @property IDToken + @breif Either an authorization code suitable for performing an STS token exchange, or the access + token from Secure Token Service, depending on whether @c returnSecureToken is set on the + request. + */ +@property(nonatomic, copy, readonly, nullable) NSString *IDToken; + +/** @property refreshToken + @breif @breif The refresh token from Secure Token Service. + */ +@property(nonatomic, copy, readonly, nullable) NSString *refreshToken; + +/** @property localID + @breif @breif The Firebase Auth user ID. + */ +@property(nonatomic, copy, readonly, nullable) NSString *localID; + +/** @property playerID + @breif @breif The verified player ID. + */ +@property(nonatomic, copy, readonly, nullable) NSString *playerID; + +/** @property approximateExpirationDate + @breif The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property isNewUser + @breif Flag indicating that the user signing in is a new user and not a returning user. + */ +@property(nonatomic, assign) BOOL isNewUser; + +/** @property displayName + @breif The user's Game Center display name. + */ +@property(nonatomic, copy, readonly, nullable) NSString *displayName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.m new file mode 100644 index 0000000..7cd1b9a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.m @@ -0,0 +1,40 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSignInWithGameCenterResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRSignInWithGameCenterResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _IDToken = [dictionary[@"idToken"] copy]; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _localID = [dictionary[@"localId"] copy]; + _approximateExpirationDate = nil; + if ([dictionary[@"expiresIn"] isKindOfClass:[NSString class]]) { + _approximateExpirationDate = [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] integerValue]]; + } + _playerID = [dictionary[@"playerId"] copy]; + _isNewUser = [dictionary[@"isNewUser"] boolValue]; + _displayName = [dictionary[@"displayName"] copy]; + return YES; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.h new file mode 100644 index 0000000..06d2cfe --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.h @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRSignUpNewUserRequest : FIRIdentityToolkitRequest + +/** @property email + @brief The email of the user. + */ +@property(nonatomic, copy, nullable) NSString *email; + +/** @property password + @brief The password inputed by the user. + */ +@property(nonatomic, copy, nullable) NSString *password; + +/** @property displayName + @brief The password inputed by the user. + */ +@property(nonatomic, copy, nullable) NSString *displayName; + +/** @property returnSecureToken + @brief Whether the response should return access token and refresh token directly. + @remarks The default value is @c YES . + */ +@property(nonatomic, assign) BOOL returnSecureToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithAPIKey:email:password:displayName:requestConfiguration instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithEndpoint:requestConfiguration: + @brief initializer for anonymous sign-in. + */ +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration; + +/** @fn initWithAPIKey:email:password:displayName:requestConfiguration + @brief Designated initializer. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithEmail:(nullable NSString *)email + password:(nullable NSString *)password + displayName:(nullable NSString *)displayName + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.m new file mode 100644 index 0000000..52a0215 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.m @@ -0,0 +1,86 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSignUpNewUserRequest.h" + +/** @var kSignupNewUserEndpoint + @brief The "SingupNewUserEndpoint" endpoint. + */ +static NSString *const kSignupNewUserEndpoint = @"signupNewUser"; + +/** @var kEmailKey + @brief The key for the "email" value in the request. + */ +static NSString *const kEmailKey = @"email"; + +/** @var kPasswordKey + @brief The key for the "password" value in the request. + */ +static NSString *const kPasswordKey = @"password"; + +/** @var kDisplayNameKey + @brief The key for the "kDisplayName" value in the request. + */ +static NSString *const kDisplayNameKey = @"displayName"; + +/** @var kReturnSecureTokenKey + @brief The key for the "returnSecureToken" value in the request. + */ +static NSString *const kReturnSecureTokenKey = @"returnSecureToken"; + +@implementation FIRSignUpNewUserRequest + +- (nullable instancetype)initWithEmail:(nullable NSString *)email + password:(nullable NSString *)password + displayName:(nullable NSString *)displayName + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kSignupNewUserEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _email = [email copy]; + _password = [password copy]; + _displayName = [displayName copy]; + _returnSecureToken = YES; + } + return self; +} + +- (nullable instancetype)initWithRequestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration { + self = [self initWithEmail:nil + password:nil + displayName:nil + requestConfiguration:requestConfiguration]; + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_email) { + postBody[kEmailKey] = _email; + } + if (_password) { + postBody[kPasswordKey] = _password; + } + if (_displayName) { + postBody[kDisplayNameKey] = _displayName; + } + if (_returnSecureToken) { + postBody[kReturnSecureTokenKey] = @YES; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.h new file mode 100644 index 0000000..0d55939 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.h @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRSignUpNewUserResponse : NSObject + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.m new file mode 100644 index 0000000..2071e07 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.m @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRSignUpNewUserResponse.h" + +@implementation FIRSignUpNewUserResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _IDToken = [dictionary[@"idToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + _refreshToken = [dictionary[@"refreshToken"] copy]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.h new file mode 100644 index 0000000..3136b80 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.h @@ -0,0 +1,103 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyAssertionRequest + @brief Represents the parameters for the verifyAssertion endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyAssertion + */ +@interface FIRVerifyAssertionRequest : FIRIdentityToolkitRequest + +/** @property requestURI + @brief The URI to which the IDP redirects the user back. It may contain federated login result + params added by the IDP. + */ +@property(nonatomic, copy, nullable) NSString *requestURI; + +/** @property pendingIDToken + @brief The Firebase ID Token for the non-trusted IDP pending to be confirmed by the user. + */ +@property(nonatomic, copy, nullable) NSString *pendingIDToken; + +/** @property accessToken + @brief The STS Access Token for the authenticated user, only needed for linking the user. + */ +@property(nonatomic, copy, nullable) NSString *accessToken; + +/** @property returnSecureToken + @brief Whether the response should return access token and refresh token directly. + @remarks The default value is @c YES . + */ +@property(nonatomic, assign) BOOL returnSecureToken; + +#pragma mark - Components of "postBody" + +/** @property providerID + @brief The ID of the IDP whose credentials are being presented to the endpoint. + */ +@property(nonatomic, copy, readonly) NSString *providerID; + +/** @property providerAccessToken + @brief An access token from the IDP. + */ +@property(nonatomic, copy, nullable) NSString *providerAccessToken; + +/** @property providerIDToken + @brief An ID Token from the IDP. + */ +@property(nonatomic, copy, nullable) NSString *providerIDToken; + +/** @property providerOAuthTokenSecret + @brief An OAuth client secret from the IDP. + */ +@property(nonatomic, copy, nullable) NSString *providerOAuthTokenSecret; + +/** @property inputEmail + @brief The originally entered email in the UI. + */ +@property(nonatomic, copy, nullable) NSString *inputEmail; + +/** @property autoCreate + @brief A flag that indicates whether or not the user should be automatically created. + */ +@property(nonatomic, assign) BOOL autoCreate; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithProviderID:requestConfifuration instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithProviderID:requestConfifuration + @brief Designated initializer. + @param providerID The auth provider's ID. + @param requestConfiguration An object containing configurations to be added to the request. + + */ +- (nullable instancetype)initWithProviderID:(NSString *)providerID + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.m new file mode 100644 index 0000000..274fd07 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.m @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyAssertionRequest.h" + +/** @var kVerifyAssertionEndpoint + @brief The "verifyAssertion" endpoint. + */ +static NSString *const kVerifyAssertionEndpoint = @"verifyAssertion"; + +/** @var kProviderIDKey + @brief The key for the "providerId" value in the request. + */ +static NSString *const kProviderIDKey = @"providerId"; + +/** @var kProviderIDTokenKey + @brief The key for the "id_token" value in the request. + */ +static NSString *const kProviderIDTokenKey = @"id_token"; + +/** @var kProviderAccessTokenKey + @brief The key for the "access_token" value in the request. + */ +static NSString *const kProviderAccessTokenKey = @"access_token"; + +/** @var kProviderOAuthTokenSecretKey + @brief The key for the "oauth_token_secret" value in the request. + */ +static NSString *const kProviderOAuthTokenSecretKey = @"oauth_token_secret"; + +/** @var kIdentifierKey + @brief The key for the "identifier" value in the request. + */ +static NSString *const kIdentifierKey = @"identifier"; + +/** @var kRequestURIKey + @brief The key for the "requestUri" value in the request. + */ +static NSString *const kRequestURIKey = @"requestUri"; + +/** @var kPostBodyKey + @brief The key for the "postBody" value in the request. + */ +static NSString *const kPostBodyKey = @"postBody"; + +/** @var kPendingIDTokenKey + @brief The key for the "pendingIdToken" value in the request. + */ +static NSString *const kPendingIDTokenKey = @"pendingIdToken"; + +/** @var kAutoCreateKey + @brief The key for the "autoCreate" value in the request. + */ +static NSString *const kAutoCreateKey = @"autoCreate"; + +/** @var kIDTokenKey + @brief The key for the "idToken" value in the request. This is actually the STS Access Token, + despite it's confusing (backwards compatiable) parameter name. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kReturnSecureTokenKey + @brief The key for the "returnSecureToken" value in the request. + */ +static NSString *const kReturnSecureTokenKey = @"returnSecureToken"; + +@implementation FIRVerifyAssertionRequest + +- (nullable instancetype)initWithProviderID:(NSString *)providerID + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyAssertionEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _providerID = providerID; + _returnSecureToken = YES; + _autoCreate = YES; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSURLComponents *components = [[NSURLComponents alloc] init]; + NSMutableArray *queryItems = [@[[NSURLQueryItem queryItemWithName:kProviderIDKey + value:_providerID]] + mutableCopy]; + + if (_providerIDToken) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:kProviderIDTokenKey + value:_providerIDToken]]; + } + + if (_providerAccessToken) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:kProviderAccessTokenKey + value:_providerAccessToken]]; + } + + if (!_providerIDToken && !_providerAccessToken) { + [NSException raise:NSInvalidArgumentException + format:@"Either IDToken or accessToken must be supplied."]; + } + + if (_providerOAuthTokenSecret) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:kProviderOAuthTokenSecretKey + value:_providerOAuthTokenSecret]]; + } + + if (_inputEmail) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:kIdentifierKey + value:_inputEmail]]; + } + [components setQueryItems:queryItems]; + NSMutableDictionary *body = [@{ + kRequestURIKey : @"http://localhost", // Unused by server, but required + kPostBodyKey : [components query] + } mutableCopy]; + + if (_pendingIDToken) { + body[kPendingIDTokenKey] = _pendingIDToken; + } + if (_accessToken) { + body[kIDTokenKey] = _accessToken; + } + if (_returnSecureToken) { + body[kReturnSecureTokenKey] = @YES; + } + + body[kAutoCreateKey] = @(_autoCreate); + + return body; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.h new file mode 100644 index 0000000..ce796ee --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.h @@ -0,0 +1,186 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyAssertionResponse + @brief Represents the response from the verifyAssertion endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyAssertion + */ +@interface FIRVerifyAssertionResponse : NSObject + +/** @property federatedID + @brief The unique ID identifies the IdP account. + */ +@property(nonatomic, strong, readonly, nullable) NSString *federatedID; + +/** @property providerID + @brief The IdP ID. For white listed IdPs it's a short domain name e.g. google.com, aol.com, + live.net and yahoo.com. If the "providerId" param is set to OpenID OP identifer other than + the whilte listed IdPs the OP identifier is returned. If the "identifier" param is federated + ID in the createAuthUri request. The domain part of the federated ID is returned. + */ +@property(nonatomic, strong, readonly, nullable) NSString *providerID; + +/** @property localID + @brief The RP local ID if it's already been mapped to the IdP account identified by the + federated ID. + */ +@property(nonatomic, strong, readonly, nullable) NSString *localID; + +/** @property email + @brief The email returned by the IdP. NOTE: The federated login user may not own the email. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property inputEmail + @brief It's the identifier param in the createAuthUri request if the identifier is an email. It + can be used to check whether the user input email is different from the asserted email. + */ +@property(nonatomic, strong, readonly, nullable) NSString *inputEmail; + +/** @property originalEmail + @brief The original email stored in the mapping storage. It's returned when the federated ID is + associated to a different email. + */ +@property(nonatomic, strong, readonly, nullable) NSString *originalEmail; + +/** @property oauthRequestToken + @brief The user approved request token for the OpenID OAuth extension. + */ +@property(nonatomic, strong, readonly, nullable) NSString *oauthRequestToken; + +/** @property oauthScope + @brief The scope for the OpenID OAuth extension. + */ +@property(nonatomic, strong, readonly, nullable) NSString *oauthScope; + +/** @property firstName + @brief The first name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *firstName; + +/** @property lastName + @brief The last name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *lastName; + +/** @property fullName + @brief The full name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *fullName; + +/** @property nickName + @brief The nick name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *nickName; + +/** @property displayName + @brief The display name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +/** @property action + @brief The action code. + */ +@property(nonatomic, strong, readonly, nullable) NSString *action; + +/** @property language + @brief The language preference of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *language; + +/** @property timeZone + @brief The timezone of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *timeZone; + +/** @property photoURL + @brief The URI of the public accessible profile picture. + */ +@property(nonatomic, strong, readonly, nullable) NSURL *photoURL; + +/** @property dateOfBirth + @brief The birth date of the IdP account. + */ +@property(nonatomic, strong, readonly, nullable) NSString *dateOfBirth; + +/** @property context + @brief The opaque value used by the client to maintain context info between the authentication + request and the IDP callback. + */ +@property(nonatomic, strong, readonly, nullable) NSString *context; + +/** @property verifiedProvider + @brief When action is 'map', contains the idps which can be used for confirmation. + */ +@property(nonatomic, strong, readonly, nullable) NSArray *verifiedProvider; + +/** @property needConfirmation + @brief Whether the assertion is from a non-trusted IDP and need account linking confirmation. + */ +@property(nonatomic, assign) BOOL needConfirmation; + +/** @property emailRecycled + @brief It's true if the email is recycled. + */ +@property(nonatomic, assign) BOOL emailRecycled; + +/** @property emailVerified + @brief The value is true if the IDP is also the email provider. It means the user owns the + email. + */ +@property(nonatomic, assign) BOOL emailVerified; + +/** @property isNewUser + @brief Flag indicating that the user signing in is a new user and not a returning user. + */ +@property(nonatomic, assign) BOOL isNewUser; + +/** @property profile + @brief Dictionary containing the additional IdP specific information. + */ +@property(nonatomic, readonly, nullable) NSDictionary *profile; + +/** @property username + @brief The name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *username; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.m new file mode 100644 index 0000000..5ee39fa --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.m @@ -0,0 +1,76 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyAssertionResponse.h" + +@implementation FIRVerifyAssertionResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _federatedID = [dictionary[@"federatedId"] copy]; + _providerID = [dictionary[@"providerId"] copy]; + _localID = [dictionary[@"localId"] copy]; + _emailRecycled = [dictionary[@"emailRecycled"] boolValue]; + _emailVerified = [dictionary[@"emailVerified"] boolValue]; + _email = [dictionary[@"email"] copy]; + _inputEmail = [dictionary[@"inputEmail"] copy]; + _originalEmail = [dictionary[@"originalEmail"] copy]; + _oauthRequestToken = [dictionary[@"oauthRequestToken"] copy]; + _oauthScope = [dictionary[@"oauthScope"] copy]; + _firstName = [dictionary[@"firstName"] copy]; + _lastName = [dictionary[@"lastName"] copy]; + _fullName = [dictionary[@"fullName"] copy]; + _nickName = [dictionary[@"nickName"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + _IDToken = [dictionary[@"idToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _isNewUser = [dictionary[@"isNewUser"] boolValue]; + id rawUserInfo = dictionary[@"rawUserInfo"]; + if ([rawUserInfo isKindOfClass:[NSString class]]) { + NSData *data = [rawUserInfo dataUsingEncoding:NSUTF8StringEncoding]; + rawUserInfo = [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingMutableLeaves + error:nil]; + } + if ([rawUserInfo isKindOfClass:[NSDictionary class]]) { + _profile = [[NSDictionary alloc] initWithDictionary:rawUserInfo + copyItems:YES]; + } + _username = [dictionary[@"username"] copy]; + _action = [dictionary[@"action"] copy]; + _language = [dictionary[@"language"] copy]; + _timeZone = [dictionary[@"timeZone"] copy]; + _photoURL = dictionary[@"photoUrl"] ? [NSURL URLWithString:dictionary[@"photoUrl"]] : nil; + _dateOfBirth = [dictionary[@"dateOfBirth"] copy]; + _context = [dictionary[@"context"] copy]; + _needConfirmation = [dictionary[@"needConfirmation"] boolValue]; + id verifiedProvider = dictionary[@"verifiedProvider"]; + if ([verifiedProvider isKindOfClass:[NSString class]]) { + NSData *data = [verifiedProvider dataUsingEncoding:NSUTF8StringEncoding]; + verifiedProvider = [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingMutableLeaves + error:nil]; + } + if ([verifiedProvider isKindOfClass:[NSArray class]]) { + _verifiedProvider = [[NSArray alloc] initWithArray:verifiedProvider + copyItems:YES]; + } + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.h new file mode 100644 index 0000000..a235788 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRIdentityToolkitRequest.h" + +#import "FIRAuthRPCRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRVerifyClientRequest : FIRIdentityToolkitRequest + +/** @property appToken + @brief The APNS device token. + */ +@property(nonatomic, readonly, nullable) NSString *appToken; + +/** @property isSandbox + @brief The flag that denotes if the appToken pertains to Sandbox or Production. + */ +@property(nonatomic, assign, readonly) BOOL isSandbox; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithToken:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithAppToken:isSandbox:requestConfiguration: + @brief Designated initializer. + @param appToken The APNS device token. + @param isSandbox The flag indicating whether or not the app token provided is for Sandbox or + Production. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithAppToken:(nullable NSString *)appToken + isSandbox:(BOOL)isSandbox + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.m new file mode 100644 index 0000000..101f4ef --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.m @@ -0,0 +1,63 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyClientRequest.h" + + +NS_ASSUME_NONNULL_BEGIN + +/** @var kVerifyClientEndpoint + @brief The endpoint for the verifyClient request. + */ +static NSString *const kVerifyClientEndpoint = @"verifyClient"; + +/** @var kAppTokenKey + @brief The key for the appToken request paramenter. + */ +static NSString *const kAPPTokenKey = @"appToken"; + +/** @var kIsSandboxKey + @brief The key for the isSandbox request parameter + */ +static NSString *const kIsSandboxKey = @"isSandbox"; + +@implementation FIRVerifyClientRequest + +- (nullable instancetype)initWithAppToken:(nullable NSString *)appToken + isSandbox:(BOOL)isSandbox + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyClientEndpoint requestConfiguration:requestConfiguration]; + if (self) { + _appToken = appToken; + _isSandbox = isSandbox; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *__autoreleasing _Nullable *)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_appToken) { + postBody[kAPPTokenKey] = _appToken; + } + if (_isSandbox) { + postBody[kIsSandboxKey] = @YES; + } + return postBody; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.h new file mode 100644 index 0000000..794256a --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRVerifyClientResponse : NSObject + +/** @property receipt + @brief Receipt that the APNS token was successfully validated with APNS. + */ +@property(nonatomic, copy, readonly, nullable) NSString *receipt; + +/** @property suggestedTimeOut + @brief The date after which delivery of the silent push notification is considered to have + failed. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *suggestedTimeOutDate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.m new file mode 100644 index 0000000..c2477d2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyClientResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRVerifyClientResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _receipt = dictionary[@"receipt"]; + _suggestedTimeOutDate = [dictionary[@"suggestedTimeout"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"suggestedTimeout"] doubleValue]] : nil; + return YES; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.h new file mode 100644 index 0000000..84bad05 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.h @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyCustomTokenRequest + @brief Represents the parameters for the verifyCustomToken endpoint. + */ +@interface FIRVerifyCustomTokenRequest : FIRIdentityToolkitRequest + +/** @property token + @brief The self-signed token from the client's BYOAuth server. + */ +@property(nonatomic, copy, readonly) NSString *token; + +/** @property returnSecureToken + @brief Whether the response should return access token and refresh token directly. + @remarks The default value is @c YES . + */ +@property(nonatomic, assign) BOOL returnSecureToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithToken:requestConfiguration: instead. + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint requestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration NS_UNAVAILABLE; + +/** @fn initWithToken:requestConfiguration: + @brief Designated initializer. + @param token The self-signed token from the client's BYOAuth server. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithToken:(NSString *)token + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.m new file mode 100644 index 0000000..79e60f4 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.m @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyCustomTokenRequest.h" + +/** @var kVerifyCustomTokenEndpoint + @brief The "verifyPassword" endpoint. + */ +static NSString *const kVerifyCustomTokenEndpoint = @"verifyCustomToken"; + +/** @var kTokenKey + @brief The key for the "token" value in the request. + */ +static NSString *const kTokenKey = @"token"; + +/** @var kReturnSecureTokenKey + @brief The key for the "returnSecureToken" value in the request. + */ +static NSString *const kReturnSecureTokenKey = @"returnSecureToken"; + +@implementation FIRVerifyCustomTokenRequest + +- (nullable instancetype)initWithToken:(NSString *)token + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyCustomTokenEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _token = [token copy]; + _returnSecureToken = YES; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *body = [@{ + kTokenKey : _token + } mutableCopy]; + if (_returnSecureToken) { + body[kReturnSecureTokenKey] = @YES; + } + return body; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.h new file mode 100644 index 0000000..6957bf3 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyCustomTokenResponse + @brief Represents the response from the verifyCustomToken endpoint. + */ +@interface FIRVerifyCustomTokenResponse : NSObject + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +/** @property isNewUser + @brief Flag indicating that the user signing in is a new user and not a returning user. + */ +@property(nonatomic, assign) BOOL isNewUser; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.m new file mode 100644 index 0000000..b6c3818 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.m @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyCustomTokenResponse.h" + +@implementation FIRVerifyCustomTokenResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _IDToken = [dictionary[@"idToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _isNewUser = [dictionary[@"isNewUser"] boolValue]; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.h new file mode 100644 index 0000000..39eb388 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.h @@ -0,0 +1,81 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCRequest.h" +#import "FIRIdentityToolkitRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyPasswordRequest + @brief Represents the parameters for the verifyPassword endpoint. + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyPassword + */ +@interface FIRVerifyPasswordRequest : FIRIdentityToolkitRequest + +/** @property email + @brief The email of the user. + */ +@property(nonatomic, copy) NSString *email; + +/** @property password + @brief The password inputed by the user. + */ +@property(nonatomic, copy) NSString *password; + +/** @property pendingIDToken + @brief The GITKit token for the non-trusted IDP, which is to be confirmed by the user. + */ +@property(nonatomic, copy, nullable) NSString *pendingIDToken; + +/** @property captchaChallenge + @brief The captcha challenge. + */ +@property(nonatomic, copy, nullable) NSString *captchaChallenge; + +/** @property captchaResponse + @brief Response to the captcha. + */ +@property(nonatomic, copy, nullable) NSString *captchaResponse; + +/** @property returnSecureToken + @brief Whether the response should return access token and refresh token directly. + @remarks The default value is @c YES . + */ +@property(nonatomic, assign) BOOL returnSecureToken; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithEmail:password:requestConfiguration: + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithEmail:password:requestConfiguration: + @brief Designated initializer. + @param email The email of the user. + @param password The password inputed by the user. + @param requestConfiguration The configu + */ +- (nullable instancetype)initWithEmail:(NSString *)email + password:(NSString *)password + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.m new file mode 100644 index 0000000..515a425 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.m @@ -0,0 +1,92 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyPasswordRequest.h" + +/** @var kVerifyPasswordEndpoint + @brief The "verifyPassword" endpoint. + */ +static NSString *const kVerifyPasswordEndpoint = @"verifyPassword"; + +/** @var kEmailKey + @brief The key for the "email" value in the request. + */ +static NSString *const kEmailKey = @"email"; + +/** @var kPasswordKey + @brief The key for the "password" value in the request. + */ +static NSString *const kPasswordKey = @"password"; + +/** @var kPendingIDTokenKey + @brief The key for the "pendingIdToken" value in the request. + */ +static NSString *const kPendingIDTokenKey = @"pendingIdToken"; + +/** @var kCaptchaChallengeKey + @brief The key for the "captchaChallenge" value in the request. + */ +static NSString *const kCaptchaChallengeKey = @"captchaChallenge"; + +/** @var kCaptchaResponseKey + @brief The key for the "captchaResponse" value in the request. + */ +static NSString *const kCaptchaResponseKey = @"captchaResponse"; + +/** @var kReturnSecureTokenKey + @brief The key for the "returnSecureToken" value in the request. + */ +static NSString *const kReturnSecureTokenKey = @"returnSecureToken"; + +@implementation FIRVerifyPasswordRequest + +- (nullable instancetype)initWithEmail:(NSString *)email + password:(NSString *)password + requestConfiguration:(nonnull FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyPasswordEndpoint + requestConfiguration:requestConfiguration]; + if (self) { + _email = [email copy]; + _password = [password copy]; + _returnSecureToken = YES; + } + return self; +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *_Nullable *_Nullable)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_email) { + postBody[kEmailKey] = _email; + } + if (_password) { + postBody[kPasswordKey] = _password; + } + if (_pendingIDToken) { + postBody[kPendingIDTokenKey] = _pendingIDToken; + } + if (_captchaChallenge) { + postBody[kCaptchaChallengeKey] = _captchaChallenge; + } + if (_captchaResponse) { + postBody[kCaptchaResponseKey] = _captchaResponse; + } + if (_returnSecureToken) { + postBody[kReturnSecureTokenKey] = @YES; + } + return postBody; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.h new file mode 100644 index 0000000..bed13be --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.h @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @class FIRVerifyPasswordResponse + @brief Represents the response from the verifyPassword endpoint. + @remarks Possible error codes: + - FIRAuthInternalErrorCodeUserDisabled + - FIRAuthInternalErrorCodeEmailNotFound + @see https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyPassword + */ +@interface FIRVerifyPasswordResponse : NSObject + +/** @property localID + @brief The RP local ID if it's already been mapped to the IdP account identified by the + federated ID. + */ +@property(nonatomic, strong, readonly, nullable) NSString *localID; + +/** @property email + @brief The email returned by the IdP. NOTE: The federated login user may not own the email. + */ +@property(nonatomic, strong, readonly, nullable) NSString *email; + +/** @property displayName + @brief The display name of the user. + */ +@property(nonatomic, strong, readonly, nullable) NSString *displayName; + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +/** @property photoURL + @brief The URI of the public accessible profile picture. + */ +@property(nonatomic, strong, readonly, nullable) NSURL *photoURL; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.m new file mode 100644 index 0000000..71b4edd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.m @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyPasswordResponse.h" + +@implementation FIRVerifyPasswordResponse + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _localID = [dictionary[@"localId"] copy]; + _email = [dictionary[@"email"] copy]; + _displayName = [dictionary[@"displayName"] copy]; + _IDToken = [dictionary[@"idToken"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _photoURL = dictionary[@"photoUrl"] ? [NSURL URLWithString:dictionary[@"photoUrl"]] : nil; + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.h new file mode 100644 index 0000000..07988f1 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.h @@ -0,0 +1,91 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRIdentityToolkitRequest.h" + +#import "FIRAuthOperationType.h" +#import "FIRAuthRPCRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRVerifyPhoneNumberRequest : FIRIdentityToolkitRequest + +/** @property verificationID + @brief The verification ID obtained from the response of @c sendVerificationCode. +*/ +@property(nonatomic, readonly, nullable) NSString *verificationID; + +/** @property verificationCode + @brief The verification code provided by the user. +*/ +@property(nonatomic, readonly, nullable) NSString *verificationCode; + +/** @property accessToken + @brief The STS Access Token for the authenticated user. + */ +@property(nonatomic, copy, nullable) NSString *accessToken; + +/** @var temporaryProof + @brief The temporary proof code, previously returned from the backend. + */ +@property(nonatomic, readonly, nonnull) NSString *temporaryProof; + +/** @var phoneNumber + @brief The phone number to be verified in the request. + */ +@property(nonatomic, readonly, nonnull) NSString *phoneNumber; + +/** @var operation + @brief The type of operation triggering this verify phone number request. + */ +@property(nonatomic, assign, readonly) FIRAuthOperationType operation; + +/** @fn initWithEndpoint:requestConfiguration: + @brief Please use initWithVerificationID:verificationCode:requestConfiguration + */ +- (nullable instancetype)initWithEndpoint:(NSString *)endpoint + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_UNAVAILABLE; + +/** @fn initWithTemporaryProof:phoneNumberAPIKey + @brief Designated initializer. + @param temporaryProof The temporary proof sent by the backed. + @param phoneNumber The phone number associated with the credential to be signed in. + @param operation Indicates what operation triggered the verify phone number request. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithTemporaryProof:(NSString *)temporaryProof + phoneNumber:(NSString *)phoneNumber + operation:(FIRAuthOperationType)operation + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +/** @fn initWithVerificationID:verificationCode:requestConfiguration + @brief Designated initializer. + @param verificationID The verification ID obtained from the response of @c sendVerificationCode. + @param verificationCode The verification code provided by the user. + @param operation Indicates what operation triggered the verify phone number request. + @param requestConfiguration An object containing configurations to be added to the request. + */ +- (nullable instancetype)initWithVerificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode + operation:(FIRAuthOperationType)operation + requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.m new file mode 100644 index 0000000..022ab9e --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.m @@ -0,0 +1,133 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyPhoneNumberRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @var kVerifyPhoneNumberEndPoint + @brief The "verifyPhoneNumber" endpoint. + */ +static NSString *const kVerifyPhoneNumberEndPoint = @"verifyPhoneNumber"; + +/** @var kVerificationIDKey + @brief The key for the verification ID parameter in the request. + */ +static NSString *const kVerificationIDKey = @"sessionInfo"; + +/** @var kVerificationCodeKey + @brief The key for the verification code parameter in the request. + */ +static NSString *const kVerificationCodeKey = @"code"; + +/** @var kIDTokenKey + @brief The key for the "ID Token" value in the request. + */ +static NSString *const kIDTokenKey = @"idToken"; + +/** @var kTemporaryProofKey + @brief The key for the temporary proof value in the request. + */ +static NSString *const kTemporaryProofKey = @"temporaryProof"; + +/** @var kPhoneNumberKey + @brief The key for the phone number value in the request. + */ +static NSString *const kPhoneNumberKey = @"phoneNumber"; + +/** @var kOperationKey + @brief The key for the operation value in the request. + */ +static NSString *const kOperationKey = @"operation"; + +@implementation FIRVerifyPhoneNumberRequest + +- (nullable instancetype)initWithTemporaryProof:(NSString *)temporaryProof + phoneNumber:(NSString *)phoneNumber + operation:(FIRAuthOperationType)operation + requestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyPhoneNumberEndPoint + requestConfiguration:requestConfiguration]; + if (self) { + _temporaryProof = [temporaryProof copy]; + _phoneNumber = [phoneNumber copy]; + _operation = operation; + } + return self; +} + +- (nullable instancetype)initWithVerificationID:(NSString *)verificationID + verificationCode:(NSString *)verificationCode + operation:(FIRAuthOperationType)operation + requestConfiguration: + (FIRAuthRequestConfiguration *)requestConfiguration { + self = [super initWithEndpoint:kVerifyPhoneNumberEndPoint + requestConfiguration:requestConfiguration]; + if (self) { + _verificationID = verificationID; + _verificationCode = verificationCode; + _operation = operation; + } + return self; +} + +/** @fn FIRAuthOperationString + @brief Returns a string object corresponding to the provided FIRAuthOperationType value. + @param operationType The value of the FIRAuthOperationType enum which will be translated to its + corresponding string value. + @return The string value corresponding to the FIRAuthOperationType argument. + */ +NSString *const FIRAuthOperationString(FIRAuthOperationType operationType) { + switch(operationType){ + case FIRAuthOperationTypeUnspecified: + return @"VERIFY_OP_UNSPECIFIED"; + case FIRAuthOperationTypeSignUpOrSignIn: + return @"SIGN_UP_OR_IN"; + case FIRAuthOperationTypeReauth: + return @"REAUTH"; + case FIRAuthOperationTypeLink: + return @"LINK"; + case FIRAuthOperationTypeUpdate: + return @"UPDATE"; + } +} + +- (nullable id)unencodedHTTPRequestBodyWithError:(NSError *__autoreleasing _Nullable *)error { + NSMutableDictionary *postBody = [NSMutableDictionary dictionary]; + if (_verificationID) { + postBody[kVerificationIDKey] = _verificationID; + } + if (_verificationCode) { + postBody[kVerificationCodeKey] = _verificationCode; + } + if (_accessToken) { + postBody[kIDTokenKey] = _accessToken; + } + if (_temporaryProof) { + postBody[kTemporaryProofKey] = _temporaryProof; + } + if (_phoneNumber) { + postBody[kPhoneNumberKey] = _phoneNumber; + } + NSString *operation = FIRAuthOperationString(_operation); + postBody[kOperationKey] = operation; + return postBody; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.h b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.h new file mode 100644 index 0000000..b0ba5dd --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.h @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAuthRPCResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRVerifyPhoneNumberResponse : NSObject + +/** @property IDToken + @brief Either an authorization code suitable for performing an STS token exchange, or the + access token from Secure Token Service, depending on whether @c returnSecureToken is set + on the request. + */ +@property(nonatomic, strong, readonly, nullable) NSString *IDToken; + +/** @property refreshToken + @brief The refresh token from Secure Token Service. + */ +@property(nonatomic, strong, readonly, nullable) NSString *refreshToken; + +/** @property localID + @brief The Firebase Auth user ID. + */ +@property(nonatomic, strong, readonly, nullable) NSString *localID; + +/** @property phoneNumber + @brief The verified phone number. + */ +@property(nonatomic, strong, readonly, nullable) NSString *phoneNumber; + +/** @property temporaryProof + @brief The temporary proof code returned by the backend. + */ +@property(nonatomic, strong, readonly, nullable) NSString *temporaryProof; + +/** @property isNewUser + @brief Flag indicating that the user signing in is a new user and not a returning user. + */ +@property(nonatomic, assign) BOOL isNewUser; + +/** @property approximateExpirationDate + @brief The approximate expiration date of the access token. + */ +@property(nonatomic, copy, readonly, nullable) NSDate *approximateExpirationDate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.m b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.m new file mode 100644 index 0000000..acba2c2 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.m @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRVerifyPhoneNumberResponse.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation FIRVerifyPhoneNumberResponse + +- (nullable NSString *)expectedKind { + return nil; +} + +- (BOOL)setWithDictionary:(NSDictionary *)dictionary + error:(NSError *_Nullable *_Nullable)error { + _IDToken = [dictionary[@"idToken"] copy]; + _refreshToken = [dictionary[@"refreshToken"] copy]; + _isNewUser = [dictionary[@"isNewUser"] boolValue]; + _localID = [dictionary[@"localId"] copy]; + _phoneNumber = [dictionary[@"phoneNumber"] copy]; + _temporaryProof = [dictionary[@"temporaryProof"] copy]; + _approximateExpirationDate = [dictionary[@"expiresIn"] isKindOfClass:[NSString class]] ? + [NSDate dateWithTimeIntervalSinceNow:[dictionary[@"expiresIn"] doubleValue]] : nil; + return YES; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseAuth/LICENSE b/My Mind/Pods/FirebaseAuth/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseAuth/README.md b/My Mind/Pods/FirebaseAuth/README.md new file mode 100644 index 0000000..d414a4c --- /dev/null +++ b/My Mind/Pods/FirebaseAuth/README.md @@ -0,0 +1,193 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Code Formatting + +Travis will verify that any code changes are done in a style compliant way. Install +`clang-format` and `swiftformat`. +This command will get the right `clang-format` version: + +`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/0743d748ba8b41eec074a0a787dc80219142c525/Formula/clang-format.rb` + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseAuthInterop/Interop/Auth/Public/FIRAuthInterop.h b/My Mind/Pods/FirebaseAuthInterop/Interop/Auth/Public/FIRAuthInterop.h new file mode 100644 index 0000000..5c365a3 --- /dev/null +++ b/My Mind/Pods/FirebaseAuthInterop/Interop/Auth/Public/FIRAuthInterop.h @@ -0,0 +1,42 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRAuthInterop_h +#define FIRAuthInterop_h + +NS_ASSUME_NONNULL_BEGIN + +/** @typedef FIRTokenCallback + @brief The type of block which gets called when a token is ready. + */ +typedef void (^FIRTokenCallback)(NSString *_Nullable token, NSError *_Nullable error) + NS_SWIFT_NAME(TokenCallback); + +/// Common methods for Auth interoperability. +NS_SWIFT_NAME(AuthInterop) +@protocol FIRAuthInterop + +/// Retrieves the Firebase authentication token, possibly refreshing it if it has expired. +- (void)getTokenForcingRefresh:(BOOL)forceRefresh withCallback:(FIRTokenCallback)callback; + +/// Get the current Auth user's UID. Returns nil if there is no user signed in. +- (nullable NSString *)getUserID; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* FIRAuthInterop_h */ diff --git a/My Mind/Pods/FirebaseAuthInterop/LICENSE b/My Mind/Pods/FirebaseAuthInterop/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseAuthInterop/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseAuthInterop/README.md b/My Mind/Pods/FirebaseAuthInterop/README.md new file mode 100644 index 0000000..4414b3e --- /dev/null +++ b/My Mind/Pods/FirebaseAuthInterop/README.md @@ -0,0 +1,179 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseMessaging and FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +An experimental Carthage distribution is now available. See +[Carthage](Carthage.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[AuthSamples/README.md](AuthSamples/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m new file mode 100644 index 0000000..33aa168 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAnalyticsConfiguration.m @@ -0,0 +1,69 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRAnalyticsConfiguration.h" + +#import "Private/FIRAnalyticsConfiguration+Internal.h" + +@implementation FIRAnalyticsConfiguration + ++ (FIRAnalyticsConfiguration *)sharedInstance { + static FIRAnalyticsConfiguration *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[FIRAnalyticsConfiguration alloc] init]; + }); + return sharedInstance; +} + +- (void)postNotificationName:(NSString *)name value:(id)value { + if (!name.length || !value) { + return; + } + [[NSNotificationCenter defaultCenter] postNotificationName:name + object:self + userInfo:@{name : value}]; +} + +- (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval { + [self postNotificationName:kFIRAnalyticsConfigurationSetMinimumSessionIntervalNotification + value:@(minimumSessionInterval)]; +} + +- (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval { + [self postNotificationName:kFIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification + value:@(sessionTimeoutInterval)]; +} + +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled { + [self setAnalyticsCollectionEnabled:analyticsCollectionEnabled persistSetting:YES]; +} + +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled + persistSetting:(BOOL)shouldPersist { + // Persist the measurementEnabledState. Use FIRAnalyticsEnabledState values instead of YES/NO. + FIRAnalyticsEnabledState analyticsEnabledState = + analyticsCollectionEnabled ? kFIRAnalyticsEnabledStateSetYes : kFIRAnalyticsEnabledStateSetNo; + if (shouldPersist) { + NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; + [userDefaults setObject:@(analyticsEnabledState) + forKey:kFIRAPersistedConfigMeasurementEnabledStateKey]; + [userDefaults synchronize]; + } + + [self postNotificationName:kFIRAnalyticsConfigurationSetEnabledNotification + value:@(analyticsCollectionEnabled)]; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRApp.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRApp.m new file mode 100644 index 0000000..29570a8 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRApp.m @@ -0,0 +1,773 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#import "FIRApp.h" +#import "FIRConfiguration.h" +#import "Private/FIRAnalyticsConfiguration+Internal.h" +#import "Private/FIRAppInternal.h" +#import "Private/FIRBundleUtil.h" +#import "Private/FIRComponentContainerInternal.h" +#import "Private/FIRCoreConfigurable.h" +#import "Private/FIRLogger.h" +#import "Private/FIROptionsInternal.h" + +NSString *const kFIRServiceAdMob = @"AdMob"; +NSString *const kFIRServiceAuth = @"Auth"; +NSString *const kFIRServiceAuthUI = @"AuthUI"; +NSString *const kFIRServiceCrash = @"Crash"; +NSString *const kFIRServiceDatabase = @"Database"; +NSString *const kFIRServiceDynamicLinks = @"DynamicLinks"; +NSString *const kFIRServiceFirestore = @"Firestore"; +NSString *const kFIRServiceFunctions = @"Functions"; +NSString *const kFIRServiceInstanceID = @"InstanceID"; +NSString *const kFIRServiceInvites = @"Invites"; +NSString *const kFIRServiceMessaging = @"Messaging"; +NSString *const kFIRServiceMeasurement = @"Measurement"; +NSString *const kFIRServicePerformance = @"Performance"; +NSString *const kFIRServiceRemoteConfig = @"RemoteConfig"; +NSString *const kFIRServiceStorage = @"Storage"; +NSString *const kGGLServiceAnalytics = @"Analytics"; +NSString *const kGGLServiceSignIn = @"SignIn"; + +NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT"; +NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification"; +NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification"; +NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey"; +NSString *const kFIRAppNameKey = @"FIRAppNameKey"; +NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey"; + +NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat = + @"/google/firebase/global_data_collection_enabled:%@"; +NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey = + @"FirebaseDataCollectionDefaultEnabled"; + +NSString *const kFIRAppDiagnosticsNotification = @"FIRAppDiagnosticsNotification"; + +NSString *const kFIRAppDiagnosticsConfigurationTypeKey = @"ConfigType"; +NSString *const kFIRAppDiagnosticsErrorKey = @"Error"; +NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRApp"; +NSString *const kFIRAppDiagnosticsSDKNameKey = @"SDKName"; +NSString *const kFIRAppDiagnosticsSDKVersionKey = @"SDKVersion"; + +// Auth internal notification notification and key. +NSString *const FIRAuthStateDidChangeInternalNotification = + @"FIRAuthStateDidChangeInternalNotification"; +NSString *const FIRAuthStateDidChangeInternalNotificationAppKey = + @"FIRAuthStateDidChangeInternalNotificationAppKey"; +NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey = + @"FIRAuthStateDidChangeInternalNotificationTokenKey"; +NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey = + @"FIRAuthStateDidChangeInternalNotificationUIDKey"; + +/** + * The URL to download plist files. + */ +static NSString *const kPlistURL = @"https://console.firebase.google.com/"; + +/** + * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle + * events from Core. + */ +static NSMutableArray> *gRegisteredAsConfigurable; + +@interface FIRApp () + +#ifdef DEBUG +@property(nonatomic) BOOL alreadyOutputDataCollectionFlag; +#endif // DEBUG + +@end + +@implementation FIRApp + +// This is necessary since our custom getter prevents `_options` from being created. +@synthesize options = _options; + +static NSMutableDictionary *sAllApps; +static FIRApp *sDefaultApp; +static NSMutableDictionary *sLibraryVersions; + ++ (void)configure { + FIROptions *options = [FIROptions defaultOptions]; + if (!options) { + // Read the Info.plist to see if the flag is set. At this point we can't check any user defaults + // since the app isn't configured at all, so only rely on the Info.plist value. + NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist]; + if (collectionEnabledPlistValue == nil || [collectionEnabledPlistValue boolValue]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsErrorKey : [FIRApp errorForMissingOptions] + }]; + } + + [NSException raise:kFirebaseCoreErrorDomain + format: + @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find " + @"a valid GoogleService-Info.plist in your project. Please download one " + @"from %@.", + kPlistURL]; + } + [FIRApp configureWithOptions:options]; +#if TARGET_OS_OSX || TARGET_OS_TV + FIRLogNotice(kFIRLoggerCore, @"I-COR000028", + @"tvOS and macOS SDK support is not part of the official Firebase product. " + @"Instead they are community supported. Details at " + @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md."); +#endif +} + ++ (void)configureWithOptions:(FIROptions *)options { + if (!options) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"Options is nil. Please pass a valid options."]; + } + [FIRApp configureWithName:kFIRDefaultAppName options:options]; +} + ++ (void)configureWithName:(NSString *)name options:(FIROptions *)options { + if (!name || !options) { + [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."]; + } + if (name.length == 0) { + [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."]; + } + + if ([name isEqualToString:kFIRDefaultAppName]) { + if (sDefaultApp) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"Default app has already been configured."]; + } + + FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app."); + } else { + // Validate the app name and ensure it hasn't been configured already. + for (NSUInteger charIndex = 0; charIndex < name.length; charIndex++) { + char character = [name characterAtIndex:charIndex]; + if (!((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || + (character >= '0' && character <= '9') || character == '_' || character == '-')) { + [NSException raise:kFirebaseCoreErrorDomain + format: + @"App name should only contain Letters, " + @"Numbers, Underscores, and Dashes."]; + } + } + + if (sAllApps && sAllApps[name]) { + [NSException raise:kFirebaseCoreErrorDomain + format:@"App named %@ has already been configured.", name]; + } + + FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name); + } + + @synchronized(self) { + FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options]; + if (app.isDefaultApp) { + sDefaultApp = app; + } + + [FIRApp addAppToAppDictionary:app]; + [FIRApp sendNotificationsToSDKs:app]; + } +} + ++ (FIRApp *)defaultApp { + if (sDefaultApp) { + return sDefaultApp; + } + FIRLogError(kFIRLoggerCore, @"I-COR000003", + @"The default Firebase app has not yet been " + @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your " + @"application initialization. Read more: https://goo.gl/ctyzm8."); + return nil; +} + ++ (FIRApp *)appNamed:(NSString *)name { + @synchronized(self) { + if (sAllApps) { + FIRApp *app = sAllApps[name]; + if (app) { + return app; + } + } + FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name); + return nil; + } +} + ++ (NSDictionary *)allApps { + @synchronized(self) { + if (!sAllApps) { + FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet."); + } + NSDictionary *dict = [NSDictionary dictionaryWithDictionary:sAllApps]; + return dict; + } +} + +// Public only for tests ++ (void)resetApps { + sDefaultApp = nil; + [sAllApps removeAllObjects]; + sAllApps = nil; + [sLibraryVersions removeAllObjects]; + sLibraryVersions = nil; +} + +- (void)deleteApp:(FIRAppVoidBoolCallback)completion { + @synchronized([self class]) { + if (sAllApps && sAllApps[self.name]) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name); + + // Remove all cached instances from the container before deleting the app. + [self.container removeAllCachedInstances]; + + [sAllApps removeObjectForKey:self.name]; + [self clearDataCollectionSwitchFromUserDefaults]; + if ([self.name isEqualToString:kFIRDefaultAppName]) { + sDefaultApp = nil; + } + NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name}; + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification + object:[self class] + userInfo:appInfoDict]; + completion(YES); + } else { + FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist."); + completion(NO); + } + } +} + ++ (void)addAppToAppDictionary:(FIRApp *)app { + if (!sAllApps) { + sAllApps = [NSMutableDictionary dictionary]; + } + if ([app configureCore]) { + sAllApps[app.name] = app; + } else { + [NSException raise:kFirebaseCoreErrorDomain + format: + @"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in " + @"GoogleService-Info.plist or set in the customized options."]; + } +} + +- (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options { + self = [super init]; + if (self) { + _name = [name copy]; + _options = [options copy]; + _options.editingLocked = YES; + _isDefaultApp = [name isEqualToString:kFIRDefaultAppName]; + _container = [[FIRComponentContainer alloc] initWithApp:self]; + } + return self; +} + +- (BOOL)configureCore { + [self checkExpectedBundleID]; + if (![self isAppIDValid]) { + if (_options.usingOptionsFromDefaultPlist && [self isDataCollectionDefaultEnabled]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsErrorKey : [FIRApp errorForInvalidAppID], + }]; + } + return NO; + } + + if ([self isDataCollectionDefaultEnabled]) { + [[NSNotificationCenter defaultCenter] + postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore), + kFIRAppDiagnosticsFIRAppKey : self + }]; + } + +#if TARGET_OS_IOS + // Initialize the Analytics once there is a valid options under default app. Analytics should + // always initialize first by itself before the other SDKs. + if ([self.name isEqualToString:kFIRDefaultAppName]) { + Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics"); + if (!firAnalyticsClass) { + FIRLogWarning(kFIRLoggerCore, @"I-COR000022", + @"Firebase Analytics is not available. To add it, include Firebase/Core in the " + @"Podfile or add FirebaseAnalytics.framework to the Link Build Phase"); + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" + SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:); +#pragma clang diagnostic pop + if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + [firAnalyticsClass performSelector:startWithConfigurationSelector + withObject:[FIRConfiguration sharedInstance].analyticsConfiguration + withObject:_options]; +#pragma clang diagnostic pop + } + } + } +#endif + + return YES; +} + +- (FIROptions *)options { + return [_options copy]; +} + +- (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled { +#ifdef DEBUG + FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.", + dataCollectionDefaultEnabled ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; +#endif // DEBUG + + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name]; + [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key]; + + // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set + // within FIROptions and change the Analytics value if necessary. Analytics only works with the + // default app, so return if this isn't the default app. + if (!self.isDefaultApp) { + return; + } + + // Check if the Analytics flag is explicitly set. If so, no further actions are necessary. + if ([self.options isAnalyticsCollectionExpicitlySet]) { + return; + } + + // The Analytics flag has not been explicitly set, so update with the value being set. + [[FIRAnalyticsConfiguration sharedInstance] + setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled + persistSetting:NO]; +} + +- (BOOL)isDataCollectionDefaultEnabled { + // Check if it's been manually set before in code, and use that as the higher priority value. + NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self]; + if (defaultsObject != nil) { +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.", + [defaultsObject boolValue] ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return [defaultsObject boolValue]; + } + + // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`. + // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has + // no performance impact calling multiple times. + NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist]; + if (collectionEnabledPlistValue != nil) { +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.", + [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled"); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return [collectionEnabledPlistValue boolValue]; + } + +#ifdef DEBUG + if (!self.alreadyOutputDataCollectionFlag) { + FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set."); + self.alreadyOutputDataCollectionFlag = YES; + } +#endif // DEBUG + return YES; +} + +#pragma mark - private + ++ (void)sendNotificationsToSDKs:(FIRApp *)app { + // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`. + NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp]; + NSDictionary *appInfoDict = @{ + kFIRAppNameKey : app.name, + kFIRAppIsDefaultAppKey : isDefaultApp, + kFIRGoogleAppIDKey : app.options.googleAppID + }; + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification + object:self + userInfo:appInfoDict]; + + // This is the new way of sending information to SDKs. + // TODO: Do we want this on a background thread, maybe? + for (Class library in gRegisteredAsConfigurable) { + [library configureWithApp:app]; + } +} + ++ (NSError *)errorForMissingOptions { + NSDictionary *errorDict = @{ + NSLocalizedDescriptionKey : + @"Unable to parse GoogleService-Info.plist in order to configure services.", + NSLocalizedRecoverySuggestionErrorKey : + @"Check formatting and location of GoogleService-Info.plist." + }; + return [NSError errorWithDomain:kFirebaseCoreErrorDomain + code:FIRErrorCodeInvalidPlistFile + userInfo:errorDict]; +} + ++ (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain + errorCode:(FIRErrorCode)code + service:(NSString *)service + reason:(NSString *)reason { + NSString *description = + [NSString stringWithFormat:@"Configuration failed for service %@.", service]; + NSDictionary *errorDict = + @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason}; + return [NSError errorWithDomain:domain code:code userInfo:errorDict]; +} + ++ (NSError *)errorForInvalidAppID { + NSDictionary *errorDict = @{ + NSLocalizedDescriptionKey : @"Unable to validate Google App ID", + NSLocalizedRecoverySuggestionErrorKey : + @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the " + @"customized options." + }; + return [NSError errorWithDomain:kFirebaseCoreErrorDomain + code:FIRErrorCodeInvalidAppID + userInfo:errorDict]; +} + ++ (void)registerAsConfigurable:(Class)klass { + // This is called at +load time, keep the work to a minimum. + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gRegisteredAsConfigurable = [[NSMutableArray alloc] initWithCapacity:1]; + }); + + NSAssert([(Class)klass conformsToProtocol:@protocol(FIRCoreConfigurable)], + @"The class being registered (%@) must conform to `FIRCoreConfigurable`.", klass); + [gRegisteredAsConfigurable addObject:klass]; +} + ++ (BOOL)isDefaultAppConfigured { + return (sDefaultApp != nil); +} + ++ (void)registerLibrary:(nonnull NSString *)library withVersion:(nonnull NSString *)version { + // Create the set of characters which aren't allowed, only if this feature is used. + NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet]; + [allowedSet addCharactersInString:@"-_."]; + NSCharacterSet *disallowedSet = [allowedSet invertedSet]; + // Make sure the library name and version strings do not contain unexpected characters, and + // add the name/version pair to the dictionary. + if ([library rangeOfCharacterFromSet:disallowedSet].location == NSNotFound && + [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) { + if (!sLibraryVersions) { + sLibraryVersions = [[NSMutableDictionary alloc] init]; + } + sLibraryVersions[library] = version; + } else { + FIRLogError(kFIRLoggerCore, @"I-COR000027", + @"The library name (%@) or version number (%@) contain illegal characters. " + @"Only alphanumeric, dash, underscore and period characters are allowed.", + library, version); + } +} + ++ (NSString *)firebaseUserAgent { + NSMutableArray *libraries = + [[NSMutableArray alloc] initWithCapacity:sLibraryVersions.count]; + for (NSString *libraryName in sLibraryVersions) { + [libraries + addObject:[NSString stringWithFormat:@"%@/%@", libraryName, sLibraryVersions[libraryName]]]; + } + [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + return [libraries componentsJoinedByString:@" "]; +} + +- (void)checkExpectedBundleID { + NSArray *bundles = [FIRBundleUtil relevantBundles]; + NSString *expectedBundleID = [self expectedBundleID]; + // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for + // backward compatibility. + if (expectedBundleID != nil && + ![FIRBundleUtil hasBundleIdentifier:expectedBundleID inBundles:bundles]) { + FIRLogError(kFIRLoggerCore, @"I-COR000008", + @"The project's Bundle ID is inconsistent with " + @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are " + @"using a customized options. To ensure that everything can be configured " + @"correctly, you may need to make the Bundle IDs consistent. To continue with this " + @"plist file, you may change your app's bundle identifier to '%@'. Or you can " + @"download a new configuration file that matches your bundle identifier from %@ " + @"and replace the current one.", + kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL); + } +} + +#pragma mark - private - App ID Validation + +/** + * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file. + * This is the main method for validating app ID. + * + * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise. + */ +- (BOOL)isAppIDValid { + NSString *appID = _options.googleAppID; + BOOL isValid = [FIRApp validateAppID:appID]; + if (!isValid) { + NSString *expectedBundleID = [self expectedBundleID]; + FIRLogError(kFIRLoggerCore, @"I-COR000009", + @"The GOOGLE_APP_ID either in the plist file " + @"'%@.%@' or the one set in the customized options is invalid. If you are using " + @"the plist file, use the iOS version of bundle identifier to download the file, " + @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle " + @"identifier to '%@'. Or you can download a new configuration file that matches " + @"your bundle identifier from %@ and replace the current one.", + kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL); + }; + return isValid; +} + ++ (BOOL)validateAppID:(NSString *)appID { + // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not + // have a valid fingerprint, otherwise we just warn about the potential issue. + if (!appID.length) { + return NO; + } + + // All app IDs must start with at least ":". + NSString *const versionPattern = @"^\\d+:"; + NSRegularExpression *versionRegex = + [NSRegularExpression regularExpressionWithPattern:versionPattern options:0 error:NULL]; + if (!versionRegex) { + return NO; + } + + NSRange appIDRange = NSMakeRange(0, appID.length); + NSArray *versionMatches = [versionRegex matchesInString:appID options:0 range:appIDRange]; + if (versionMatches.count != 1) { + return NO; + } + + NSRange versionRange = [(NSTextCheckingResult *)versionMatches.firstObject range]; + NSString *appIDVersion = [appID substringWithRange:versionRange]; + NSArray *knownVersions = @[ @"1:" ]; + if (![knownVersions containsObject:appIDVersion]) { + // Permit unknown yet properly formatted app ID versions. + return YES; + } + + if (![FIRApp validateAppIDFormat:appID withVersion:appIDVersion]) { + return NO; + } + + if (![FIRApp validateAppIDFingerprint:appID withVersion:appIDVersion]) { + return NO; + } + + return YES; +} + ++ (NSString *)actualBundleID { + return [[NSBundle mainBundle] bundleIdentifier]; +} + +/** + * Validates that the format of the app ID string is what is expected based on the supplied version. + * The version must end in ":". + * + * For v1 app ids the format is expected to be + * '::ios:'. + * + * This method does not verify that the contents of the app id are correct, just that they fulfill + * the expected format. + * + * @param appID Contents of GOOGLE_APP_ID from the plist file. + * @param version Indicates what version of the app id format this string should be. + * @return YES if provided string fufills the expected format, NO otherwise. + */ ++ (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version { + if (!appID.length || !version.length) { + return NO; + } + + if (![version hasSuffix:@":"]) { + return NO; + } + + if (![appID hasPrefix:version]) { + return NO; + } + + NSString *const pattern = @"^\\d+:ios:[a-f0-9]+$"; + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL]; + if (!regex) { + return NO; + } + + NSRange localRange = NSMakeRange(version.length, appID.length - version.length); + NSUInteger numberOfMatches = [regex numberOfMatchesInString:appID options:0 range:localRange]; + if (numberOfMatches != 1) { + return NO; + } + return YES; +} + +/** + * Validates that the fingerprint of the app ID string is what is expected based on the supplied + * version. The version must end in ":". + * + * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated. + * + * @param appID Contents of GOOGLE_APP_ID from the plist file. + * @param version Indicates what version of the app id format this string should be. + * @return YES if provided string fufills the expected fingerprint and the version is known, NO + * otherwise. + */ ++ (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version { + if (!appID.length || !version.length) { + return NO; + } + + if (![version hasSuffix:@":"]) { + return NO; + } + + if (![appID hasPrefix:version]) { + return NO; + } + + // Extract the supplied fingerprint from the supplied app ID. + // This assumes the app ID format is the same for all known versions below. If the app ID format + // changes in future versions, the tokenizing of the app ID format will need to take into account + // the version of the app ID. + NSArray *components = [appID componentsSeparatedByString:@":"]; + if (components.count != 4) { + return NO; + } + + NSString *suppliedFingerprintString = components[3]; + if (!suppliedFingerprintString.length) { + return NO; + } + + uint64_t suppliedFingerprint; + NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString]; + if (![scanner scanHexLongLong:&suppliedFingerprint]) { + return NO; + } + + if ([version isEqual:@"1:"]) { + // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated. + return YES; + } + + // Unknown version. + return NO; +} + +- (NSString *)expectedBundleID { + return _options.bundleID; +} + +// end App ID validation + +#pragma mark - Reading From Plist & User Defaults + +/** + * Clears the data collection switch from the standard NSUserDefaults for easier testing and + * readability. + */ +- (void)clearDataCollectionSwitchFromUserDefaults { + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name]; + [[NSUserDefaults standardUserDefaults] removeObjectForKey:key]; +} + +/** + * Reads the data collection switch from the standard NSUserDefaults for easier testing and + * readability. + */ ++ (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app { + // Read the object in user defaults, and only return if it's an NSNumber. + NSString *key = + [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name]; + id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key]; + if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) { + return collectionEnabledDefaultsObject; + } + + return nil; +} + +/** + * Reads the data collection switch from the Info.plist for easier testing and readability. Will + * only read once from the plist and return the cached value. + */ ++ (nullable NSNumber *)readDataCollectionSwitchFromPlist { + static NSNumber *collectionEnabledPlistObject; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber. + id plistValue = [[NSBundle mainBundle] + objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey]; + if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) { + collectionEnabledPlistObject = (NSNumber *)plistValue; + } + }); + + return collectionEnabledPlistObject; +} + +#pragma mark - Sending Logs + +- (void)sendLogsWithServiceName:(NSString *)serviceName + version:(NSString *)version + error:(NSError *)error { + // If the user has manually turned off data collection, return and don't send logs. + if (![self isDataCollectionDefaultEnabled]) { + return; + } + + NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:@{ + kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeSDK), + kFIRAppDiagnosticsSDKNameKey : serviceName, + kFIRAppDiagnosticsSDKVersionKey : version, + kFIRAppDiagnosticsFIRAppKey : self + }]; + if (error) { + userInfo[kFIRAppDiagnosticsErrorKey] = error; + } + [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDiagnosticsNotification + object:nil + userInfo:userInfo]; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m new file mode 100644 index 0000000..2aecdab --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRAppAssociationRegistration.m @@ -0,0 +1,47 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRAppAssociationRegistration.h" + +#import + +@implementation FIRAppAssociationRegistration + ++ (nullable id)registeredObjectWithHost:(id)host + key:(NSString *)key + creationBlock:(id _Nullable (^)(void))creationBlock { + @synchronized(self) { + SEL dictKey = @selector(registeredObjectWithHost:key:creationBlock:); + NSMutableDictionary *objectsByKey = objc_getAssociatedObject(host, dictKey); + if (!objectsByKey) { + objectsByKey = [[NSMutableDictionary alloc] init]; + objc_setAssociatedObject(host, dictKey, objectsByKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + id obj = objectsByKey[key]; + NSValue *creationBlockBeingCalled = [NSValue valueWithPointer:dictKey]; + if (obj) { + if ([creationBlockBeingCalled isEqual:obj]) { + [NSException raise:@"Reentering registeredObjectWithHost:key:creationBlock: not allowed" + format:@"host: %@ key: %@", host, key]; + } + return obj; + } + objectsByKey[key] = creationBlockBeingCalled; + obj = creationBlock(); + objectsByKey[key] = obj; + return obj; + } +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m new file mode 100644 index 0000000..93ee02e --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRBundleUtil.m @@ -0,0 +1,57 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRBundleUtil.h" + +@implementation FIRBundleUtil + ++ (NSArray *)relevantBundles { + return @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ]; +} + ++ (NSString *)optionsDictionaryPathWithResourceName:(NSString *)resourceName + andFileType:(NSString *)fileType + inBundles:(NSArray *)bundles { + // Loop through all bundles to find the config dict. + for (NSBundle *bundle in bundles) { + NSString *path = [bundle pathForResource:resourceName ofType:fileType]; + // Use the first one we find. + if (path) { + return path; + } + } + return nil; +} + ++ (NSArray *)relevantURLSchemes { + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (NSBundle *bundle in [[self class] relevantBundles]) { + NSArray *urlTypes = [bundle objectForInfoDictionaryKey:@"CFBundleURLTypes"]; + for (NSDictionary *urlType in urlTypes) { + [result addObjectsFromArray:urlType[@"CFBundleURLSchemes"]]; + } + } + return result; +} + ++ (BOOL)hasBundleIdentifier:(NSString *)bundleIdentifier inBundles:(NSArray *)bundles { + for (NSBundle *bundle in bundles) { + if ([bundle.bundleIdentifier isEqualToString:bundleIdentifier]) { + return YES; + } + } + return NO; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponent.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponent.m new file mode 100644 index 0000000..2474d1a --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponent.m @@ -0,0 +1,65 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponent.h" + +#import "Private/FIRComponentContainer.h" +#import "Private/FIRDependency.h" + +@interface FIRComponent () + +- (instancetype)initWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock; + +@end + +@implementation FIRComponent + ++ (instancetype)componentWithProtocol:(Protocol *)protocol + creationBlock:(FIRComponentCreationBlock)creationBlock { + return [[FIRComponent alloc] initWithProtocol:protocol + instantiationTiming:FIRInstantiationTimingLazy + dependencies:@[] + creationBlock:creationBlock]; +} + ++ (instancetype)componentWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock { + return [[FIRComponent alloc] initWithProtocol:protocol + instantiationTiming:instantiationTiming + dependencies:dependencies + creationBlock:creationBlock]; +} + +- (instancetype)initWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock { + self = [super init]; + if (self) { + _protocol = protocol; + _instantiationTiming = instantiationTiming; + _dependencies = [dependencies copy]; + _creationBlock = creationBlock; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m new file mode 100644 index 0000000..381c95c --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentContainer.m @@ -0,0 +1,205 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponentContainer.h" + +#import "Private/FIRAppInternal.h" +#import "Private/FIRComponent.h" +#import "Private/FIRComponentRegistrant.h" +#import "Private/FIRLogger.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRComponentContainer () + +/// The dictionary of components that are registered for a particular app. The key is an NSString +/// of the protocol. +@property(nonatomic, strong) NSMutableDictionary *components; + +/// Cached instances of components that requested to be cached. +@property(nonatomic, strong) NSMutableDictionary *cachedInstances; + +@end + +@implementation FIRComponentContainer + +// Collection of all classes that register to provide components. +static NSMutableSet *gFIRComponentRegistrants; + +#pragma mark - Public Registration + ++ (void)registerAsComponentRegistrant:(Class)klass { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gFIRComponentRegistrants = [[NSMutableSet alloc] init]; + }); + + [self registerAsComponentRegistrant:klass inSet:gFIRComponentRegistrants]; +} + ++ (void)registerAsComponentRegistrant:(Class)klass inSet:(NSMutableSet *)allRegistrants { + // Validate the array to store the components is initialized. + if (!allRegistrants) { + FIRLogWarning(kFIRLoggerCore, @"I-COR000025", + @"Attempted to store registered components in an empty set."); + return; + } + + // Ensure the class given conforms to the proper protocol. + if (![klass conformsToProtocol:@protocol(FIRComponentRegistrant)] || + ![klass respondsToSelector:@selector(componentsToRegister)]) { + [NSException raise:NSInvalidArgumentException + format: + @"Class %@ attempted to register components, but it does not conform to " + @"`FIRComponentRegistrant` or provide a `componentsToRegister:` method.", + klass]; + } + + [allRegistrants addObject:klass]; +} + +#pragma mark - Internal Initialization + +- (instancetype)initWithApp:(FIRApp *)app { + return [self initWithApp:app registrants:gFIRComponentRegistrants]; +} + +- (instancetype)initWithApp:(FIRApp *)app registrants:(NSMutableSet *)allRegistrants { + self = [super init]; + if (self) { + _app = app; + _cachedInstances = [NSMutableDictionary dictionary]; + _components = [NSMutableDictionary dictionary]; + + [self populateComponentsFromRegisteredClasses:allRegistrants forApp:app]; + } + return self; +} + +- (void)populateComponentsFromRegisteredClasses:(NSSet *)classes forApp:(FIRApp *)app { + // Loop through the verified component registrants and populate the components array. + for (Class klass in classes) { + // Loop through all the components being registered and store them as appropriate. + // Classes which do not provide functionality should use a dummy FIRComponentRegistrant + // protocol. + for (FIRComponent *component in [klass componentsToRegister]) { + // Check if the component has been registered before, and error out if so. + NSString *protocolName = NSStringFromProtocol(component.protocol); + if (self.components[protocolName]) { + FIRLogError(kFIRLoggerCore, @"I-COR000029", + @"Attempted to register protocol %@, but it already has an implementation.", + protocolName); + continue; + } + + // Store the creation block for later usage. + self.components[protocolName] = component.creationBlock; + + // Instantiate the + BOOL shouldInstantiateEager = + (component.instantiationTiming == FIRInstantiationTimingAlwaysEager); + BOOL shouldInstantiateDefaultEager = + (component.instantiationTiming == FIRInstantiationTimingEagerInDefaultApp && + [app isDefaultApp]); + if (shouldInstantiateEager || shouldInstantiateDefaultEager) { + [self instantiateInstanceForProtocol:component.protocol withBlock:component.creationBlock]; + } + } + } +} + +#pragma mark - Instance Creation + +/// Instantiate an instance of a class that conforms to the specified protocol. +/// This will: +/// - Call the block to create an instance if possible, +/// - Validate that the instance returned conforms to the protocol it claims to, +/// - Cache the instance if the block requests it +- (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol + withBlock:(FIRComponentCreationBlock)creationBlock { + if (!creationBlock) { + return nil; + } + + // Create an instance using the creation block. + BOOL shouldCache = NO; + id instance = creationBlock(self, &shouldCache); + if (!instance) { + return nil; + } + + // An instance was created, validate that it conforms to the protocol it claims to. + NSString *protocolName = NSStringFromProtocol(protocol); + if (![instance conformsToProtocol:protocol]) { + FIRLogError(kFIRLoggerCore, @"I-COR000030", + @"An instance conforming to %@ was requested, but the instance provided does not " + @"conform to the protocol", + protocolName); + } + + // The instance is ready to be returned, but check if it should be cached first before returning. + if (shouldCache) { + self.cachedInstances[protocolName] = instance; + } + + return instance; +} + +#pragma mark - Internal Retrieval + +- (nullable id)instanceForProtocol:(Protocol *)protocol { + // Check if there is a cached instance, and return it if so. + NSString *protocolName = NSStringFromProtocol(protocol); + id cachedInstance = self.cachedInstances[protocolName]; + if (cachedInstance) { + return cachedInstance; + } + + // Use the creation block to instantiate an instance and return it. + FIRComponentCreationBlock creationBlock = self.components[protocolName]; + return [self instantiateInstanceForProtocol:protocol withBlock:creationBlock]; +} + +#pragma mark - Lifecycle + +- (void)removeAllCachedInstances { + // Loop through the cache and notify each instance that is a maintainer to clean up after itself. + for (id instance in self.cachedInstances.allValues) { + if ([instance conformsToProtocol:@protocol(FIRComponentLifecycleMaintainer)] && + [instance respondsToSelector:@selector(appWillBeDeleted:)]) { + [instance appWillBeDeleted:self.app]; + } + } + + [self.cachedInstances removeAllObjects]; +} + +#pragma mark - Testing Initializers + +// TODO(wilsonryan): Set up a testing flag so this only is compiled in with unit tests. +/// Initialize an instance with an app and existing components. +- (instancetype)initWithApp:(FIRApp *)app + components:(NSDictionary *)components { + self = [self initWithApp:app registrants:[[NSMutableSet alloc] init]]; + if (self) { + _components = [components mutableCopy]; + } + return self; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m new file mode 100644 index 0000000..bdc004f --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRComponentType.m @@ -0,0 +1,28 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRComponentType.h" + +#import "Private/FIRComponentContainerInternal.h" + +@implementation FIRComponentType + ++ (id)instanceForProtocol:(Protocol *)protocol inContainer:(FIRComponentContainer *)container { + // Forward the call to the container. + return [container instanceForProtocol:protocol]; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m new file mode 100644 index 0000000..cd64862 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRConfiguration.m @@ -0,0 +1,44 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRConfiguration.h" + +extern void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel); + +@implementation FIRConfiguration + ++ (instancetype)sharedInstance { + static FIRConfiguration *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[FIRConfiguration alloc] init]; + }); + return sharedInstance; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _analyticsConfiguration = [FIRAnalyticsConfiguration sharedInstance]; + } + return self; +} + +- (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel { + NSAssert(loggerLevel <= FIRLoggerLevelMax && loggerLevel >= FIRLoggerLevelMin, + @"Invalid logger level, %ld", (long)loggerLevel); + FIRSetLoggerLevel(loggerLevel); +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRDependency.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRDependency.m new file mode 100644 index 0000000..f979984 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRDependency.m @@ -0,0 +1,44 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Private/FIRDependency.h" + +@interface FIRDependency () + +- (instancetype)initWithProtocol:(Protocol *)protocol isRequired:(BOOL)required; + +@end + +@implementation FIRDependency + ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol { + return [[self alloc] initWithProtocol:protocol isRequired:YES]; +} + ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol isRequired:(BOOL)required { + return [[self alloc] initWithProtocol:protocol isRequired:required]; +} + +- (instancetype)initWithProtocol:(Protocol *)protocol isRequired:(BOOL)required { + self = [super init]; + if (self) { + _protocol = protocol; + _isRequired = required; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRErrors.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRErrors.m new file mode 100644 index 0000000..6d6d52d --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRErrors.m @@ -0,0 +1,29 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRErrors.h" + +NSString *const kFirebaseErrorDomain = @"com.firebase"; +NSString *const kFirebaseAdMobErrorDomain = @"com.firebase.admob"; +NSString *const kFirebaseAppInviteErrorDomain = @"com.firebase.appinvite"; +NSString *const kFirebaseAuthErrorDomain = @"com.firebase.auth"; +NSString *const kFirebaseCloudMessagingErrorDomain = @"com.firebase.cloudmessaging"; +NSString *const kFirebaseConfigErrorDomain = @"com.firebase.config"; +NSString *const kFirebaseCoreErrorDomain = @"com.firebase.core"; +NSString *const kFirebaseCrashReportingErrorDomain = @"com.firebase.crashreporting"; +NSString *const kFirebaseDatabaseErrorDomain = @"com.firebase.database"; +NSString *const kFirebaseDurableDeepLinkErrorDomain = @"com.firebase.durabledeeplink"; +NSString *const kFirebaseInstanceIDErrorDomain = @"com.firebase.instanceid"; +NSString *const kFirebasePerfErrorDomain = @"com.firebase.perf"; +NSString *const kFirebaseStorageErrorDomain = @"com.firebase.storage"; diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRLogger.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRLogger.m new file mode 100644 index 0000000..d1e3b37 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRLogger.m @@ -0,0 +1,185 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRLogger.h" + +#import +#import +#import + +#import "Private/FIRVersion.h" + +FIRLoggerService kFIRLoggerABTesting = @"[Firebase/ABTesting]"; +FIRLoggerService kFIRLoggerAdMob = @"[Firebase/AdMob]"; +FIRLoggerService kFIRLoggerAnalytics = @"[Firebase/Analytics]"; +FIRLoggerService kFIRLoggerAuth = @"[Firebase/Auth]"; +FIRLoggerService kFIRLoggerCore = @"[Firebase/Core]"; +FIRLoggerService kFIRLoggerCrash = @"[Firebase/Crash]"; +FIRLoggerService kFIRLoggerDatabase = @"[Firebase/Database]"; +FIRLoggerService kFIRLoggerDynamicLinks = @"[Firebase/DynamicLinks]"; +FIRLoggerService kFIRLoggerFirestore = @"[Firebase/Firestore]"; +FIRLoggerService kFIRLoggerInstanceID = @"[Firebase/InstanceID]"; +FIRLoggerService kFIRLoggerInvites = @"[Firebase/Invites]"; +FIRLoggerService kFIRLoggerMLKit = @"[Firebase/MLKit]"; +FIRLoggerService kFIRLoggerMessaging = @"[Firebase/Messaging]"; +FIRLoggerService kFIRLoggerPerf = @"[Firebase/Performance]"; +FIRLoggerService kFIRLoggerRemoteConfig = @"[Firebase/RemoteConfig]"; +FIRLoggerService kFIRLoggerStorage = @"[Firebase/Storage]"; +FIRLoggerService kFIRLoggerSwizzler = @"[FirebaseSwizzlingUtilities]"; + +/// Arguments passed on launch. +NSString *const kFIRDisableDebugModeApplicationArgument = @"-FIRDebugDisabled"; +NSString *const kFIREnableDebugModeApplicationArgument = @"-FIRDebugEnabled"; +NSString *const kFIRLoggerForceSDTERRApplicationArgument = @"-FIRLoggerForceSTDERR"; + +/// Key for the debug mode bit in NSUserDefaults. +NSString *const kFIRPersistedDebugModeKey = @"/google/firebase/debug_mode"; + +/// NSUserDefaults that should be used to store and read variables. If nil, `standardUserDefaults` +/// will be used. +static NSUserDefaults *sFIRLoggerUserDefaults; + +static dispatch_once_t sFIRLoggerOnceToken; + +// The sFIRAnalyticsDebugMode flag is here to support the -FIRDebugEnabled/-FIRDebugDisabled +// flags used by Analytics. Users who use those flags expect Analytics to log verbosely, +// while the rest of Firebase logs at the default level. This flag is introduced to support +// that behavior. +static BOOL sFIRAnalyticsDebugMode; + +#ifdef DEBUG +/// The regex pattern for the message code. +static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$"; +static NSRegularExpression *sMessageCodeRegex; +#endif + +void FIRLoggerInitializeASL() { + dispatch_once(&sFIRLoggerOnceToken, ^{ + // Register Firebase Version with GULLogger. + GULLoggerRegisterVersion(FIRVersionString); + + // Override the aslOptions to ASL_OPT_STDERR if the override argument is passed in. + NSArray *arguments = [NSProcessInfo processInfo].arguments; + BOOL overrideSTDERR = [arguments containsObject:kFIRLoggerForceSDTERRApplicationArgument]; + + // Use the standard NSUserDefaults if it hasn't been explicitly set. + if (sFIRLoggerUserDefaults == nil) { + sFIRLoggerUserDefaults = [NSUserDefaults standardUserDefaults]; + } + + BOOL forceDebugMode = NO; + BOOL debugMode = [sFIRLoggerUserDefaults boolForKey:kFIRPersistedDebugModeKey]; + if ([arguments containsObject:kFIRDisableDebugModeApplicationArgument]) { // Default mode + [sFIRLoggerUserDefaults removeObjectForKey:kFIRPersistedDebugModeKey]; + } else if ([arguments containsObject:kFIREnableDebugModeApplicationArgument] || + debugMode) { // Debug mode + [sFIRLoggerUserDefaults setBool:YES forKey:kFIRPersistedDebugModeKey]; + forceDebugMode = YES; + } + GULLoggerInitializeASL(); + if (overrideSTDERR) { + GULLoggerEnableSTDERR(); + } + if (forceDebugMode) { + GULLoggerForceDebug(); + } + }); +} + +__attribute__((no_sanitize("thread"))) void FIRSetAnalyticsDebugMode(BOOL analyticsDebugMode) { + sFIRAnalyticsDebugMode = analyticsDebugMode; +} + +void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel) { + FIRLoggerInitializeASL(); + GULSetLoggerLevel((GULLoggerLevel)loggerLevel); +} + +#ifdef DEBUG +void FIRResetLogger() { + extern void GULResetLogger(void); + sFIRLoggerOnceToken = 0; + [sFIRLoggerUserDefaults removeObjectForKey:kFIRPersistedDebugModeKey]; + sFIRLoggerUserDefaults = nil; + GULResetLogger(); +} + +void FIRSetLoggerUserDefaults(NSUserDefaults *defaults) { + sFIRLoggerUserDefaults = defaults; +} +#endif + +/** + * Check if the level is high enough to be loggable. + * + * Analytics can override the log level with an intentional race condition. + * Add the attribute to get a clean thread sanitizer run. + */ +__attribute__((no_sanitize("thread"))) BOOL FIRIsLoggableLevel(FIRLoggerLevel loggerLevel, + BOOL analyticsComponent) { + FIRLoggerInitializeASL(); + if (sFIRAnalyticsDebugMode && analyticsComponent) { + return YES; + } + return GULIsLoggableLevel((GULLoggerLevel)loggerLevel); +} + +void FIRLogBasic(FIRLoggerLevel level, + FIRLoggerService service, + NSString *messageCode, + NSString *message, + va_list args_ptr) { + FIRLoggerInitializeASL(); + GULLogBasic((GULLoggerLevel)level, service, + sFIRAnalyticsDebugMode && [kFIRLoggerAnalytics isEqualToString:service], messageCode, + message, args_ptr); +} + +/** + * Generates the logging functions using macros. + * + * Calling FIRLogError(kFIRLoggerCore, @"I-COR000001", @"Configure %@ failed.", @"blah") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [Firebase/Core][I-COR000001] Configure blah failed. + * Calling FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configure succeed.") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [Firebase/Core][I-COR000001] Configure succeed. + */ +#define FIR_LOGGING_FUNCTION(level) \ + void FIRLog##level(FIRLoggerService service, NSString *messageCode, NSString *message, ...) { \ + va_list args_ptr; \ + va_start(args_ptr, message); \ + FIRLogBasic(FIRLoggerLevel##level, service, messageCode, message, args_ptr); \ + va_end(args_ptr); \ + } + +FIR_LOGGING_FUNCTION(Error) +FIR_LOGGING_FUNCTION(Warning) +FIR_LOGGING_FUNCTION(Notice) +FIR_LOGGING_FUNCTION(Info) +FIR_LOGGING_FUNCTION(Debug) + +#undef FIR_MAKE_LOGGER + +#pragma mark - FIRLoggerWrapper + +@implementation FIRLoggerWrapper + ++ (void)logWithLevel:(FIRLoggerLevel)level + withService:(FIRLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args { + FIRLogBasic(level, service, messageCode, message, args); +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIROptions.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIROptions.m new file mode 100644 index 0000000..fe70851 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIROptions.m @@ -0,0 +1,444 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/FIRAppInternal.h" +#import "Private/FIRBundleUtil.h" +#import "Private/FIRErrors.h" +#import "Private/FIRLogger.h" +#import "Private/FIROptionsInternal.h" + +// Keys for the strings in the plist file. +NSString *const kFIRAPIKey = @"API_KEY"; +NSString *const kFIRTrackingID = @"TRACKING_ID"; +NSString *const kFIRGoogleAppID = @"GOOGLE_APP_ID"; +NSString *const kFIRClientID = @"CLIENT_ID"; +NSString *const kFIRGCMSenderID = @"GCM_SENDER_ID"; +NSString *const kFIRAndroidClientID = @"ANDROID_CLIENT_ID"; +NSString *const kFIRDatabaseURL = @"DATABASE_URL"; +NSString *const kFIRStorageBucket = @"STORAGE_BUCKET"; +// The key to locate the expected bundle identifier in the plist file. +NSString *const kFIRBundleID = @"BUNDLE_ID"; +// The key to locate the project identifier in the plist file. +NSString *const kFIRProjectID = @"PROJECT_ID"; + +NSString *const kFIRIsMeasurementEnabled = @"IS_MEASUREMENT_ENABLED"; +NSString *const kFIRIsAnalyticsCollectionEnabled = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; +NSString *const kFIRIsAnalyticsCollectionDeactivated = @"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED"; + +NSString *const kFIRIsAnalyticsEnabled = @"IS_ANALYTICS_ENABLED"; +NSString *const kFIRIsSignInEnabled = @"IS_SIGNIN_ENABLED"; + +// Library version ID. +NSString *const kFIRLibraryVersionID = + @"5" // Major version (one or more digits) + @"01" // Minor version (exactly 2 digits) + @"10" // Build number (exactly 2 digits) + @"000"; // Fixed "000" +// Plist file name. +NSString *const kServiceInfoFileName = @"GoogleService-Info"; +// Plist file type. +NSString *const kServiceInfoFileType = @"plist"; + +// Exception raised from attempting to modify a FIROptions after it's been copied to a FIRApp. +NSString *const kFIRExceptionBadModification = + @"Attempted to modify options after it's set on FIRApp. Please modify all properties before " + @"initializing FIRApp."; + +@interface FIROptions () + +/** + * This property maintains the actual configuration key-value pairs. + */ +@property(nonatomic, readwrite) NSMutableDictionary *optionsDictionary; + +/** + * Calls `analyticsOptionsDictionaryWithInfoDictionary:` using [NSBundle mainBundle].infoDictionary. + * It combines analytics options from both the infoDictionary and the GoogleService-Info.plist. + * Values which are present in the main plist override values from the GoogleService-Info.plist. + */ +@property(nonatomic, readonly) NSDictionary *analyticsOptionsDictionary; + +/** + * Combination of analytics options from both the infoDictionary and the GoogleService-Info.plist. + * Values which are present in the infoDictionary override values from the GoogleService-Info.plist. + */ +- (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary; + +/** + * Throw exception if editing is locked when attempting to modify an option. + */ +- (void)checkEditingLocked; + +@end + +@implementation FIROptions { + /// Backing variable for self.analyticsOptionsDictionary. + NSDictionary *_analyticsOptionsDictionary; +} + +static FIROptions *sDefaultOptions = nil; +static NSDictionary *sDefaultOptionsDictionary = nil; + +#pragma mark - Public only for internal class methods + ++ (FIROptions *)defaultOptions { + if (sDefaultOptions != nil) { + return sDefaultOptions; + } + + NSDictionary *defaultOptionsDictionary = [self defaultOptionsDictionary]; + if (defaultOptionsDictionary == nil) { + return nil; + } + + sDefaultOptions = [[FIROptions alloc] initInternalWithOptionsDictionary:defaultOptionsDictionary]; + return sDefaultOptions; +} + +#pragma mark - Private class methods + ++ (void)initialize { + // Report FirebaseCore version for useragent string + NSRange major = NSMakeRange(0, 1); + NSRange minor = NSMakeRange(1, 2); + NSRange patch = NSMakeRange(3, 2); + [FIRApp + registerLibrary:@"fire-ios" + withVersion:[NSString stringWithFormat:@"%@.%d.%d", + [kFIRLibraryVersionID substringWithRange:major], + [[kFIRLibraryVersionID substringWithRange:minor] + intValue], + [[kFIRLibraryVersionID substringWithRange:patch] + intValue]]]; + NSDictionary *info = [[NSBundle mainBundle] infoDictionary]; + NSString *xcodeVersion = info[@"DTXcodeBuild"]; + NSString *sdkVersion = info[@"DTSDKBuild"]; + if (xcodeVersion) { + [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion]; + } + if (sdkVersion) { + [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion]; + } +} + ++ (NSDictionary *)defaultOptionsDictionary { + if (sDefaultOptionsDictionary != nil) { + return sDefaultOptionsDictionary; + } + NSString *plistFilePath = [FIROptions plistFilePathWithName:kServiceInfoFileName]; + if (plistFilePath == nil) { + return nil; + } + sDefaultOptionsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistFilePath]; + if (sDefaultOptionsDictionary == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000011", + @"The configuration file is not a dictionary: " + @"'%@.%@'.", + kServiceInfoFileName, kServiceInfoFileType); + } + return sDefaultOptionsDictionary; +} + +// Returns the path of the plist file with a given file name. ++ (NSString *)plistFilePathWithName:(NSString *)fileName { + NSArray *bundles = [FIRBundleUtil relevantBundles]; + NSString *plistFilePath = + [FIRBundleUtil optionsDictionaryPathWithResourceName:fileName + andFileType:kServiceInfoFileType + inBundles:bundles]; + if (plistFilePath == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000012", @"Could not locate configuration file: '%@.%@'.", + fileName, kServiceInfoFileType); + } + return plistFilePath; +} + ++ (void)resetDefaultOptions { + sDefaultOptions = nil; + sDefaultOptionsDictionary = nil; +} + +#pragma mark - Private instance methods + +- (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)optionsDictionary { + self = [super init]; + if (self) { + _optionsDictionary = [optionsDictionary mutableCopy]; + _usingOptionsFromDefaultPlist = YES; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + FIROptions *newOptions = [[[self class] allocWithZone:zone] init]; + if (newOptions) { + newOptions.optionsDictionary = self.optionsDictionary; + newOptions.deepLinkURLScheme = self.deepLinkURLScheme; + newOptions.editingLocked = self.isEditingLocked; + newOptions.usingOptionsFromDefaultPlist = self.usingOptionsFromDefaultPlist; + } + return newOptions; +} + +#pragma mark - Public instance methods + +- (instancetype)initWithContentsOfFile:(NSString *)plistPath { + self = [super init]; + if (self) { + if (plistPath == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000013", @"The plist file path is nil."); + return nil; + } + _optionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy]; + if (_optionsDictionary == nil) { + FIRLogError(kFIRLoggerCore, @"I-COR000014", + @"The configuration file at %@ does not exist or " + @"is not a well-formed plist file.", + plistPath); + return nil; + } + // TODO: Do we want to validate the dictionary here? It says we do that already in + // the public header. + } + return self; +} + +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID GCMSenderID:(NSString *)GCMSenderID { + self = [super init]; + if (self) { + NSMutableDictionary *mutableOptionsDict = [NSMutableDictionary dictionary]; + [mutableOptionsDict setValue:googleAppID forKey:kFIRGoogleAppID]; + [mutableOptionsDict setValue:GCMSenderID forKey:kFIRGCMSenderID]; + [mutableOptionsDict setValue:[[NSBundle mainBundle] bundleIdentifier] forKey:kFIRBundleID]; + self.optionsDictionary = mutableOptionsDict; + } + return self; +} + +- (NSString *)APIKey { + return self.optionsDictionary[kFIRAPIKey]; +} + +- (void)checkEditingLocked { + if (self.isEditingLocked) { + [NSException raise:kFirebaseCoreErrorDomain format:kFIRExceptionBadModification]; + } +} + +- (void)setAPIKey:(NSString *)APIKey { + [self checkEditingLocked]; + _optionsDictionary[kFIRAPIKey] = [APIKey copy]; +} + +- (NSString *)clientID { + return self.optionsDictionary[kFIRClientID]; +} + +- (void)setClientID:(NSString *)clientID { + [self checkEditingLocked]; + _optionsDictionary[kFIRClientID] = [clientID copy]; +} + +- (NSString *)trackingID { + return self.optionsDictionary[kFIRTrackingID]; +} + +- (void)setTrackingID:(NSString *)trackingID { + [self checkEditingLocked]; + _optionsDictionary[kFIRTrackingID] = [trackingID copy]; +} + +- (NSString *)GCMSenderID { + return self.optionsDictionary[kFIRGCMSenderID]; +} + +- (void)setGCMSenderID:(NSString *)GCMSenderID { + [self checkEditingLocked]; + _optionsDictionary[kFIRGCMSenderID] = [GCMSenderID copy]; +} + +- (NSString *)projectID { + return self.optionsDictionary[kFIRProjectID]; +} + +- (void)setProjectID:(NSString *)projectID { + [self checkEditingLocked]; + _optionsDictionary[kFIRProjectID] = [projectID copy]; +} + +- (NSString *)androidClientID { + return self.optionsDictionary[kFIRAndroidClientID]; +} + +- (void)setAndroidClientID:(NSString *)androidClientID { + [self checkEditingLocked]; + _optionsDictionary[kFIRAndroidClientID] = [androidClientID copy]; +} + +- (NSString *)googleAppID { + return self.optionsDictionary[kFIRGoogleAppID]; +} + +- (void)setGoogleAppID:(NSString *)googleAppID { + [self checkEditingLocked]; + _optionsDictionary[kFIRGoogleAppID] = [googleAppID copy]; +} + +- (NSString *)libraryVersionID { + return kFIRLibraryVersionID; +} + +- (void)setLibraryVersionID:(NSString *)libraryVersionID { + _optionsDictionary[kFIRLibraryVersionID] = [libraryVersionID copy]; +} + +- (NSString *)databaseURL { + return self.optionsDictionary[kFIRDatabaseURL]; +} + +- (void)setDatabaseURL:(NSString *)databaseURL { + [self checkEditingLocked]; + + _optionsDictionary[kFIRDatabaseURL] = [databaseURL copy]; +} + +- (NSString *)storageBucket { + return self.optionsDictionary[kFIRStorageBucket]; +} + +- (void)setStorageBucket:(NSString *)storageBucket { + [self checkEditingLocked]; + _optionsDictionary[kFIRStorageBucket] = [storageBucket copy]; +} + +- (void)setDeepLinkURLScheme:(NSString *)deepLinkURLScheme { + [self checkEditingLocked]; + _deepLinkURLScheme = [deepLinkURLScheme copy]; +} + +- (NSString *)bundleID { + return self.optionsDictionary[kFIRBundleID]; +} + +- (void)setBundleID:(NSString *)bundleID { + [self checkEditingLocked]; + _optionsDictionary[kFIRBundleID] = [bundleID copy]; +} + +#pragma mark - Internal instance methods + +- (NSDictionary *)analyticsOptionsDictionaryWithInfoDictionary:(NSDictionary *)infoDictionary { + if (_analyticsOptionsDictionary == nil) { + NSMutableDictionary *tempAnalyticsOptions = [[NSMutableDictionary alloc] init]; + NSArray *measurementKeys = @[ + kFIRIsMeasurementEnabled, kFIRIsAnalyticsCollectionEnabled, + kFIRIsAnalyticsCollectionDeactivated + ]; + for (NSString *key in measurementKeys) { + id value = infoDictionary[key] ?: self.optionsDictionary[key] ?: nil; + if (!value) { + continue; + } + tempAnalyticsOptions[key] = value; + } + _analyticsOptionsDictionary = tempAnalyticsOptions; + } + return _analyticsOptionsDictionary; +} + +- (NSDictionary *)analyticsOptionsDictionary { + return [self analyticsOptionsDictionaryWithInfoDictionary:[NSBundle mainBundle].infoDictionary]; +} + +/** + * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in + * GoogleService-Info.plist. This uses the old plist flag IS_MEASUREMENT_ENABLED, which should still + * be supported. + */ +- (BOOL)isMeasurementEnabled { + if (self.isAnalyticsCollectionDeactivated) { + return NO; + } + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled]; + if (value == nil) { + // TODO: This could probably be cleaned up since FIROptions shouldn't know about FIRApp or have + // to check if it's the default app. The FIROptions instance can't be modified after + // `+configure` is called, so it's not a good place to copy it either in case the flag is + // changed at runtime. + + // If no values are set for Analytics, fall back to the global collection switch in FIRApp. + // Analytics only supports the default FIRApp, so check that first. + if (![FIRApp isDefaultAppConfigured]) { + return NO; + } + + // Fall back to the default app's collection switch when the key is not in the dictionary. + return [FIRApp defaultApp].isDataCollectionDefaultEnabled; + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsCollectionExpicitlySet { + // If it's de-activated, it classifies as explicity set. If not, it's not a good enough indication + // that the developer wants FirebaseAnalytics enabled so continue checking. + if (self.isAnalyticsCollectionDeactivated) { + return YES; + } + + // Check if the current Analytics flag is set. + id collectionEnabledObject = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled]; + if (collectionEnabledObject && [collectionEnabledObject isKindOfClass:[NSNumber class]]) { + // It doesn't matter what the value is, it's explicitly set. + return YES; + } + + // Check if the old measurement flag is set. + id measurementEnabledObject = self.analyticsOptionsDictionary[kFIRIsMeasurementEnabled]; + if (measurementEnabledObject && [measurementEnabledObject isKindOfClass:[NSNumber class]]) { + // It doesn't matter what the value is, it's explicitly set. + return YES; + } + + // No flags are set to explicitly enable or disable FirebaseAnalytics. + return NO; +} + +- (BOOL)isAnalyticsCollectionEnabled { + if (self.isAnalyticsCollectionDeactivated) { + return NO; + } + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionEnabled]; + if (value == nil) { + return self.isMeasurementEnabled; // Fall back to older plist flag. + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsCollectionDeactivated { + NSNumber *value = self.analyticsOptionsDictionary[kFIRIsAnalyticsCollectionDeactivated]; + if (value == nil) { + return NO; // Analytics Collection is not deactivated when the key is not in the dictionary. + } + return [value boolValue]; +} + +- (BOOL)isAnalyticsEnabled { + return [self.optionsDictionary[kFIRIsAnalyticsEnabled] boolValue]; +} + +- (BOOL)isSignInEnabled { + return [self.optionsDictionary[kFIRIsSignInEnabled] boolValue]; +} + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/FIRVersion.m b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRVersion.m new file mode 100644 index 0000000..ec0f6ba --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/FIRVersion.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Firebase_VERSION +#error "Firebase_VERSION is not defined: add -DFirebase_VERSION=... to the build invocation" +#endif + +#ifndef FIRCore_VERSION +#error "FIRCore_VERSION is not defined: add -DFIRCore_VERSION=... to the build invocation" +#endif + +// The following two macros supply the incantation so that the C +// preprocessor does not try to parse the version as a floating +// point number. See +// https://www.guyrutenberg.com/2008/12/20/expanding-macros-into-string-constants-in-c/ +#define STR(x) STR_EXPAND(x) +#define STR_EXPAND(x) #x + +const char *const FIRVersionString = (const char *const)STR(Firebase_VERSION); +const char *const FIRCoreVersionString = (const char *const)STR(FIRCore_VERSION); diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h new file mode 100644 index 0000000..be624b4 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAnalyticsConfiguration.h" + +/// Values stored in analyticsEnabledState. Never alter these constants since they must match with +/// values persisted to disk. +typedef NS_ENUM(int64_t, FIRAnalyticsEnabledState) { + // 0 is the default value for keys not found stored in persisted config, so it cannot represent + // kFIRAnalyticsEnabledStateSetNo. It must represent kFIRAnalyticsEnabledStateNotSet. + kFIRAnalyticsEnabledStateNotSet = 0, + kFIRAnalyticsEnabledStateSetYes = 1, + kFIRAnalyticsEnabledStateSetNo = 2, +}; + +/// The user defaults key for the persisted measurementEnabledState value. FIRAPersistedConfig reads +/// measurementEnabledState using this same key. +static NSString *const kFIRAPersistedConfigMeasurementEnabledStateKey = + @"/google/measurement/measurement_enabled_state"; + +static NSString *const kFIRAnalyticsConfigurationSetEnabledNotification = + @"FIRAnalyticsConfigurationSetEnabledNotification"; +static NSString *const kFIRAnalyticsConfigurationSetMinimumSessionIntervalNotification = + @"FIRAnalyticsConfigurationSetMinimumSessionIntervalNotification"; +static NSString *const kFIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification = + @"FIRAnalyticsConfigurationSetSessionTimeoutIntervalNotification"; + +@interface FIRAnalyticsConfiguration (Internal) + +/// Sets whether analytics collection is enabled for this app on this device, and a flag to persist +/// the value or not. The setting should not be persisted if being set by the global data collection +/// flag. +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled + persistSetting:(BOOL)shouldPersist; + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h new file mode 100644 index 0000000..3fc69c6 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppAssociationRegistration.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +// TODO: Remove this once Auth moves over to Core's instance registration system. +/** @class FIRAppAssociationRegistration + @brief Manages object associations as a singleton-dependent: At most one object is + registered for any given host/key pair, and the object shall be created on-the-fly when + asked for. + */ +@interface FIRAppAssociationRegistration : NSObject + +/** @fn registeredObjectWithHost:key:creationBlock: + @brief Retrieves the registered object with a particular host and key. + @param host The host object. + @param key The key to specify the registered object on the host. + @param creationBlock The block to return the object to be registered if not already. + The block is executed immediately before this method returns if it is executed at all. + It can also be executed multiple times across different method invocations if previous + execution of the block returns @c nil. + @return The registered object for the host/key pair, or @c nil if no object is registered + and @c creationBlock returns @c nil. + @remarks The method is thread-safe but non-reentrant in the sense that attempting to call this + method again within the @c creationBlock with the same host/key pair raises an exception. + The registered object is retained by the host. + */ ++ (nullable ObjectType)registeredObjectWithHost:(id)host + key:(NSString *)key + creationBlock:(ObjectType _Nullable (^)(void))creationBlock; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h new file mode 100644 index 0000000..67cb33b --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRAppInternal.h @@ -0,0 +1,180 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRApp.h" +#import "FIRErrors.h" + +@class FIRComponentContainer; +@protocol FIRCoreConfigurable; + +/** + * The internal interface to FIRApp. This is meant for first-party integrators, who need to receive + * FIRApp notifications, log info about the success or failure of their configuration, and access + * other internal functionality of FIRApp. + * + * TODO(b/28296561): Restructure this header. + */ +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, FIRConfigType) { + FIRConfigTypeCore = 1, + FIRConfigTypeSDK = 2, +}; + +/** + * Names of services provided by Firebase. + */ +extern NSString *const kFIRServiceAdMob; +extern NSString *const kFIRServiceAuth; +extern NSString *const kFIRServiceAuthUI; +extern NSString *const kFIRServiceCrash; +extern NSString *const kFIRServiceDatabase; +extern NSString *const kFIRServiceDynamicLinks; +extern NSString *const kFIRServiceInstanceID; +extern NSString *const kFIRServiceInvites; +extern NSString *const kFIRServiceMessaging; +extern NSString *const kFIRServiceMeasurement; +extern NSString *const kFIRServiceRemoteConfig; +extern NSString *const kFIRServiceStorage; + +/** + * Names of services provided by the Google pod, but logged by the Firebase pod. + */ +extern NSString *const kGGLServiceAnalytics; +extern NSString *const kGGLServiceSignIn; + +extern NSString *const kFIRDefaultAppName; +extern NSString *const kFIRAppReadyToConfigureSDKNotification; +extern NSString *const kFIRAppDeleteNotification; +extern NSString *const kFIRAppIsDefaultAppKey; +extern NSString *const kFIRAppNameKey; +extern NSString *const kFIRGoogleAppIDKey; + +/** + * The format string for the User Defaults key used for storing the data collection enabled flag. + * This includes formatting to append the Firebase App's name. + */ +extern NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat; + +/** + * The plist key used for storing the data collection enabled flag. + */ +extern NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey; + +/** + * A notification fired containing diagnostic information when SDK errors occur. + */ +extern NSString *const kFIRAppDiagnosticsNotification; + +/** @var FIRAuthStateDidChangeInternalNotification + @brief The name of the @c NSNotificationCenter notification which is posted when the auth state + changes (e.g. a new token has been produced, a user logs in or out). The object parameter of + the notification is a dictionary possibly containing the key: + @c FIRAuthStateDidChangeInternalNotificationTokenKey (the new access token.) If it does not + contain this key it indicates a sign-out event took place. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotification; + +/** @var FIRAuthStateDidChangeInternalNotificationTokenKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the new access token. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey; + +/** @var FIRAuthStateDidChangeInternalNotificationAppKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the FIRApp associated with the auth instance. + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationAppKey; + +/** @var FIRAuthStateDidChangeInternalNotificationUIDKey + @brief A key present in the dictionary object parameter of the + @c FIRAuthStateDidChangeInternalNotification notification. The value associated with this + key will contain the new user's UID (or nil if there is no longer a user signed in). + */ +extern NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey; + +@interface FIRApp () + +/** + * A flag indicating if this is the default app (has the default app name). + */ +@property(nonatomic, readonly) BOOL isDefaultApp; + +/* + * The container of interop SDKs for this app. + */ +@property(nonatomic) FIRComponentContainer *container; + +/** + * Creates an error for failing to configure a subspec service. This method is called by each + * FIRApp notification listener. + */ ++ (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain + errorCode:(FIRErrorCode)code + service:(NSString *)service + reason:(NSString *)reason; +/** + * Checks if the default app is configured without trying to configure it. + */ ++ (BOOL)isDefaultAppConfigured; + +/** + * Register a class that conforms to `FIRCoreConfigurable`. Each SDK should have one class that + * registers in order to provide critical information for interoperability and lifecycle events. + * TODO(wilsonryan): Write more documentation. + */ ++ (void)registerAsConfigurable:(Class)klass; + +/** + * Registers a given third-party library with the given version number to be reported for + * analyitcs. + * + * @param library Name of the library + * @param version Version of the library + */ +// clang-format off ++ (void)registerLibrary:(NSString *)library + withVersion:(NSString *)version NS_SWIFT_NAME(registerLibrary(_:version:)); +// clang-format on + +/** + * A concatenated string representing all the third-party libraries and version numbers. + */ ++ (NSString *)firebaseUserAgent; + +/** + * Used by each SDK to send logs about SDK configuration status to Clearcut. + */ +- (void)sendLogsWithServiceName:(NSString *)serviceName + version:(NSString *)version + error:(NSError *)error; + +/** + * Can be used by the unit tests in eack SDK to reset FIRApp. This method is thread unsafe. + */ ++ (void)resetApps; + +/** + * Can be used by the unit tests in each SDK to set customized options. + */ +- (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h new file mode 100644 index 0000000..c458a2c --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRBundleUtil.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + * This class provides utilities for accessing resources in bundles. + */ +@interface FIRBundleUtil : NSObject + +/** + * Finds all relevant bundles, starting with [NSBundle mainBundle]. + */ ++ (NSArray *)relevantBundles; + +/** + * Reads the options dictionary from one of the provided bundles. + * + * @param resourceName The resource name, e.g. @"GoogleService-Info". + * @param fileType The file type (extension), e.g. @"plist". + * @param bundles The bundles to expect, in priority order. See also + * +[FIRBundleUtil relevantBundles]. + */ ++ (NSString *)optionsDictionaryPathWithResourceName:(NSString *)resourceName + andFileType:(NSString *)fileType + inBundles:(NSArray *)bundles; + +/** + * Finds URL schemes defined in all relevant bundles, starting with those from + * [NSBundle mainBundle]. + */ ++ (NSArray *)relevantURLSchemes; + +/** + * Checks if the bundle identifier exists in the given bundles. + */ ++ (BOOL)hasBundleIdentifier:(NSString *)bundleIdentifier inBundles:(NSArray *)bundles; + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h new file mode 100644 index 0000000..cb51ee7 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponent.h @@ -0,0 +1,91 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRApp; +@class FIRComponentContainer; + +NS_ASSUME_NONNULL_BEGIN + +/// Provides a system to clean up cached instances returned from the component system. +NS_SWIFT_NAME(ComponentLifecycleMaintainer) +@protocol FIRComponentLifecycleMaintainer +/// The associated app will be deleted, clean up any resources as they are about to be deallocated. +- (void)appWillBeDeleted:(FIRApp *)app; +@end + +typedef _Nullable id (^FIRComponentCreationBlock)(FIRComponentContainer *container, + BOOL *isCacheable) + NS_SWIFT_NAME(ComponentCreationBlock); + +@class FIRDependency; + +/// Describes the timing of instantiation. Note: new components should default to lazy unless there +/// is a strong reason to be eager. +typedef NS_ENUM(NSInteger, FIRInstantiationTiming) { + FIRInstantiationTimingLazy, + FIRInstantiationTimingAlwaysEager, + FIRInstantiationTimingEagerInDefaultApp +} NS_SWIFT_NAME(InstantiationTiming); + +/// A component that can be used from other Firebase SDKs. +NS_SWIFT_NAME(Component) +@interface FIRComponent : NSObject + +/// The protocol describing functionality provided from the Component. +@property(nonatomic, strong, readonly) Protocol *protocol; + +/// The timing of instantiation. +@property(nonatomic, readonly) FIRInstantiationTiming instantiationTiming; + +/// An array of dependencies for the component. +@property(nonatomic, copy, readonly) NSArray *dependencies; + +/// A block to instantiate an instance of the component with the appropriate dependencies. +@property(nonatomic, copy, readonly) FIRComponentCreationBlock creationBlock; + +// There's an issue with long NS_SWIFT_NAMES that causes compilation to fail, disable clang-format +// for the next two methods. +// clang-format off + +/// Creates a component with no dependencies that will be lazily initialized. ++ (instancetype)componentWithProtocol:(Protocol *)protocol + creationBlock:(FIRComponentCreationBlock)creationBlock +NS_SWIFT_NAME(init(_:creationBlock:)); + +/// Creates a component to be registered with the component container. +/// +/// @param protocol - The protocol describing functionality provided by the component. +/// @param instantiationTiming - When the component should be initialized. Use .lazy unless there's +/// a good reason to be instantiated earlier. +/// @param dependencies - Any dependencies the `implementingClass` has, optional or required. +/// @param creationBlock - A block to instantiate the component with a container, and if +/// @return A component that can be registered with the component container. ++ (instancetype)componentWithProtocol:(Protocol *)protocol + instantiationTiming:(FIRInstantiationTiming)instantiationTiming + dependencies:(NSArray *)dependencies + creationBlock:(FIRComponentCreationBlock)creationBlock +NS_SWIFT_NAME(init(_:instantiationTiming:dependencies:creationBlock:)); + +// clang-format on + +/// Unavailable. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h new file mode 100644 index 0000000..10e2255 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainer.h @@ -0,0 +1,47 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import "FIRComponentType.h" + +NS_ASSUME_NONNULL_BEGIN + +/// A type-safe macro to retrieve a component from a container. This should be used to retrieve +/// components instead of using the container directly. +#define FIR_COMPONENT(type, container) \ + [FIRComponentType> instanceForProtocol:@protocol(type) inContainer:container] + +@class FIRApp; + +/// A container that holds different components that are registered via the +/// `registerAsComponentRegistrant:` call. These classes should conform to `FIRComponentRegistrant` +/// in order to properly register components for Core. +NS_SWIFT_NAME(FirebaseComponentContainer) +@interface FIRComponentContainer : NSObject + +/// A weak reference to the app that an instance of the container belongs to. +@property(nonatomic, weak, readonly) FIRApp *app; + +/// Unavailable. Use the `container` property on `FIRApp`. +- (instancetype)init NS_UNAVAILABLE; + +/// Register a class to provide components for the interoperability system. The class should conform +/// to `FIRComponentRegistrant` and provide an array of `FIRComponent` objects. ++ (void)registerAsComponentRegistrant:(Class)klass; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h new file mode 100644 index 0000000..bb73e7b --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentContainerInternal.h @@ -0,0 +1,39 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import "FIRComponent.h" +#import "FIRComponentContainer.h" + +@class FIRApp; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRComponentContainer (Private) + +/// Initializes a contain for a given app. This should only be called by the app itself. +- (instancetype)initWithApp:(FIRApp *)app; + +/// Retrieves an instance that conforms to the specified protocol. This will return `nil` if the +/// protocol wasn't registered, or if the instance couldn't instantiate for the provided app. +- (nullable id)instanceForProtocol:(Protocol *)protocol NS_SWIFT_NAME(instance(for:)); + +/// Remove all of the cached instances stored and allow them to clean up after themselves. +- (void)removeAllCachedInstances; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h new file mode 100644 index 0000000..ad2cad2 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentRegistrant.h @@ -0,0 +1,38 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRComponentRegistrant_h +#define FIRComponentRegistrant_h + +#import + +@class FIRComponent; + +NS_ASSUME_NONNULL_BEGIN + +/// Describes functionality for SDKs registering components in the `FIRComponentContainer`. +NS_SWIFT_NAME(ComponentRegistrant) +@protocol FIRComponentRegistrant + +/// Returns one or more FIRComponents that will be registered in +/// FIRApp and participate in dependency resolution and injection. ++ (NSArray *)componentsToRegister; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* FIRComponentRegistrant_h */ diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h new file mode 100644 index 0000000..6f2aca7 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRComponentType.h @@ -0,0 +1,34 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRComponentContainer; + +NS_ASSUME_NONNULL_BEGIN + +/// Do not use directly. A placeholder type in order to provide a macro that will warn users of +/// mis-matched protocols. +NS_SWIFT_NAME(ComponentType) +@interface FIRComponentType<__covariant T> : NSObject + +/// Do not use directly. A factory method to retrieve an instance that provides a specific +/// functionality. ++ (T)instanceForProtocol:(Protocol *)protocol inContainer:(FIRComponentContainer *)container; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h new file mode 100644 index 0000000..6c2b077 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRCoreConfigurable.h @@ -0,0 +1,38 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRCoreConfigurable_h +#define FIRCoreConfigurable_h + +#import + +@class FIRApp; + +NS_ASSUME_NONNULL_BEGIN + +/// Provides an interface to set up an SDK once a `FIRApp` is configured. +NS_SWIFT_NAME(CoreConfigurable) +@protocol FIRCoreConfigurable + +/// Configure the SDK if needed ahead of time. This method is called when the developer calls +/// `FirebaseApp.configure()`. ++ (void)configureWithApp:(FIRApp *)app; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* FIRCoreConfigurable_h */ diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h new file mode 100644 index 0000000..46e9b7e --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRDependency.h @@ -0,0 +1,45 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// A dependency on a specific protocol's functionality. +NS_SWIFT_NAME(Dependency) +@interface FIRDependency : NSObject + +/// The protocol describing functionality being depended on. +@property(nonatomic, strong, readonly) Protocol *protocol; + +/// A flag to specify if the dependency is required or not. +@property(nonatomic, readonly) BOOL isRequired; + +/// Initializes a dependency that is required. Calls `initWithProtocol:isRequired` with `YES` for +/// the required parameter. +/// Creates a required dependency on the specified protocol's functionality. ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol; + +/// Creates a dependency on the specified protocol's functionality and specify if it's required for +/// the class's functionality. ++ (instancetype)dependencyWithProtocol:(Protocol *)protocol isRequired:(BOOL)required; + +/// Use `dependencyWithProtocol:isRequired:` instead. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h new file mode 100644 index 0000000..01d3c56 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrorCode.h @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Error codes in Firebase error domain. */ +typedef NS_ENUM(NSInteger, FIRErrorCode) { + /** + * Unknown error. + */ + FIRErrorCodeUnknown = 0, + /** + * Loading data from the GoogleService-Info.plist file failed. This is a fatal error and should + * not be ignored. Further calls to the API will fail and/or possibly cause crashes. + */ + FIRErrorCodeInvalidPlistFile = -100, + + /** + * Validating the Google App ID format failed. + */ + FIRErrorCodeInvalidAppID = -101, + + /** + * Error code for failing to configure a specific service. + */ + FIRErrorCodeAdMobFailed = -110, + FIRErrorCodeAppInviteFailed = -112, + FIRErrorCodeCloudMessagingFailed = -113, + FIRErrorCodeConfigFailed = -114, + FIRErrorCodeDatabaseFailed = -115, + FIRErrorCodeCrashReportingFailed = -118, + FIRErrorCodeDurableDeepLinkFailed = -119, + FIRErrorCodeAuthFailed = -120, + FIRErrorCodeInstanceIDFailed = -121, + FIRErrorCodeStorageFailed = -123, + + /** + * Error codes returned by Dynamic Links + */ + FIRErrorCodeDynamicLinksStrongMatchNotAvailable = -124, + FIRErrorCodeDynamicLinksManualRetrievalNotEnabled = -125, + FIRErrorCodeDynamicLinksPendingLinkOnlyAvailableAtFirstLaunch = -126, + FIRErrorCodeDynamicLinksPendingLinkRetrievalAlreadyRunning = -127, +}; diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h new file mode 100644 index 0000000..cf69252 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRErrors.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#include "FIRErrorCode.h" + +extern NSString *const kFirebaseErrorDomain; +extern NSString *const kFirebaseAdMobErrorDomain; +extern NSString *const kFirebaseAppInviteErrorDomain; +extern NSString *const kFirebaseAuthErrorDomain; +extern NSString *const kFirebaseCloudMessagingErrorDomain; +extern NSString *const kFirebaseConfigErrorDomain; +extern NSString *const kFirebaseCoreErrorDomain; +extern NSString *const kFirebaseCrashReportingErrorDomain; +extern NSString *const kFirebaseDatabaseErrorDomain; +extern NSString *const kFirebaseDurableDeepLinkErrorDomain; +extern NSString *const kFirebaseInstanceIDErrorDomain; +extern NSString *const kFirebasePerfErrorDomain; +extern NSString *const kFirebaseStorageErrorDomain; diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h new file mode 100644 index 0000000..a538199 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRLogger.h @@ -0,0 +1,159 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRLoggerLevel.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * The Firebase services used in Firebase logger. + */ +typedef NSString *const FIRLoggerService; + +extern FIRLoggerService kFIRLoggerABTesting; +extern FIRLoggerService kFIRLoggerAdMob; +extern FIRLoggerService kFIRLoggerAnalytics; +extern FIRLoggerService kFIRLoggerAuth; +extern FIRLoggerService kFIRLoggerCore; +extern FIRLoggerService kFIRLoggerCrash; +extern FIRLoggerService kFIRLoggerDatabase; +extern FIRLoggerService kFIRLoggerDynamicLinks; +extern FIRLoggerService kFIRLoggerFirestore; +extern FIRLoggerService kFIRLoggerInstanceID; +extern FIRLoggerService kFIRLoggerInvites; +extern FIRLoggerService kFIRLoggerMLKit; +extern FIRLoggerService kFIRLoggerMessaging; +extern FIRLoggerService kFIRLoggerPerf; +extern FIRLoggerService kFIRLoggerRemoteConfig; +extern FIRLoggerService kFIRLoggerStorage; +extern FIRLoggerService kFIRLoggerSwizzler; + +/** + * The key used to store the logger's error count. + */ +extern NSString *const kFIRLoggerErrorCountKey; + +/** + * The key used to store the logger's warning count. + */ +extern NSString *const kFIRLoggerWarningCountKey; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Enables or disables Analytics debug mode. + * If set to YES, the logging level for Analytics will be set to FIRLoggerLevelDebug. + * Enabling the debug mode has no effect if the app is running from App Store. + * (required) analytics debug mode flag. + */ +void FIRSetAnalyticsDebugMode(BOOL analyticsDebugMode); + +/** + * Changes the default logging level of FIRLoggerLevelNotice to a user-specified level. + * The default level cannot be set above FIRLoggerLevelNotice if the app is running from App Store. + * (required) log level (one of the FIRLoggerLevel enum values). + */ +void FIRSetLoggerLevel(FIRLoggerLevel loggerLevel); + +/** + * Checks if the specified logger level is loggable given the current settings. + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) whether or not this function is called from the Analytics component. + */ +BOOL FIRIsLoggableLevel(FIRLoggerLevel loggerLevel, BOOL analyticsComponent); + +/** + * Logs a message to the Xcode console and the device log. If running from AppStore, will + * not log any messages with a level higher than FIRLoggerLevelNotice to avoid log spamming. + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) service name of type FIRLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ +extern void FIRLogBasic(FIRLoggerLevel level, + FIRLoggerService service, + NSString *messageCode, + NSString *message, +// On 64-bit simulators, va_list is not a pointer, so cannot be marked nullable +// See: http://stackoverflow.com/q/29095469 +#if __LP64__ && TARGET_OS_SIMULATOR || TARGET_OS_OSX + va_list args_ptr +#else + va_list _Nullable args_ptr +#endif +); + +/** + * The following functions accept the following parameters in order: + * (required) service name of type FIRLoggerService. + * (required) message code starting from "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * See go/firebase-log-proposal for details. + * (required) message string which can be a format string. + * (optional) the list of arguments to substitute into the format string. + * Example usage: + * FIRLogError(kFIRLoggerCore, @"I-COR000001", @"Configuration of %@ failed.", app.name); + */ +extern void FIRLogError(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogWarning(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogNotice(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogInfo(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); +extern void FIRLogDebug(FIRLoggerService service, NSString *messageCode, NSString *message, ...) + NS_FORMAT_FUNCTION(3, 4); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +@interface FIRLoggerWrapper : NSObject + +/** + * Objective-C wrapper for FIRLogBasic to allow weak linking to FIRLogger + * (required) log level (one of the FIRLoggerLevel enum values). + * (required) service name of type FIRLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ + ++ (void)logWithLevel:(FIRLoggerLevel)level + withService:(FIRLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h new file mode 100644 index 0000000..7bb40fc --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIROptionsInternal.h @@ -0,0 +1,114 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIROptions.h" + +/** + * Keys for the strings in the plist file. + */ +extern NSString *const kFIRAPIKey; +extern NSString *const kFIRTrackingID; +extern NSString *const kFIRGoogleAppID; +extern NSString *const kFIRClientID; +extern NSString *const kFIRGCMSenderID; +extern NSString *const kFIRAndroidClientID; +extern NSString *const kFIRDatabaseURL; +extern NSString *const kFIRStorageBucket; +extern NSString *const kFIRBundleID; +extern NSString *const kFIRProjectID; + +/** + * Keys for the plist file name + */ +extern NSString *const kServiceInfoFileName; + +extern NSString *const kServiceInfoFileType; + +/** + * This header file exposes the initialization of FIROptions to internal use. + */ +@interface FIROptions () + +/** + * resetDefaultOptions and initInternalWithOptionsDictionary: are exposed only for unit tests. + */ ++ (void)resetDefaultOptions; + +/** + * Initializes the options with dictionary. The above strings are the keys of the dictionary. + * This is the designated initializer. + */ +- (instancetype)initInternalWithOptionsDictionary:(NSDictionary *)serviceInfoDictionary; + +/** + * defaultOptions and defaultOptionsDictionary are exposed in order to be used in FIRApp and + * other first party services. + */ ++ (FIROptions *)defaultOptions; + ++ (NSDictionary *)defaultOptionsDictionary; + +/** + * Indicates whether or not Analytics collection was explicitly enabled via a plist flag or at + * runtime. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionExpicitlySet; + +/** + * Whether or not Analytics Collection was enabled. Analytics Collection is enabled unless + * explicitly disabled in GoogleService-Info.plist. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionEnabled; + +/** + * Whether or not Analytics Collection was completely disabled. If YES, then + * isAnalyticsCollectionEnabled will be NO. + */ +@property(nonatomic, readonly) BOOL isAnalyticsCollectionDeactivated; + +/** + * The version ID of the client library, e.g. @"1100000". + */ +@property(nonatomic, readonly, copy) NSString *libraryVersionID; + +/** + * The flag indicating whether this object was constructed with the values in the default plist + * file. + */ +@property(nonatomic) BOOL usingOptionsFromDefaultPlist; + +/** + * Whether or not Measurement was enabled. Measurement is enabled unless explicitly disabled in + * GoogleService-Info.plist. + */ +@property(nonatomic, readonly) BOOL isMeasurementEnabled; + +/** + * Whether or not Analytics was enabled in the developer console. + */ +@property(nonatomic, readonly) BOOL isAnalyticsEnabled; + +/** + * Whether or not SignIn was enabled in the developer console. + */ +@property(nonatomic, readonly) BOOL isSignInEnabled; + +/** + * Whether or not editing is locked. This should occur after FIROptions has been set on a FIRApp. + */ +@property(nonatomic, getter=isEditingLocked) BOOL editingLocked; + +@end diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h new file mode 100644 index 0000000..226efb1 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Private/FIRVersion.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** The version of the Firebase SDK. */ +FOUNDATION_EXPORT const char *const FIRVersionString; + +/** The version of the FirebaseCore Component. */ +FOUNDATION_EXPORT const char *const FIRCoreVersionString; diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h new file mode 100644 index 0000000..ca1d32c --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRAnalyticsConfiguration.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * This class provides configuration fields for Firebase Analytics. + */ +NS_SWIFT_NAME(AnalyticsConfiguration) +@interface FIRAnalyticsConfiguration : NSObject + +/** + * Returns the shared instance of FIRAnalyticsConfiguration. + */ ++ (FIRAnalyticsConfiguration *)sharedInstance NS_SWIFT_NAME(shared()); + +/** + * Sets the minimum engagement time in seconds required to start a new session. The default value + * is 10 seconds. + */ +- (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval; + +/** + * Sets the interval of inactivity in seconds that terminates the current session. The default + * value is 1800 seconds (30 minutes). + */ +- (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval; + +/** + * Sets whether analytics collection is enabled for this app on this device. This setting is + * persisted across app sessions. By default it is enabled. + */ +- (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h new file mode 100644 index 0000000..e0dd6d6 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRApp.h @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIROptions; + +NS_ASSUME_NONNULL_BEGIN + +/** A block that takes a BOOL and has no return value. */ +typedef void (^FIRAppVoidBoolCallback)(BOOL success) NS_SWIFT_NAME(FirebaseAppVoidBoolCallback); + +/** + * The entry point of Firebase SDKs. + * + * Initialize and configure FIRApp using +[FIRApp configure] + * or other customized ways as shown below. + * + * The logging system has two modes: default mode and debug mode. In default mode, only logs with + * log level Notice, Warning and Error will be sent to device. In debug mode, all logs will be sent + * to device. The log levels that Firebase uses are consistent with the ASL log levels. + * + * Enable debug mode by passing the -FIRDebugEnabled argument to the application. You can add this + * argument in the application's Xcode scheme. When debug mode is enabled via -FIRDebugEnabled, + * further executions of the application will also be in debug mode. In order to return to default + * mode, you must explicitly disable the debug mode with the application argument -FIRDebugDisabled. + * + * It is also possible to change the default logging level in code by calling setLoggerLevel: on + * the FIRConfiguration interface. + */ +NS_SWIFT_NAME(FirebaseApp) +@interface FIRApp : NSObject + +/** + * Configures a default Firebase app. Raises an exception if any configuration step fails. The + * default app is named "__FIRAPP_DEFAULT". This method should be called after the app is launched + * and before using Firebase services. This method is thread safe and contains synchronous file I/O + * (reading GoogleService-Info.plist from disk). + */ ++ (void)configure; + +/** + * Configures the default Firebase app with the provided options. The default app is named + * "__FIRAPP_DEFAULT". Raises an exception if any configuration step fails. This method is thread + * safe. + * + * @param options The Firebase application options used to configure the service. + */ ++ (void)configureWithOptions:(FIROptions *)options NS_SWIFT_NAME(configure(options:)); + +/** + * Configures a Firebase app with the given name and options. Raises an exception if any + * configuration step fails. This method is thread safe. + * + * @param name The application's name given by the developer. The name should should only contain + Letters, Numbers and Underscore. + * @param options The Firebase application options used to configure the services. + */ +// clang-format off ++ (void)configureWithName:(NSString *)name + options:(FIROptions *)options NS_SWIFT_NAME(configure(name:options:)); +// clang-format on + +/** + * Returns the default app, or nil if the default app does not exist. + */ ++ (nullable FIRApp *)defaultApp NS_SWIFT_NAME(app()); + +/** + * Returns a previously created FIRApp instance with the given name, or nil if no such app exists. + * This method is thread safe. + */ ++ (nullable FIRApp *)appNamed:(NSString *)name NS_SWIFT_NAME(app(name:)); + +/** + * Returns the set of all extant FIRApp instances, or nil if there are no FIRApp instances. This + * method is thread safe. + */ +@property(class, readonly, nullable) NSDictionary *allApps; + +/** + * Cleans up the current FIRApp, freeing associated data and returning its name to the pool for + * future use. This method is thread safe. + */ +- (void)deleteApp:(FIRAppVoidBoolCallback)completion; + +/** + * FIRApp instances should not be initialized directly. Call +[FIRApp configure], + * +[FIRApp configureWithOptions:], or +[FIRApp configureWithNames:options:] directly. + */ +- (instancetype)init NS_UNAVAILABLE; + +/** + * Gets the name of this app. + */ +@property(nonatomic, copy, readonly) NSString *name; + +/** + * Gets a copy of the options for this app. These are non-modifiable. + */ +@property(nonatomic, copy, readonly) FIROptions *options; + +/** + * Gets or sets whether automatic data collection is enabled for all products. Defaults to `YES` + * unless `FirebaseDataCollectionDefaultEnabled` is set to `NO` in your app's Info.plist. This value + * is persisted across runs of the app so that it can be set once when users have consented to + * collection. + */ +@property(nonatomic, readwrite, getter=isDataCollectionDefaultEnabled) + BOOL dataCollectionDefaultEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h new file mode 100644 index 0000000..95bba5e --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRConfiguration.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRAnalyticsConfiguration.h" +#import "FIRLoggerLevel.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * This interface provides global level properties that the developer can tweak, and the singleton + * of the Firebase Analytics configuration class. + */ +NS_SWIFT_NAME(FirebaseConfiguration) +@interface FIRConfiguration : NSObject + +/** Returns the shared configuration object. */ +@property(class, nonatomic, readonly) FIRConfiguration *sharedInstance NS_SWIFT_NAME(shared); + +/** The configuration class for Firebase Analytics. */ +@property(nonatomic, readwrite) FIRAnalyticsConfiguration *analyticsConfiguration; + +/** + * Sets the logging level for internal Firebase logging. Firebase will only log messages + * that are logged at or below loggerLevel. The messages are logged both to the Xcode + * console and to the device's log. Note that if an app is running from AppStore, it will + * never log above FIRLoggerLevelNotice even if loggerLevel is set to a higher (more verbose) + * setting. + * + * @param loggerLevel The maximum logging level. The default level is set to FIRLoggerLevelNotice. + */ +- (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h new file mode 100644 index 0000000..dca3aa0 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIRLoggerLevel.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Note that importing GULLoggerLevel.h will lead to a non-modular header +// import error. + +/** + * The log levels used by internal logging. + */ +typedef NS_ENUM(NSInteger, FIRLoggerLevel) { + /** Error level, matches ASL_LEVEL_ERR. */ + FIRLoggerLevelError = 3, + /** Warning level, matches ASL_LEVEL_WARNING. */ + FIRLoggerLevelWarning = 4, + /** Notice level, matches ASL_LEVEL_NOTICE. */ + FIRLoggerLevelNotice = 5, + /** Info level, matches ASL_LEVEL_INFO. */ + FIRLoggerLevelInfo = 6, + /** Debug level, matches ASL_LEVEL_DEBUG. */ + FIRLoggerLevelDebug = 7, + /** Minimum log level. */ + FIRLoggerLevelMin = FIRLoggerLevelError, + /** Maximum log level. */ + FIRLoggerLevelMax = FIRLoggerLevelDebug +} NS_SWIFT_NAME(FirebaseLoggerLevel); diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h new file mode 100644 index 0000000..87a01dd --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FIROptions.h @@ -0,0 +1,116 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * This class provides constant fields of Google APIs. + */ +NS_SWIFT_NAME(FirebaseOptions) +@interface FIROptions : NSObject + +/** + * Returns the default options. The first time this is called it synchronously reads + * GoogleService-Info.plist from disk. + */ ++ (nullable FIROptions *)defaultOptions NS_SWIFT_NAME(defaultOptions()); + +/** + * An iOS API key used for authenticating requests from your app, e.g. + * @"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk", used to identify your app to Google servers. + */ +@property(nonatomic, copy, nullable) NSString *APIKey NS_SWIFT_NAME(apiKey); + +/** + * The bundle ID for the application. Defaults to `[[NSBundle mainBundle] bundleID]` when not set + * manually or in a plist. + */ +@property(nonatomic, copy) NSString *bundleID; + +/** + * The OAuth2 client ID for iOS application used to authenticate Google users, for example + * @"12345.apps.googleusercontent.com", used for signing in with Google. + */ +@property(nonatomic, copy, nullable) NSString *clientID; + +/** + * The tracking ID for Google Analytics, e.g. @"UA-12345678-1", used to configure Google Analytics. + */ +@property(nonatomic, copy, nullable) NSString *trackingID; + +/** + * The Project Number from the Google Developer's console, for example @"012345678901", used to + * configure Google Cloud Messaging. + */ +@property(nonatomic, copy) NSString *GCMSenderID NS_SWIFT_NAME(gcmSenderID); + +/** + * The Project ID from the Firebase console, for example @"abc-xyz-123". + */ +@property(nonatomic, copy, nullable) NSString *projectID; + +/** + * The Android client ID used in Google AppInvite when an iOS app has its Android version, for + * example @"12345.apps.googleusercontent.com". + */ +@property(nonatomic, copy, nullable) NSString *androidClientID; + +/** + * The Google App ID that is used to uniquely identify an instance of an app. + */ +@property(nonatomic, copy) NSString *googleAppID; + +/** + * The database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + */ +@property(nonatomic, copy, nullable) NSString *databaseURL; + +/** + * The URL scheme used to set up Durable Deep Link service. + */ +@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; + +/** + * The Google Cloud Storage bucket name, e.g. @"abc-xyz-123.storage.firebase.com". + */ +@property(nonatomic, copy, nullable) NSString *storageBucket; + +/** + * Initializes a customized instance of FIROptions from the file at the given plist file path. This + * will read the file synchronously from disk. + * For example, + * NSString *filePath = + * [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; + * FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; + * Returns nil if the plist file does not exist or is invalid. + */ +- (nullable instancetype)initWithContentsOfFile:(NSString *)plistPath; + +/** + * Initializes a customized instance of FIROptions with required fields. Use the mutable properties + * to modify fields for configuring specific services. + */ +// clang-format off +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID + GCMSenderID:(NSString *)GCMSenderID + NS_SWIFT_NAME(init(googleAppID:gcmSenderID:)); +// clang-format on + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h new file mode 100644 index 0000000..fa26f69 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/Firebase/Core/Public/FirebaseCore.h @@ -0,0 +1,21 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRAnalyticsConfiguration.h" +#import "FIRApp.h" +#import "FIRConfiguration.h" +#import "FIRLoggerLevel.h" +#import "FIROptions.h" diff --git a/My Mind/Pods/FirebaseCore/LICENSE b/My Mind/Pods/FirebaseCore/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseCore/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseCore/README.md b/My Mind/Pods/FirebaseCore/README.md new file mode 100644 index 0000000..d414a4c --- /dev/null +++ b/My Mind/Pods/FirebaseCore/README.md @@ -0,0 +1,193 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Code Formatting + +Travis will verify that any code changes are done in a style compliant way. Install +`clang-format` and `swiftformat`. +This command will get the right `clang-format` version: + +`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/0743d748ba8b41eec074a0a787dc80219142c525/Formula/clang-format.rb` + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDataSnapshot.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDataSnapshot.m new file mode 100644 index 0000000..b774493 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDataSnapshot.m @@ -0,0 +1,101 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDataSnapshot.h" +#import "FIRDataSnapshot_Private.h" +#import "FChildrenNode.h" +#import "FValidation.h" +#import "FTransformedEnumerator.h" +#import "FIRDatabaseReference.h" + +@interface FIRDataSnapshot () +@property (nonatomic, strong) FIRDatabaseReference *ref; +@end + +@implementation FIRDataSnapshot + +- (id)initWithRef:(FIRDatabaseReference *)ref indexedNode:(FIndexedNode *)node +{ + self = [super init]; + if (self != nil) { + self->_ref = ref; + self->_node = node; + } + return self; +} + +- (id) value { + return [self.node.node val]; +} + +- (id) valueInExportFormat { + return [self.node.node valForExport:YES]; +} + +- (FIRDataSnapshot *)childSnapshotForPath:(NSString *)childPathString { + [FValidation validateFrom:@"child:" validPathString:childPathString]; + FPath* childPath = [[FPath alloc] initWith:childPathString]; + FIRDatabaseReference * childRef = [self.ref child:childPathString]; + + id childNode = [self.node.node getChild:childPath]; + return [[FIRDataSnapshot alloc] initWithRef:childRef indexedNode:[FIndexedNode indexedNodeWithNode:childNode]]; +} + +- (BOOL) hasChild:(NSString *)childPathString { + [FValidation validateFrom:@"hasChild:" validPathString:childPathString]; + FPath* childPath = [[FPath alloc] initWith:childPathString]; + return ! [[self.node.node getChild:childPath] isEmpty]; +} + +- (id) priority { + id priority = [self.node.node getPriority]; + return priority.val; +} + + +- (BOOL) hasChildren { + if([self.node.node isLeafNode]) { + return false; + } + else { + return ![self.node.node isEmpty]; + } +} + +- (BOOL) exists { + return ![self.node.node isEmpty]; +} + +- (NSString *) key { + return [self.ref key]; +} + +- (NSUInteger) childrenCount { + return [self.node.node numChildren]; +} + +- (NSEnumerator *) children { + return [[FTransformedEnumerator alloc] initWithEnumerator:self.node.childEnumerator andTransform:^id(FNamedNode *node) { + FIRDatabaseReference *childRef = [self.ref child:node.name]; + return [[FIRDataSnapshot alloc] initWithRef:childRef indexedNode:[FIndexedNode indexedNodeWithNode:node.node]]; + }]; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"Snap (%@) %@", self.key, self.node.node]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabase.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabase.m new file mode 100644 index 0000000..1a2ba88 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabase.m @@ -0,0 +1,211 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import +#import +#import +#import +#import +#import +#import + +#import "FIRDatabase.h" +#import "FIRDatabaseComponent.h" +#import "FIRDatabaseConfig_Private.h" +#import "FIRDatabaseQuery_Private.h" +#import "FIRDatabaseReference_Private.h" +#import "FIRDatabase_Private.h" +#import "FRepoInfo.h" +#import "FValidation.h" + +@implementation FIRDatabase + +// The STR and STR_EXPAND macro allow a numeric version passed to he compiler driver +// with a -D to be treated as a string instead of an invalid floating point value. +#define STR(x) STR_EXPAND(x) +#define STR_EXPAND(x) #x +static const char *FIREBASE_SEMVER = (const char *)STR(FIRDatabase_VERSION); + ++ (FIRDatabase *)database { + if (![FIRApp isDefaultAppConfigured]) { + [NSException raise:@"FIRAppNotConfigured" + format:@"Failed to get default Firebase Database instance. Must call `[FIRApp " + @"configure]` (`FirebaseApp.configure()` in Swift) before using " + @"Firebase Database."]; + } + return [FIRDatabase databaseForApp:[FIRApp defaultApp]]; +} + ++ (FIRDatabase *)databaseWithURL:(NSString *)url { + FIRApp *app = [FIRApp defaultApp]; + if (app == nil) { + [NSException raise:@"FIRAppNotConfigured" + format:@"Failed to get default Firebase Database instance. " + @"Must call `[FIRApp configure]` (`FirebaseApp.configure()` in " + @"Swift) before using Firebase Database."]; + } + return [FIRDatabase databaseForApp:app URL:url]; +} + ++ (FIRDatabase *)databaseForApp:(FIRApp *)app { + if (app == nil) { + [NSException raise:@"InvalidFIRApp" format:@"nil FIRApp instance passed to databaseForApp."]; + } + return [FIRDatabase databaseForApp:app URL:app.options.databaseURL]; +} + ++ (FIRDatabase *)databaseForApp:(FIRApp *)app URL:(NSString *)url { + if (app == nil) { + [NSException raise:@"InvalidFIRApp" + format:@"nil FIRApp instance passed to databaseForApp."]; + } + if (url == nil) { + [NSException raise:@"MissingDatabaseURL" + format:@"Failed to get FirebaseDatabase instance: " + @"Specify DatabaseURL within FIRApp or from your databaseForApp:URL: call."]; + } + id provider = FIR_COMPONENT(FIRDatabaseProvider, app.container); + return [provider databaseForApp:app URL:url]; +} + ++ (NSString *) buildVersion { + // TODO: Restore git hash when build moves back to git + return [NSString stringWithFormat:@"%s_%s", FIREBASE_SEMVER, __DATE__]; +} + ++ (FIRDatabase *)createDatabaseForTests:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config { + FIRDatabase *db = [[FIRDatabase alloc] initWithApp:nil repoInfo:repoInfo config:config]; + [db ensureRepo]; + return db; +} + ++ (NSString *) sdkVersion { + return [NSString stringWithUTF8String:FIREBASE_SEMVER]; +} + ++ (void) setLoggingEnabled:(BOOL)enabled { + [FUtilities setLoggingEnabled:enabled]; + FFLog(@"I-RDB024001", @"BUILD Version: %@", [FIRDatabase buildVersion]); +} + + +- (id)initWithApp:(FIRApp *)app repoInfo:(FRepoInfo *)info config:(FIRDatabaseConfig *)config { + self = [super init]; + if (self != nil) { + self->_repoInfo = info; + self->_config = config; + self->_app = app; + } + return self; +} + +- (FIRDatabaseReference *)reference { + [self ensureRepo]; + + return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:[FPath empty]]; +} + +- (FIRDatabaseReference *)referenceWithPath:(NSString *)path { + [self ensureRepo]; + + [FValidation validateFrom:@"referenceWithPath" validRootPathString:path]; + FPath *childPath = [[FPath alloc] initWith:path]; + return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:childPath]; +} + +- (FIRDatabaseReference *)referenceFromURL:(NSString *)databaseUrl { + [self ensureRepo]; + + if (databaseUrl == nil) { + [NSException raise:@"InvalidDatabaseURL" format:@"Invalid nil url passed to referenceFromURL:"]; + } + FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl]; + [FValidation validateFrom:@"referenceFromURL:" validURL:parsedUrl]; + if (![parsedUrl.repoInfo.host isEqualToString:_repoInfo.host]) { + [NSException raise:@"InvalidDatabaseURL" format:@"Invalid URL (%@) passed to getReference(). URL was expected " + "to match configured Database URL: %@", databaseUrl, [self reference].URL]; + } + return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:parsedUrl.path]; +} + + +- (void)purgeOutstandingWrites { + [self ensureRepo]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo purgeOutstandingWrites]; + }); +} + +- (void)goOnline { + [self ensureRepo]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo resume]; + }); +} + +- (void)goOffline { + [self ensureRepo]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo interrupt]; + }); +} + +- (void)setPersistenceEnabled:(BOOL)persistenceEnabled { + [self assertUnfrozen:@"setPersistenceEnabled"]; + self->_config.persistenceEnabled = persistenceEnabled; +} + +- (BOOL)persistenceEnabled { + return self->_config.persistenceEnabled; +} + +- (void)setPersistenceCacheSizeBytes:(NSUInteger)persistenceCacheSizeBytes { + [self assertUnfrozen:@"setPersistenceCacheSizeBytes"]; + self->_config.persistenceCacheSizeBytes = persistenceCacheSizeBytes; +} + +- (NSUInteger)persistenceCacheSizeBytes { + return self->_config.persistenceCacheSizeBytes; +} + +- (void)setCallbackQueue:(dispatch_queue_t)callbackQueue { + [self assertUnfrozen:@"setCallbackQueue"]; + self->_config.callbackQueue = callbackQueue; +} + +- (dispatch_queue_t)callbackQueue { + return self->_config.callbackQueue; +} + +- (void) assertUnfrozen:(NSString*)methodName { + if (self.repo != nil) { + [NSException raise:@"FIRDatabaseAlreadyInUse" format:@"Calls to %@ must be made before any other usage of " + "FIRDatabase instance.", methodName]; + } +} + +- (void) ensureRepo { + if (self.repo == nil) { + self.repo = [FRepoManager createRepo:self.repoInfo config:self.config database:self]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.h new file mode 100644 index 0000000..37840a1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.h @@ -0,0 +1,44 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRApp; +@class FIRDatabase; + +NS_ASSUME_NONNULL_BEGIN + +/// This protocol is used in the interop registration process to register an instance provider for +/// individual FIRApps. +@protocol FIRDatabaseProvider + +/// Gets a FirebaseDatabase instance for the specified URL, using the specified FirebaseApp. +- (FIRDatabase *)databaseForApp:(FIRApp *)app URL:(NSString *)url; + +@end + +/// A concrete implementation for FIRDatabaseProvider to create Database instances. +@interface FIRDatabaseComponent : NSObject + +/// The FIRApp that instances will be set up with. +@property(nonatomic, weak, readonly) FIRApp *app; + +/// Unavailable, use `databaseForApp:URL:` instead. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.m new file mode 100644 index 0000000..eee0b33 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseComponent.m @@ -0,0 +1,156 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseComponent.h" + +#import "FIRDatabase_Private.h" +#import "FIRDatabaseConfig_Private.h" +#import "FRepoManager.h" + +#import +#import +#import +#import +#import +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** A NSMutableDictionary of FirebaseApp name and FRepoInfo to FirebaseDatabase instance. */ +typedef NSMutableDictionary FIRDatabaseDictionary; + +@interface FIRDatabaseComponent () +@property (nonatomic) FIRDatabaseDictionary *instances; +/// Internal intializer. +- (instancetype)initWithApp:(FIRApp *)app; +@end + +@implementation FIRDatabaseComponent + +#pragma mark - Initialization + +- (instancetype)initWithApp:(FIRApp *)app { + self = [super init]; + if (self) { + _app = app; + _instances = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark - Lifecycle + ++ (void)load { + [FIRComponentContainer registerAsComponentRegistrant:self]; +} + +#pragma mark - FIRComponentRegistrant + ++ (NSArray *)componentsToRegister { + FIRDependency *authDep = + [FIRDependency dependencyWithProtocol:@protocol(FIRAuthInterop) isRequired:NO]; + FIRComponentCreationBlock creationBlock = + ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) { + *isCacheable = YES; + return [[FIRDatabaseComponent alloc] initWithApp:container.app]; + }; + FIRComponent *databaseProvider = + [FIRComponent componentWithProtocol:@protocol(FIRDatabaseProvider) + instantiationTiming:FIRInstantiationTimingLazy + dependencies:@[ authDep ] + creationBlock:creationBlock]; + return @[ databaseProvider ]; +} + +#pragma mark - Instance management. + +- (void)appWillBeDeleted:(FIRApp *)app { + NSString *appName = app.name; + if (appName == nil) { + return; + } + FIRDatabaseDictionary* instances = [self instances]; + @synchronized (instances) { + // Clean up the deleted instance in an effort to remove any resources still in use. + // Note: Any leftover instances of this exact database will be invalid. + for (FIRDatabase * database in [instances allValues]) { + [FRepoManager disposeRepos:database.config]; + } + [instances removeAllObjects]; + } +} + +#pragma mark - FIRDatabaseProvider Conformance + + +- (FIRDatabase *)databaseForApp:(FIRApp *)app URL:(NSString *)url { + if (app == nil) { + [NSException raise:@"InvalidFIRApp" + format:@"nil FIRApp instance passed to databaseForApp."]; + } + + if (url == nil) { + [NSException raise:@"MissingDatabaseURL" + format:@"Failed to get FirebaseDatabase instance: " + "Specify DatabaseURL within FIRApp or from your databaseForApp:URL: call."]; + } + + NSURL *databaseUrl = [NSURL URLWithString:url]; + + if (databaseUrl == nil) { + [NSException raise:@"InvalidDatabaseURL" format:@"The Database URL '%@' cannot be parsed. " + "Specify a valid DatabaseURL within FIRApp or from your databaseForApp:URL: call.", databaseUrl]; + } else if (![databaseUrl.path isEqualToString:@""] && ![databaseUrl.path isEqualToString:@"/"]) { + [NSException raise:@"InvalidDatabaseURL" format:@"Configured Database URL '%@' is invalid. It should point " + "to the root of a Firebase Database but it includes a path: %@",databaseUrl, databaseUrl.path]; + } + + FIRDatabaseDictionary *instances = [self instances]; + @synchronized (instances) { + FParsedUrl *parsedUrl = [FUtilities parseUrl:databaseUrl.absoluteString]; + NSString *urlIndex = + [NSString stringWithFormat:@"%@:%@", parsedUrl.repoInfo.host, [parsedUrl.path toString]]; + FIRDatabase *database = instances[urlIndex]; + if (!database) { + id authTokenProvider = + [FAuthTokenProvider authTokenProviderWithAuth: + FIR_COMPONENT(FIRAuthInterop, app.container)]; + + // If this is the default app, don't set the session persistence key so that we use our + // default ("default") instead of the FIRApp default ("[DEFAULT]") so that we + // preserve the default location used by the legacy Firebase SDK. + NSString *sessionIdentifier = @"default"; + if (![FIRApp isDefaultAppConfigured] || app != [FIRApp defaultApp]) { + sessionIdentifier = app.name; + } + + FIRDatabaseConfig *config = + [[FIRDatabaseConfig alloc] initWithSessionIdentifier:sessionIdentifier + authTokenProvider:authTokenProvider]; + database = [[FIRDatabase alloc] initWithApp:app + repoInfo:parsedUrl.repoInfo + config:config]; + instances[urlIndex] = database; + } + + return database; + } +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.h new file mode 100644 index 0000000..d41f3a8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.h @@ -0,0 +1,63 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FAuthTokenProvider; + +NS_ASSUME_NONNULL_BEGIN + +/** + * TODO: Merge FIRDatabaseConfig into FIRDatabase. + */ +@interface FIRDatabaseConfig : NSObject + +- (id)initWithSessionIdentifier:(NSString *)identifier authTokenProvider:(id)authTokenProvider; + +/** + * By default the Firebase Database client will keep data in memory while your application is running, but not + * when it is restarted. By setting this value to YES, the data will be persisted to on-device (disk) + * storage and will thus be available again when the app is restarted (even when there is no network + * connectivity at that time). Note that this property must be set before creating your first FIRDatabaseReference + * and only needs to be called once per application. + * + * If your app uses Firebase Authentication, the client will automatically persist the user's authentication + * token across restarts, even without persistence enabled. But if the auth token expired while offline and + * you've enabled persistence, the client will pause write operations until you successfully re-authenticate + * (or explicitly unauthenticate) to prevent your writes from being sent unauthenticated and failing due to + * security rules. + */ +@property (nonatomic) BOOL persistenceEnabled; + +/** + * By default the Firebase Database client will use up to 10MB of disk space to cache data. If the cache grows beyond this size, + * the client will start removing data that hasn't been recently used. If you find that your application caches too + * little or too much data, call this method to change the cache size. This property must be set before creating + * your first FIRDatabaseReference and only needs to be called once per application. + * + * Note that the specified cache size is only an approximation and the size on disk may temporarily exceed it + * at times. + */ +@property (nonatomic) NSUInteger persistenceCacheSizeBytes; + +/** + * Sets the dispatch queue on which all events are raised. The default queue is the main queue. + */ +@property (nonatomic, strong) dispatch_queue_t callbackQueue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.m new file mode 100644 index 0000000..a49d4a0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseConfig.m @@ -0,0 +1,84 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseConfig.h" + +#import "FAuthTokenProvider.h" +#import "FIRDatabaseConfig_Private.h" +#import "FIRNoopAuthTokenProvider.h" + +@interface FIRDatabaseConfig (Private) + +@property (nonatomic, strong, readwrite) NSString *sessionIdentifier; + +@end + +@implementation FIRDatabaseConfig + +- (id)init { + [NSException raise:NSInvalidArgumentException format:@"Can't create config objects!"]; + return nil; +} + +- (id)initWithSessionIdentifier:(NSString *)identifier authTokenProvider:(id)authTokenProvider { + self = [super init]; + if (self != nil) { + self->_sessionIdentifier = identifier; + self->_callbackQueue = dispatch_get_main_queue(); + self->_persistenceCacheSizeBytes = 10*1024*1024; // Default cache size is 10MB + self->_authTokenProvider = authTokenProvider; + } + return self; +} + +- (void)assertUnfrozen { + if (self.isFrozen) { + [NSException raise:NSGenericException format:@"Can't modify config objects after they are in use for FIRDatabaseReferences."]; + } +} + +- (void)setAuthTokenProvider:(id)authTokenProvider { + [self assertUnfrozen]; + self->_authTokenProvider = authTokenProvider; +} + +- (void)setPersistenceEnabled:(BOOL)persistenceEnabled { + [self assertUnfrozen]; + self->_persistenceEnabled = persistenceEnabled; +} + +- (void)setPersistenceCacheSizeBytes:(NSUInteger)persistenceCacheSizeBytes { + [self assertUnfrozen]; + // Can't be less than 1MB + if (persistenceCacheSizeBytes < 1024*1024) { + [NSException raise:NSInvalidArgumentException format:@"The minimum cache size must be at least 1MB"]; + } + if (persistenceCacheSizeBytes > 100*1024*1024) { + [NSException raise:NSInvalidArgumentException format:@"Firebase Database currently doesn't support a cache size larger than 100MB"]; + } + self->_persistenceCacheSizeBytes = persistenceCacheSizeBytes; +} + +- (void)setCallbackQueue:(dispatch_queue_t)callbackQueue { + [self assertUnfrozen]; + self->_callbackQueue = callbackQueue; +} + +- (void)freeze { + self->_isFrozen = YES; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseQuery.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseQuery.m new file mode 100644 index 0000000..de18a7c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRDatabaseQuery.m @@ -0,0 +1,525 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseQuery.h" +#import "FIRDatabaseQuery_Private.h" +#import "FValidation.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FValueEventRegistration.h" +#import "FChildEventRegistration.h" +#import "FPath.h" +#import "FKeyIndex.h" +#import "FPathIndex.h" +#import "FPriorityIndex.h" +#import "FValueIndex.h" +#import "FLeafNode.h" +#import "FSnapshotUtilities.h" +#import "FConstants.h" + +@implementation FIRDatabaseQuery + +@synthesize repo; +@synthesize path; +@synthesize queryParams; + +#define INVALID_QUERY_PARAM_ERROR @"InvalidQueryParameter" + + ++ (dispatch_queue_t)sharedQueue +{ + // We use this shared queue across all of the FQueries so things happen FIFO (as opposed to dispatch_get_global_queue(0, 0) which is concurrent) + static dispatch_once_t pred; + static dispatch_queue_t sharedDispatchQueue; + + dispatch_once(&pred, ^{ + sharedDispatchQueue = dispatch_queue_create("FirebaseWorker", NULL); + }); + + return sharedDispatchQueue; +} + +- (id) initWithRepo:(FRepo *)theRepo path:(FPath *)thePath { + return [self initWithRepo:theRepo path:thePath params:nil orderByCalled:NO priorityMethodCalled:NO]; +} + +- (id) initWithRepo:(FRepo *)theRepo + path:(FPath *)thePath + params:(FQueryParams *)theParams + orderByCalled:(BOOL)orderByCalled +priorityMethodCalled:(BOOL)priorityMethodCalled { + self = [super init]; + if (self) { + self.repo = theRepo; + self.path = thePath; + if (!theParams) { + theParams = [FQueryParams defaultInstance]; + } + if (![theParams isValid]) { + @throw [[NSException alloc] initWithName:@"InvalidArgumentError" reason:@"Queries are limited to two constraints" userInfo:nil]; + } + self.queryParams = theParams; + self.orderByCalled = orderByCalled; + self.priorityMethodCalled = priorityMethodCalled; + } + return self; +} + +- (FQuerySpec *)querySpec { + return [[FQuerySpec alloc] initWithPath:self.path params:self.queryParams]; +} + +- (void)validateQueryEndpointsForParams:(FQueryParams *)params { + if ([params.index isEqual:[FKeyIndex keyIndex]]) { + if ([params hasStart]) { + if (params.indexStartKey != [FUtilities minName]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't use queryStartingAtValue:childKey: or queryEqualTo:andChildKey: in combination with queryOrderedByKey"]; + } + if (![params.indexStartValue.val isKindOfClass:[NSString class]]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't use queryStartingAtValue: with other types than string in combination with queryOrderedByKey"]; + } + } + if ([params hasEnd]) { + if (params.indexEndKey != [FUtilities maxName]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't use queryEndingAtValue:childKey: or queryEqualToValue:childKey: in combination with queryOrderedByKey"]; + } + if (![params.indexEndValue.val isKindOfClass:[NSString class]]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't use queryEndingAtValue: with other types than string in combination with queryOrderedByKey"]; + } + } + } else if ([params.index isEqual:[FPriorityIndex priorityIndex]]) { + if (([params hasStart] && ![FValidation validatePriorityValue:params.indexStartValue.val]) || + ([params hasEnd] && ![FValidation validatePriorityValue:params.indexEndValue.val])) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"When using queryOrderedByPriority, values provided to queryStartingAtValue:, queryEndingAtValue:, or queryEqualToValue: must be valid priorities."]; + } + } +} + +- (void)validateEqualToCall { + if ([self.queryParams hasStart]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Cannot combine queryEqualToValue: and queryStartingAtValue:"]; + } + if ([self.queryParams hasEnd]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Cannot combine queryEqualToValue: and queryEndingAtValue:"]; + } +} + +- (void)validateNoPreviousOrderByCalled { + if (self.orderByCalled) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Cannot use multiple queryOrderedBy calls!"]; + } +} + +- (void)validateIndexValueType:(id)type fromMethod:(NSString *)method { + if (type != nil && + ![type isKindOfClass:[NSNumber class]] && + ![type isKindOfClass:[NSString class]] && + ![type isKindOfClass:[NSNull class]]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"You can only pass nil, NSString or NSNumber to %@", method]; + } +} + +- (FIRDatabaseQuery *)queryStartingAtValue:(id)startValue { + return [self queryStartingAtInternal:startValue childKey:nil from:@"queryStartingAtValue:" priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryStartingAtValue:(id)startValue childKey:(NSString *)childKey { + if ([self.queryParams.index isEqual:[FKeyIndex keyIndex]]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:@"You must use queryStartingAtValue: instead of queryStartingAtValue:childKey: when using queryOrderedByKey:" + userInfo:nil]; + } + return [self queryStartingAtInternal:startValue + childKey:childKey + from:@"queryStartingAtValue:childKey:" + priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryStartingAtInternal:(id)startValue + childKey:(NSString *)childKey + from:(NSString *)methodName + priorityMethod:(BOOL)priorityMethod { + [self validateIndexValueType:startValue fromMethod:methodName]; + if (childKey != nil) { + [FValidation validateFrom:methodName validKey:childKey]; + } + if ([self.queryParams hasStart]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR + format:@"Can't call %@ after queryStartingAtValue or queryEqualToValue was previously called", methodName]; + } + id startNode = [FSnapshotUtilities nodeFrom:startValue]; + FQueryParams* params = [self.queryParams startAt:startNode childKey:childKey]; + [self validateQueryEndpointsForParams:params]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:self.orderByCalled + priorityMethodCalled:priorityMethod || self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *)queryEndingAtValue:(id)endValue { + return [self queryEndingAtInternal:endValue + childKey:nil + from:@"queryEndingAtValue:" + priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryEndingAtValue:(id)endValue childKey:(NSString *)childKey { + if ([self.queryParams.index isEqual:[FKeyIndex keyIndex]]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:@"You must use queryEndingAtValue: instead of queryEndingAtValue:childKey: when using queryOrderedByKey:" + userInfo:nil]; + } + + return [self queryEndingAtInternal:endValue + childKey:childKey + from:@"queryEndingAtValue:childKey:" + priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryEndingAtInternal:(id)endValue + childKey:(NSString *)childKey + from:(NSString *)methodName + priorityMethod:(BOOL)priorityMethod { + [self validateIndexValueType:endValue fromMethod:methodName]; + if (childKey != nil) { + [FValidation validateFrom:methodName validKey:childKey]; + } + if ([self.queryParams hasEnd]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR + format:@"Can't call %@ after queryEndingAtValue or queryEqualToValue was previously called", methodName]; + } + id endNode = [FSnapshotUtilities nodeFrom:endValue]; + FQueryParams* params = [self.queryParams endAt:endNode childKey:childKey]; + [self validateQueryEndpointsForParams:params]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:self.orderByCalled + priorityMethodCalled:priorityMethod || self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *)queryEqualToValue:(id)value { + return [self queryEqualToInternal:value childKey:nil from:@"queryEqualToValue:" priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryEqualToValue:(id)value childKey:(NSString *)childKey { + if ([self.queryParams.index isEqual:[FKeyIndex keyIndex]]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:@"You must use queryEqualToValue: instead of queryEqualTo:childKey: when using queryOrderedByKey:" + userInfo:nil]; + } + return [self queryEqualToInternal:value childKey:childKey from:@"queryEqualToValue:childKey:" priorityMethod:NO]; +} + +- (FIRDatabaseQuery *)queryEqualToInternal:(id)value + childKey:(NSString *)childKey + from:(NSString *)methodName + priorityMethod:(BOOL)priorityMethod { + [self validateIndexValueType:value fromMethod:methodName]; + if (childKey != nil) { + [FValidation validateFrom:methodName validKey:childKey]; + } + if ([self.queryParams hasEnd] || [self.queryParams hasStart]) { + [NSException raise:INVALID_QUERY_PARAM_ERROR + format:@"Can't call %@ after queryStartingAtValue, queryEndingAtValue or queryEqualToValue was previously called", methodName]; + } + id node = [FSnapshotUtilities nodeFrom:value]; + FQueryParams* params = [[self.queryParams startAt:node childKey:childKey] endAt:node childKey:childKey]; + [self validateQueryEndpointsForParams:params]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:self.orderByCalled + priorityMethodCalled:priorityMethod || self.priorityMethodCalled]; +} + +- (void)validateLimitRange:(NSUInteger)limit +{ + // No need to check for negative ranges, since limit is unsigned + if (limit == 0) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Limit can't be zero"]; + } + if (limit >= 1ul<<31) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Limit must be less than 2,147,483,648"]; + } +} + +- (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit { + if (self.queryParams.limitSet) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't call queryLimitedToFirst: if a limit was previously set"]; + } + [self validateLimitRange:limit]; + FQueryParams* params = [self.queryParams limitToFirst:limit]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:self.orderByCalled + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit { + if (self.queryParams.limitSet) { + [NSException raise:INVALID_QUERY_PARAM_ERROR format:@"Can't call queryLimitedToLast: if a limit was previously set"]; + } + [self validateLimitRange:limit]; + FQueryParams* params = [self.queryParams limitToLast:limit]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:self.orderByCalled + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)indexPathString { + if ([indexPathString isEqualToString:@"$key"] || [indexPathString isEqualToString:@".key"]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:[NSString stringWithFormat:@"(queryOrderedByChild:) %@ is invalid. Use queryOrderedByKey: instead.", indexPathString] + userInfo:nil]; + } else if ([indexPathString isEqualToString:@"$priority"] || [indexPathString isEqualToString:@".priority"]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:[NSString stringWithFormat:@"(queryOrderedByChild:) %@ is invalid. Use queryOrderedByPriority: instead.", indexPathString] + userInfo:nil]; + } else if ([indexPathString isEqualToString:@"$value"] || [indexPathString isEqualToString:@".value"]) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:[NSString stringWithFormat:@"(queryOrderedByChild:) %@ is invalid. Use queryOrderedByValue: instead.", indexPathString] + userInfo:nil]; + } + [self validateNoPreviousOrderByCalled]; + + [FValidation validateFrom:@"queryOrderedByChild:" validPathString:indexPathString]; + FPath *indexPath = [FPath pathWithString:indexPathString]; + if (indexPath.isEmpty) { + @throw [[NSException alloc] initWithName:INVALID_QUERY_PARAM_ERROR + reason:[NSString stringWithFormat:@"(queryOrderedByChild:) with an empty path is invalid. Use queryOrderedByValue: instead."] + userInfo:nil]; + } + id index = [[FPathIndex alloc] initWithPath:indexPath]; + + FQueryParams *params = [self.queryParams orderBy:index]; + [self validateQueryEndpointsForParams:params]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:YES + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *) queryOrderedByKey { + [self validateNoPreviousOrderByCalled]; + FQueryParams *params = [self.queryParams orderBy:[FKeyIndex keyIndex]]; + [self validateQueryEndpointsForParams:params]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:YES + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *) queryOrderedByValue { + [self validateNoPreviousOrderByCalled]; + FQueryParams *params = [self.queryParams orderBy:[FValueIndex valueIndex]]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:YES + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseQuery *) queryOrderedByPriority { + [self validateNoPreviousOrderByCalled]; + FQueryParams *params = [self.queryParams orderBy:[FPriorityIndex priorityIndex]]; + return [[FIRDatabaseQuery alloc] initWithRepo:self.repo + path:self.path + params:params + orderByCalled:YES + priorityMethodCalled:self.priorityMethodCalled]; +} + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *))block { + [FValidation validateFrom:@"observeEventType:withBlock:" knownEventType:eventType]; + return [self observeEventType:eventType withBlock:block withCancelBlock:nil]; +} + + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block { + [FValidation validateFrom:@"observeEventType:andPreviousSiblingKeyWithBlock:" knownEventType:eventType]; + return [self observeEventType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:nil]; +} + + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block withCancelBlock:(fbt_void_nserror)cancelBlock { + [FValidation validateFrom:@"observeEventType:withBlock:withCancelBlock:" knownEventType:eventType]; + + if (eventType == FIRDataEventTypeValue) { + // Handle FIRDataEventTypeValue specially because they shouldn't have prevName callbacks + NSUInteger handle = [[FUtilities LUIDGenerator] integerValue]; + [self observeValueEventWithHandle:handle withBlock:block cancelCallback:cancelBlock]; + return handle; + } else { + // Wrap up the userCallback so we can treat everything as a callback that has a prevName + fbt_void_datasnapshot userCallback = [block copy]; + return [self observeEventType:eventType andPreviousSiblingKeyWithBlock:^(FIRDataSnapshot *snapshot, NSString *prevName) { + if (userCallback != nil) { + userCallback(snapshot); + } + } withCancelBlock:cancelBlock]; + } +} + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block withCancelBlock:(fbt_void_nserror)cancelBlock { + [FValidation validateFrom:@"observeEventType:andPreviousSiblingKeyWithBlock:withCancelBlock:" knownEventType:eventType]; + + + if (eventType == FIRDataEventTypeValue) { + // TODO: This gets hit by observeSingleEventOfType. Need to fix. + /* + @throw [[NSException alloc] initWithName:@"InvalidEventTypeForObserver" + reason:@"(observeEventType:andPreviousSiblingKeyWithBlock:withCancelBlock:) Cannot use observeEventType:andPreviousSiblingKeyWithBlock:withCancelBlock: with FIRDataEventTypeValue. Use observeEventType:withBlock:withCancelBlock: instead." + userInfo:nil]; + */ + } + + NSUInteger handle = [[FUtilities LUIDGenerator] integerValue]; + NSDictionary *callbacks = @{[NSNumber numberWithInteger:eventType]: [block copy]}; + [self observeChildEventWithHandle:handle withCallbacks:callbacks cancelCallback:cancelBlock]; + + return handle; +} + +// If we want to distinguish between value event listeners and child event listeners, like in the Java client, we can +// consider exporting this. If we do, add argument validation. Otherwise, arguments are validated in the public-facing +// portions of the API. Also, move the FIRDatabaseHandle logic. +- (void)observeValueEventWithHandle:(FIRDatabaseHandle)handle withBlock:(fbt_void_datasnapshot)block cancelCallback:(fbt_void_nserror)cancelBlock { + // Note that we don't need to copy the callbacks here, FEventRegistration callback properties set to copy + FValueEventRegistration *registration = [[FValueEventRegistration alloc] initWithRepo:self.repo + handle:handle + callback:block + cancelCallback:cancelBlock]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo addEventRegistration:registration forQuery:self.querySpec]; + }); +} + +// Note: as with the above method, we may wish to expose this at some point. +- (void)observeChildEventWithHandle:(FIRDatabaseHandle)handle withCallbacks:(NSDictionary *)callbacks cancelCallback:(fbt_void_nserror)cancelBlock { + // Note that we don't need to copy the callbacks here, FEventRegistration callback properties set to copy + FChildEventRegistration *registration = [[FChildEventRegistration alloc] initWithRepo:self.repo + handle:handle + callbacks:callbacks + cancelCallback:cancelBlock]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo addEventRegistration:registration forQuery:self.querySpec]; + }); +} + + +- (void) removeObserverWithHandle:(FIRDatabaseHandle)handle { + FValueEventRegistration *event = [[FValueEventRegistration alloc] initWithRepo:self.repo + handle:handle + callback:nil + cancelCallback:nil]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo removeEventRegistration:event forQuery:self.querySpec]; + }); +} + + +- (void) removeAllObservers { + [self removeObserverWithHandle:NSNotFound]; +} + +- (void)keepSynced:(BOOL)keepSynced { + if ([self.path.getFront isEqualToString:kDotInfoPrefix]) { + [NSException raise:NSInvalidArgumentException format:@"Can't keep query on .info tree synced (this already is the case)."]; + } + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo keepQuery:self.querySpec synced:keepSynced]; + }); +} + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block { + + [self observeSingleEventOfType:eventType withBlock:block withCancelBlock:nil]; +} + + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block { + + [self observeSingleEventOfType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:nil]; +} + + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block withCancelBlock:(fbt_void_nserror)cancelBlock { + + // XXX: user reported memory leak in method + + // "When you copy a block, any references to other blocks from within that block are copied if necessary—an entire tree may be copied (from the top). If you have block variables and you reference a block from within the block, that block will be copied." + // http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW1 + // So... we don't need to do this since inside the on: we copy this block off the stack to the heap. + // __block fbt_void_datasnapshot userCallback = [callback copy]; + + [self observeSingleEventOfType:eventType andPreviousSiblingKeyWithBlock:^(FIRDataSnapshot *snapshot, NSString *prevName) { + if (block != nil) { + block(snapshot); + } + } withCancelBlock:cancelBlock]; +} + +/** +* Attaches a listener, waits for the first event, and then removes the listener +*/ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block withCancelBlock:(fbt_void_nserror)cancelBlock { + + // XXX: user reported memory leak in method + + // "When you copy a block, any references to other blocks from within that block are copied if necessary—an entire tree may be copied (from the top). If you have block variables and you reference a block from within the block, that block will be copied." + // http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW1 + // So... we don't need to do this since inside the on: we copy this block off the stack to the heap. + // __block fbt_void_datasnapshot userCallback = [callback copy]; + + __block FIRDatabaseHandle handle; + __block BOOL firstCall = YES; + + fbt_void_datasnapshot_nsstring callback = [block copy]; + fbt_void_datasnapshot_nsstring wrappedCallback = ^(FIRDataSnapshot *snap, NSString* prevName) { + if (firstCall) { + firstCall = NO; + [self removeObserverWithHandle:handle]; + callback(snap, prevName); + } + }; + + fbt_void_nserror cancelCallback = [cancelBlock copy]; + handle = [self observeEventType:eventType andPreviousSiblingKeyWithBlock:wrappedCallback withCancelBlock:^(NSError* error){ + + [self removeObserverWithHandle:handle]; + + if (cancelCallback) { + cancelCallback(error); + } + }]; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"(%@ %@)", self.path, self.queryParams.description]; +} + +- (FIRDatabaseReference *) ref { + return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:self.path]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRMutableData.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRMutableData.m new file mode 100644 index 0000000..77a022a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRMutableData.m @@ -0,0 +1,134 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMutableData.h" +#import "FIRMutableData_Private.h" +#import "FSnapshotHolder.h" +#import "FSnapshotUtilities.h" +#import "FChildrenNode.h" +#import "FTransformedEnumerator.h" +#import "FNamedNode.h" +#import "FIndexedNode.h" + +@interface FIRMutableData () + +- (id) initWithPrefixPath:(FPath *)path andSnapshotHolder:(FSnapshotHolder *)snapshotHolder; + +@property (strong, nonatomic) FSnapshotHolder* data; +@property (strong, nonatomic) FPath* prefixPath; + +@end + +@implementation FIRMutableData + +@synthesize data; +@synthesize prefixPath; + +- (id) initWithNode:(id)node { + FSnapshotHolder* holder = [[FSnapshotHolder alloc] init]; + FPath* path = [FPath empty]; + [holder updateSnapshot:path withNewSnapshot:node]; + return [self initWithPrefixPath:path andSnapshotHolder:holder]; +} + +- (id) initWithPrefixPath:(FPath *)path andSnapshotHolder:(FSnapshotHolder *)snapshotHolder { + self = [super init]; + if (self) { + self.prefixPath = path; + self.data = snapshotHolder; + } + return self; +} + +- (FIRMutableData *)childDataByAppendingPath:(NSString *)path { + FPath* wholePath = [self.prefixPath childFromString:path]; + return [[FIRMutableData alloc] initWithPrefixPath:wholePath andSnapshotHolder:self.data]; +} + +- (FIRMutableData *) parent { + if ([self.prefixPath isEmpty]) { + return nil; + } else { + FPath* path = [self.prefixPath parent]; + return [[FIRMutableData alloc] initWithPrefixPath:path andSnapshotHolder:self.data]; + } +} + +- (void) setValue:(id)aValue { + id node = [FSnapshotUtilities nodeFrom:aValue withValidationFrom:@"setValue:"]; + [self.data updateSnapshot:self.prefixPath withNewSnapshot:node]; +} + +- (void) setPriority:(id)aPriority { + id node = [self.data getNode:self.prefixPath]; + id pri = [FSnapshotUtilities nodeFrom:aPriority]; + node = [node updatePriority:pri]; + [self.data updateSnapshot:self.prefixPath withNewSnapshot:node]; +} + +- (id) value { + return [[self.data getNode:self.prefixPath] val]; +} + +- (id) priority { + return [[[self.data getNode:self.prefixPath] getPriority] val]; +} + +- (BOOL) hasChildren { + id node = [self.data getNode:self.prefixPath]; + return ![node isLeafNode] && ![(FChildrenNode*)node isEmpty]; +} + +- (BOOL) hasChildAtPath:(NSString *)path { + id node = [self.data getNode:self.prefixPath]; + FPath* childPath = [[FPath alloc] initWith:path]; + return ![[node getChild:childPath] isEmpty]; +} + +- (NSUInteger) childrenCount { + return [[self.data getNode:self.prefixPath] numChildren]; +} + +- (NSString *) key { + return [self.prefixPath getBack]; +} + +- (id) nodeValue { + return [self.data getNode:self.prefixPath]; +} + +- (NSEnumerator *) children { + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:self.nodeValue]; + return [[FTransformedEnumerator alloc] initWithEnumerator:[indexedNode childEnumerator] andTransform:^id(FNamedNode *node) { + FPath* childPath = [self.prefixPath childFromString:node.name]; + FIRMutableData * childData = [[FIRMutableData alloc] initWithPrefixPath:childPath andSnapshotHolder:self.data]; + return childData; + }]; +} + +- (BOOL) isEqualToData:(FIRMutableData *)other { + return self.data == other.data && [[self.prefixPath description] isEqualToString:[other.prefixPath description]]; +} + +- (NSString *) description { + if (self.key == nil) { + return [NSString stringWithFormat:@"FIRMutableData (top-most transaction) %@ %@", self.key, self.value]; + } else { + return [NSString stringWithFormat:@"FIRMutableData (%@) %@", self.key, self.value]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRServerValue.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRServerValue.m new file mode 100644 index 0000000..14bb745 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRServerValue.m @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseReference.h" +#import "FIRServerValue.h" + +@implementation FIRServerValue + ++ (NSDictionary *) timestamp { + static NSDictionary *timestamp = nil; + if (timestamp == nil) { + timestamp = @{ @".sv": @"timestamp" }; + } + return timestamp; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRTransactionResult.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRTransactionResult.m new file mode 100644 index 0000000..8afc5b7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/FIRTransactionResult.m @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRTransactionResult.h" +#import "FIRTransactionResult_Private.h" + +@implementation FIRTransactionResult + +@synthesize update; +@synthesize isSuccess; + ++ (FIRTransactionResult *)successWithValue:(FIRMutableData *)value { + FIRTransactionResult * result = [[FIRTransactionResult alloc] init]; + result.isSuccess = YES; + result.update = value; + return result; +} + ++ (FIRTransactionResult *) abort { + FIRTransactionResult * result = [[FIRTransactionResult alloc] init]; + result.isSuccess = NO; + result.update = nil; + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDataSnapshot_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDataSnapshot_Private.h new file mode 100644 index 0000000..c2d3871 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDataSnapshot_Private.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDataSnapshot.h" +#import "FIndexedNode.h" +#import "FTypedefs_Private.h" + +@interface FIRDataSnapshot () + +// in _Private for testing purposes +@property (nonatomic, strong) FIndexedNode *node; + +- (id)initWithRef:(FIRDatabaseReference *)ref indexedNode:(FIndexedNode *)node; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseQuery_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseQuery_Private.h new file mode 100644 index 0000000..3a10fe3 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseQuery_Private.h @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRepo.h" +#import "FPath.h" +#import "FRepoManager.h" +#import "FTypedefs_Private.h" +#import "FQueryParams.h" +#import "FIRDatabaseQuery.h" + +@interface FIRDatabaseQuery () + ++ (dispatch_queue_t)sharedQueue; + +- (id) initWithRepo:(FRepo *)repo path:(FPath *)path; +- (id) initWithRepo:(FRepo *)repo + path:(FPath *)path + params:(FQueryParams *)params + orderByCalled:(BOOL)orderByCalled +priorityMethodCalled:(BOOL)priorityMethodCalled; + +@property (nonatomic, strong) FRepo* repo; +@property (nonatomic, strong) FPath* path; +@property (nonatomic, strong) FQueryParams *queryParams; +@property (nonatomic) BOOL orderByCalled; +@property (nonatomic) BOOL priorityMethodCalled; + +- (FQuerySpec *)querySpec; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseReference_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseReference_Private.h new file mode 100644 index 0000000..6063cb8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabaseReference_Private.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseReference.h" +#import "FTypedefs_Private.h" +#import "FIRDatabaseConfig.h" +#import "FRepo.h" + +@interface FIRDatabaseReference () + +- (id)initWithConfig:(FIRDatabaseConfig *)config; +- (id)initWithRepo:(FRepo *)repo path:(FPath *)path; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabase_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabase_Private.h new file mode 100644 index 0000000..5e29451 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRDatabase_Private.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabase.h" + +@class FRepo; +@class FRepoInfo; +@class FIRDatabaseConfig; + +@interface FIRDatabase () + +@property (nonatomic, strong) FRepoInfo *repoInfo; +@property (nonatomic, strong) FIRDatabaseConfig *config; +@property (nonatomic, strong) FRepo *repo; + +- (id)initWithApp:(FIRApp *)app repoInfo:(FRepoInfo *)info config:(FIRDatabaseConfig *)config; + ++ (NSString *) buildVersion; ++ (FIRDatabase *) createDatabaseForTests:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRMutableData_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRMutableData_Private.h new file mode 100644 index 0000000..ee3aa96 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRMutableData_Private.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMutableData.h" +#import "FNode.h" + +@interface FIRMutableData () + +- (id) initWithNode:(id)node; +- (id) nodeValue; +- (BOOL) isEqualToData:(FIRMutableData *)other; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRTransactionResult_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRTransactionResult_Private.h new file mode 100644 index 0000000..82290f2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FIRTransactionResult_Private.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRTransactionResult.h" +#import "FIRMutableData.h" + +@interface FIRTransactionResult () + +@property (nonatomic) BOOL isSuccess; +@property (nonatomic, strong) FIRMutableData * update; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FTypedefs_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FTypedefs_Private.h new file mode 100644 index 0000000..73f4c9a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Api/Private/FTypedefs_Private.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FTYPEDEFS_PRIVATE__ +#define __FTYPEDEFS_PRIVATE__ + +#import + +typedef NS_ENUM(NSInteger, FTransactionStatus) { + FTransactionInitializing, // 0 + FTransactionRun, // 1 + FTransactionSent, // 2 + FTransactionCompleted, // 3 + FTransactionSentNeedsAbort, // 4 + FTransactionNeedsAbort // 5 +}; + +@protocol FNode; +@class FPath; +@class FIRTransactionResult; +@class FIRMutableData; +@class FIRDataSnapshot; +@class FCompoundHash; + +typedef void (^fbt_void_nserror_bool_datasnapshot) (NSError* error, BOOL committed, FIRDataSnapshot * snapshot); +typedef FIRTransactionResult * (^fbt_transactionresult_mutabledata) (FIRMutableData * currentData); +typedef void (^fbt_void_path_node) (FPath*, id); +typedef void (^fbt_void_nsstring) (NSString *); +typedef BOOL (^fbt_bool_nsstring_node) (NSString *, id); +typedef void (^fbt_void_path_node_marray) (FPath *, id, NSMutableArray *); +typedef BOOL (^fbt_bool_void) (void); +typedef void (^fbt_void_nsstring_nsstring)(NSString *str1, NSString* str2); +typedef void (^fbt_void_nsstring_nserror)(NSString *str, NSError* error); +typedef BOOL (^fbt_bool_path)(FPath *str); +typedef void (^fbt_void_id)(id data); +typedef NSString* (^fbt_nsstring_void) (void); +typedef FCompoundHash* (^fbt_compoundhash_void) (void); +typedef NSArray* (^fbt_nsarray_nsstring_id)(NSString *status, id Data); +typedef NSArray* (^fbt_nsarray_nsstring)(NSString *status); + +// WWDC 2012 session 712 starting in page 83 for saving blocks in properties (use @property (strong) type name). + +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.h new file mode 100644 index 0000000..e97a8a1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.h @@ -0,0 +1,190 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Firebase_FConstants_h +#define Firebase_FConstants_h + +#import + +#pragma mark - +#pragma mark Wire Protocol Envelope Constants + +FOUNDATION_EXPORT NSString *const kFWPRequestType; +FOUNDATION_EXPORT NSString *const kFWPRequestTypeData; +FOUNDATION_EXPORT NSString *const kFWPRequestDataPayload; +FOUNDATION_EXPORT NSString *const kFWPRequestNumber; +FOUNDATION_EXPORT NSString *const kFWPRequestPayloadBody; +FOUNDATION_EXPORT NSString *const kFWPRequestError; +FOUNDATION_EXPORT NSString *const kFWPRequestAction; +FOUNDATION_EXPORT NSString *const kFWPResponseForRNData; +FOUNDATION_EXPORT NSString *const kFWPResponseForActionStatus; +FOUNDATION_EXPORT NSString *const kFWPResponseForActionStatusOk; +FOUNDATION_EXPORT NSString *const kFWPResponseForActionStatusDataStale; +FOUNDATION_EXPORT NSString *const kFWPResponseForActionData; +FOUNDATION_EXPORT NSString *const kFWPResponseDataWarnings; + +FOUNDATION_EXPORT NSString *const kFWPAsyncServerAction; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerPayloadBody; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdate; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataMerge; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataRangeMerge; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerAuthRevoked; +FOUNDATION_EXPORT NSString *const kFWPASyncServerListenCancelled; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerSecurityDebug; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateBodyPath; // {“a”: “d”, “b”: {“p”: “/”, “d”: “”}} +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateBodyData; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateStartPath; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateEndPath; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateRangeMerge; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataUpdateBodyTag; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataQueries; + +FOUNDATION_EXPORT NSString *const kFWPAsyncServerEnvelopeType; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerEnvelopeData; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerControlMessage; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerControlMessageType; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerControlMessageData; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerDataMessage; + +FOUNDATION_EXPORT NSString *const kFWPAsyncServerHello; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerHelloTimestamp; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerHelloVersion; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerHelloConnectedHost; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerHelloSession; + +FOUNDATION_EXPORT NSString *const kFWPAsyncServerControlMessageShutdown; +FOUNDATION_EXPORT NSString *const kFWPAsyncServerControlMessageReset; + +#pragma mark - +#pragma mark Wire Protocol Payload Constants + +FOUNDATION_EXPORT NSString *const kFWPRequestActionPut; +FOUNDATION_EXPORT NSString *const kFWPRequestActionMerge; +FOUNDATION_EXPORT NSString *const kFWPRequestActionTaggedListen; +FOUNDATION_EXPORT NSString *const kFWPRequestActionTaggedUnlisten; +FOUNDATION_EXPORT NSString *const kFWPRequestActionListen; // {"t": "d", "d": {"r": 1, "a": "l", "b": { "p": "/" } } } +FOUNDATION_EXPORT NSString *const kFWPRequestActionUnlisten; +FOUNDATION_EXPORT NSString *const kFWPRequestActionStats; +FOUNDATION_EXPORT NSString *const kFWPRequestActionDisconnectPut; +FOUNDATION_EXPORT NSString *const kFWPRequestActionDisconnectMerge; +FOUNDATION_EXPORT NSString *const kFWPRequestActionDisconnectCancel; +FOUNDATION_EXPORT NSString *const kFWPRequestActionAuth; +FOUNDATION_EXPORT NSString *const kFWPRequestActionUnauth; +FOUNDATION_EXPORT NSString *const kFWPRequestCredential; +FOUNDATION_EXPORT NSString *const kFWPRequestPath; +FOUNDATION_EXPORT NSString *const kFWPRequestCounters; +FOUNDATION_EXPORT NSString *const kFWPRequestQueries; +FOUNDATION_EXPORT NSString *const kFWPRequestTag; +FOUNDATION_EXPORT NSString *const kFWPRequestData; +FOUNDATION_EXPORT NSString *const kFWPRequestHash; +FOUNDATION_EXPORT NSString *const kFWPRequestCompoundHash; +FOUNDATION_EXPORT NSString *const kFWPRequestCompoundHashPaths; +FOUNDATION_EXPORT NSString *const kFWPRequestCompoundHashHashes; +FOUNDATION_EXPORT NSString *const kFWPRequestStatus; + +#pragma mark - +#pragma mark Websock Transport Constants + +FOUNDATION_EXPORT NSString *const kWireProtocolVersionParam; +FOUNDATION_EXPORT NSString *const kWebsocketProtocolVersion; +FOUNDATION_EXPORT NSString *const kWebsocketServerKillPacket; +FOUNDATION_EXPORT const int kWebsocketMaxFrameSize; +FOUNDATION_EXPORT NSUInteger const kWebsocketKeepaliveInterval; +FOUNDATION_EXPORT NSUInteger const kWebsocketConnectTimeout; + +FOUNDATION_EXPORT float const kPersistentConnReconnectMinDelay; +FOUNDATION_EXPORT float const kPersistentConnReconnectMaxDelay; +FOUNDATION_EXPORT float const kPersistentConnReconnectMultiplier; +FOUNDATION_EXPORT float const kPersistentConnSuccessfulConnectionEstablishedDelay; + +#pragma mark - +#pragma mark Query / QueryParams constants + +FOUNDATION_EXPORT NSString *const kQueryDefault; +FOUNDATION_EXPORT NSString *const kQueryDefaultObject; +FOUNDATION_EXPORT NSString *const kViewManagerDictConstView; +FOUNDATION_EXPORT NSString *const kFQPIndexStartValue; +FOUNDATION_EXPORT NSString *const kFQPIndexStartName; +FOUNDATION_EXPORT NSString *const kFQPIndexEndValue; +FOUNDATION_EXPORT NSString *const kFQPIndexEndName; +FOUNDATION_EXPORT NSString *const kFQPLimit; +FOUNDATION_EXPORT NSString *const kFQPViewFrom; +FOUNDATION_EXPORT NSString *const kFQPViewFromLeft; +FOUNDATION_EXPORT NSString *const kFQPViewFromRight; +FOUNDATION_EXPORT NSString *const kFQPIndex; + +#pragma mark - +#pragma mark Interrupt Reasons + +FOUNDATION_EXPORT NSString *const kFInterruptReasonServerKill; +FOUNDATION_EXPORT NSString *const kFInterruptReasonWaitingForOpen; +FOUNDATION_EXPORT NSString *const kFInterruptReasonRepoInterrupt; +FOUNDATION_EXPORT NSString *const kFInterruptReasonAuthExpired; + +#pragma mark - +#pragma mark Payload constants + +FOUNDATION_EXPORT NSString *const kPayloadPriority; +FOUNDATION_EXPORT NSString *const kPayloadValue; +FOUNDATION_EXPORT NSString *const kPayloadMetadataPrefix; + +#pragma mark - +#pragma mark ServerValue constants + +FOUNDATION_EXPORT NSString *const kServerValueSubKey; +FOUNDATION_EXPORT NSString *const kServerValuePriority; + +#pragma mark - +#pragma mark .info/ constants + +FOUNDATION_EXPORT NSString *const kDotInfoPrefix; +FOUNDATION_EXPORT NSString *const kDotInfoConnected; +FOUNDATION_EXPORT NSString *const kDotInfoServerTimeOffset; + +#pragma mark - +#pragma mark ObjectiveC to JavaScript type constants + +FOUNDATION_EXPORT NSString *const kJavaScriptObject; +FOUNDATION_EXPORT NSString *const kJavaScriptString; +FOUNDATION_EXPORT NSString *const kJavaScriptBoolean; +FOUNDATION_EXPORT NSString *const kJavaScriptNumber; +FOUNDATION_EXPORT NSString *const kJavaScriptNull; +FOUNDATION_EXPORT NSString *const kJavaScriptTrue; +FOUNDATION_EXPORT NSString *const kJavaScriptFalse; + +#pragma mark - +#pragma mark Error handling constants + +FOUNDATION_EXPORT NSString *const kFErrorDomain; +FOUNDATION_EXPORT NSUInteger const kFAuthError; +FOUNDATION_EXPORT NSString *const kFErrorWriteCanceled; + +#pragma mark - +#pragma mark Validation Constants + +FOUNDATION_EXPORT NSUInteger const kFirebaseMaxObjectDepth; +FOUNDATION_EXPORT const unsigned int kFirebaseMaxLeafSize; + +#pragma mark - +#pragma mark Transaction Constants + +FOUNDATION_EXPORT NSUInteger const kFTransactionMaxRetries; +FOUNDATION_EXPORT NSString *const kFTransactionTooManyRetries; +FOUNDATION_EXPORT NSString *const kFTransactionNoData; +FOUNDATION_EXPORT NSString *const kFTransactionSet; +FOUNDATION_EXPORT NSString *const kFTransactionDisconnect; + +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.m new file mode 100644 index 0000000..e492ba1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Constants/FConstants.m @@ -0,0 +1,183 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FConstants.h" + +#pragma mark - +#pragma mark Wire Protocol Envelope Constants + +NSString *const kFWPRequestType = @"t"; +NSString *const kFWPRequestTypeData = @"d"; +NSString *const kFWPRequestDataPayload = @"d"; +NSString *const kFWPRequestNumber = @"r"; +NSString *const kFWPRequestPayloadBody = @"b"; +NSString *const kFWPRequestError = @"error"; +NSString *const kFWPRequestAction = @"a"; +NSString *const kFWPResponseForRNData = @"b"; +NSString *const kFWPResponseForActionStatus = @"s"; +NSString *const kFWPResponseForActionStatusOk = @"ok"; +NSString *const kFWPResponseForActionStatusDataStale = @"datastale"; +NSString *const kFWPResponseForActionData = @"d"; +NSString *const kFWPResponseDataWarnings = @"w"; +NSString *const kFWPAsyncServerAction = @"a"; +NSString *const kFWPAsyncServerPayloadBody = @"b"; +NSString *const kFWPAsyncServerDataUpdate = @"d"; +NSString *const kFWPAsyncServerDataMerge = @"m"; +NSString *const kFWPAsyncServerDataRangeMerge = @"rm"; +NSString *const kFWPAsyncServerAuthRevoked = @"ac"; +NSString *const kFWPASyncServerListenCancelled = @"c"; +NSString *const kFWPAsyncServerSecurityDebug = @"sd"; +NSString *const kFWPAsyncServerDataUpdateBodyPath = @"p"; // {“a”: “d”, “b”: {“p”: “/”, “d”: “”}} +NSString *const kFWPAsyncServerDataUpdateBodyData = @"d"; +NSString *const kFWPAsyncServerDataUpdateStartPath = @"s"; +NSString *const kFWPAsyncServerDataUpdateEndPath = @"e"; +NSString *const kFWPAsyncServerDataUpdateRangeMerge = @"m"; +NSString *const kFWPAsyncServerDataUpdateBodyTag = @"t"; +NSString *const kFWPAsyncServerDataQueries = @"q"; + +NSString *const kFWPAsyncServerEnvelopeType = @"t"; +NSString *const kFWPAsyncServerEnvelopeData = @"d"; +NSString *const kFWPAsyncServerControlMessage = @"c"; +NSString *const kFWPAsyncServerControlMessageType = @"t"; +NSString *const kFWPAsyncServerControlMessageData = @"d"; +NSString *const kFWPAsyncServerDataMessage = @"d"; + +NSString *const kFWPAsyncServerHello = @"h"; +NSString *const kFWPAsyncServerHelloTimestamp = @"ts"; +NSString *const kFWPAsyncServerHelloVersion = @"v"; +NSString *const kFWPAsyncServerHelloConnectedHost = @"h"; +NSString *const kFWPAsyncServerHelloSession = @"s"; + +NSString *const kFWPAsyncServerControlMessageShutdown = @"s"; +NSString *const kFWPAsyncServerControlMessageReset = @"r"; + +#pragma mark - +#pragma mark Wire Protocol Payload Constants + +NSString *const kFWPRequestActionPut = @"p"; +NSString *const kFWPRequestActionMerge = @"m"; +NSString *const kFWPRequestActionListen = @"l"; // {"t": "d", "d": {"r": 1, "a": "l", "b": { "p": "/" } } } +NSString *const kFWPRequestActionUnlisten = @"u"; +NSString *const kFWPRequestActionStats = @"s"; +NSString *const kFWPRequestActionTaggedListen = @"q"; +NSString *const kFWPRequestActionTaggedUnlisten = @"n"; +NSString *const kFWPRequestActionDisconnectPut = @"o"; +NSString *const kFWPRequestActionDisconnectMerge = @"om"; +NSString *const kFWPRequestActionDisconnectCancel = @"oc"; +NSString *const kFWPRequestActionAuth = @"auth"; +NSString *const kFWPRequestActionUnauth = @"unauth"; +NSString *const kFWPRequestCredential = @"cred"; +NSString *const kFWPRequestPath = @"p"; +NSString *const kFWPRequestCounters = @"c"; +NSString *const kFWPRequestQueries = @"q"; +NSString *const kFWPRequestTag = @"t"; +NSString *const kFWPRequestData = @"d"; +NSString *const kFWPRequestHash = @"h"; +NSString *const kFWPRequestCompoundHash = @"ch"; +NSString *const kFWPRequestCompoundHashPaths = @"ps"; +NSString *const kFWPRequestCompoundHashHashes = @"hs"; +NSString *const kFWPRequestStatus = @"s"; + +#pragma mark - +#pragma mark Websock Transport Constants + +NSString *const kWireProtocolVersionParam = @"v"; +NSString *const kWebsocketProtocolVersion = @"5"; +NSString *const kWebsocketServerKillPacket = @"kill"; +const int kWebsocketMaxFrameSize = 16384; +NSUInteger const kWebsocketKeepaliveInterval = 45; +NSUInteger const kWebsocketConnectTimeout = 30; + +float const kPersistentConnReconnectMinDelay = 1.0; +float const kPersistentConnReconnectMaxDelay = 30.0; +float const kPersistentConnReconnectMultiplier = 1.3f; +float const kPersistentConnSuccessfulConnectionEstablishedDelay = 30.0; + +#pragma mark - +#pragma mark Query constants + +NSString *const kQueryDefault = @"default"; +NSString *const kQueryDefaultObject = @"{}"; +NSString *const kViewManagerDictConstView = @"view"; +NSString *const kFQPIndexStartValue = @"sp"; +NSString *const kFQPIndexStartName = @"sn"; +NSString *const kFQPIndexEndValue = @"ep"; +NSString *const kFQPIndexEndName = @"en"; +NSString *const kFQPLimit = @"l"; +NSString *const kFQPViewFrom = @"vf"; +NSString *const kFQPViewFromLeft = @"l"; +NSString *const kFQPViewFromRight = @"r"; +NSString *const kFQPIndex = @"i"; + +#pragma mark - +#pragma mark Interrupt Reasons + +NSString *const kFInterruptReasonServerKill = @"server_kill"; +NSString *const kFInterruptReasonWaitingForOpen = @"waiting_for_open"; +NSString *const kFInterruptReasonRepoInterrupt = @"repo_interrupt"; + +#pragma mark - +#pragma mark Payload constants + +NSString *const kPayloadPriority = @".priority"; +NSString *const kPayloadValue = @".value"; +NSString *const kPayloadMetadataPrefix = @"."; + +#pragma mark - +#pragma mark ServerValue constants + +NSString *const kServerValueSubKey = @".sv"; +NSString *const kServerValuePriority = @"timestamp"; + +#pragma mark - +#pragma mark .info/ constants + +NSString *const kDotInfoPrefix = @".info"; +NSString *const kDotInfoConnected = @"connected"; +NSString *const kDotInfoServerTimeOffset = @"serverTimeOffset"; + +#pragma mark - +#pragma mark ObjectiveC to JavaScript type constants + +NSString *const kJavaScriptObject = @"object"; +NSString *const kJavaScriptString = @"string"; +NSString *const kJavaScriptBoolean = @"boolean"; +NSString *const kJavaScriptNumber = @"number"; +NSString *const kJavaScriptNull = @"null"; +NSString *const kJavaScriptTrue = @"true"; +NSString *const kJavaScriptFalse = @"false"; + +#pragma mark - +#pragma mark Error handling constants + +NSString *const kFErrorDomain = @"com.firebase"; +NSUInteger const kFAuthError = 1; +NSString *const kFErrorWriteCanceled = @"write_canceled"; + +#pragma mark - +#pragma mark Validation Constants + +NSUInteger const kFirebaseMaxObjectDepth = 1000; +const unsigned int kFirebaseMaxLeafSize = 1024 * 1024 * 10; // 10 MB + +#pragma mark - +#pragma mark Transaction Constants + +NSUInteger const kFTransactionMaxRetries = 25; +NSString *const kFTransactionTooManyRetries = @"maxretry"; +NSString *const kFTransactionNoData = @"nodata"; +NSString *const kFTransactionSet = @"set"; +NSString *const kFTransactionDisconnect = @"disconnect"; diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.h new file mode 100644 index 0000000..cd5240e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FNode.h" + + +@interface FCompoundHashBuilder : NSObject + +- (FPath *)currentPath; + +@end + + +typedef BOOL (^FCompoundHashSplitStrategy) (FCompoundHashBuilder *builder); + + +@interface FCompoundHash : NSObject + +@property (nonatomic, strong, readonly) NSArray *posts; +@property (nonatomic, strong, readonly) NSArray *hashes; + ++ (FCompoundHash *)fromNode:(id)node; ++ (FCompoundHash *)fromNode:(id)node splitStrategy:(FCompoundHashSplitStrategy)strategy; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.m new file mode 100644 index 0000000..b4f72cd --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FCompoundHash.m @@ -0,0 +1,236 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FCompoundHash.h" +#import "FLeafNode.h" +#import "FStringUtilities.h" +#import "FSnapshotUtilities.h" +#import "FChildrenNode.h" + +@interface FCompoundHashBuilder () + +@property (nonatomic, strong) FCompoundHashSplitStrategy splitStrategy; + +@property (nonatomic, strong) NSMutableArray *currentPaths; +@property (nonatomic, strong) NSMutableArray *currentHashes; + +@end + +@implementation FCompoundHashBuilder { + + // NOTE: We use the existence of this to know if we've started building a range (i.e. encountered a leaf node). + NSMutableString *optHashValueBuilder; + + // The current path as a stack. This is used in combination with currentPathDepth to simultaneously store the + // last leaf node path. The depth is changed when descending and ascending, at the same time the current key + // is set for the current depth. Because the keys are left unchanged for ascending the path will also contain + // the path of the last visited leaf node (using lastLeafDepth elements) + NSMutableArray *currentPath; + NSInteger lastLeafDepth; + NSInteger currentPathDepth; + + BOOL needsComma; +} + +- (instancetype)initWithSplitStrategy:(FCompoundHashSplitStrategy)strategy { + self = [super init]; + if (self != nil) { + self->_splitStrategy = strategy; + self->optHashValueBuilder = nil; + self->currentPath = [NSMutableArray array]; + self->lastLeafDepth = -1; + self->currentPathDepth = 0; + self->needsComma = YES; + self->_currentPaths = [NSMutableArray array]; + self->_currentHashes = [NSMutableArray array]; + } + return self; +} + +- (BOOL)isBuildingRange { + return self->optHashValueBuilder != nil; +} + +- (NSUInteger)currentHashLength { + return self->optHashValueBuilder.length; +} + +- (FPath *)currentPath { + return [self currentPathWithDepth:self->currentPathDepth]; +} + +- (FPath *)currentPathWithDepth:(NSInteger)depth { + NSArray *pieces = [self->currentPath subarrayWithRange:NSMakeRange(0, depth)]; + return [[FPath alloc] initWithPieces:pieces andPieceNum:0]; +} + +- (void)enumerateCurrentPathToDepth:(NSInteger)depth withBlock:(void (^) (NSString *key))block { + for (NSInteger i = 0; i < depth; i++) { + block(self->currentPath[i]); + } +} + +- (void)appendKey:(NSString *)key toString:(NSMutableString *)string { + [FSnapshotUtilities appendHashV2RepresentationForString:key toString:string]; +} + +- (void)ensureRange { + if (![self isBuildingRange]) { + optHashValueBuilder = [NSMutableString string]; + [optHashValueBuilder appendString:@"("]; + [self enumerateCurrentPathToDepth:self->currentPathDepth withBlock:^(NSString *key) { + [self appendKey:key toString:self->optHashValueBuilder]; + [self->optHashValueBuilder appendString:@":("]; + }]; + self->needsComma = NO; + } +} + +- (void)processLeaf:(FLeafNode *)leafNode { + [self ensureRange]; + + self->lastLeafDepth = self->currentPathDepth; + [FSnapshotUtilities appendHashRepresentationForLeafNode:leafNode + toString:self->optHashValueBuilder + hashVersion:FDataHashVersionV2]; + self->needsComma = YES; + if (self.splitStrategy(self)) { + [self endRange]; + } +} + +- (void)startChild:(NSString *)key { + [self ensureRange]; + + if (self->needsComma) { + [self->optHashValueBuilder appendString:@","]; + } + [self appendKey:key toString:self->optHashValueBuilder]; + [self->optHashValueBuilder appendString:@":("]; + if (self->currentPathDepth == currentPath.count) { + [self->currentPath addObject:key]; + } else { + self->currentPath[self->currentPathDepth] = key; + } + self->currentPathDepth++; + self->needsComma = NO; +} + +- (void)endChild { + self->currentPathDepth--; + if ([self isBuildingRange]) { + [self->optHashValueBuilder appendString:@")"]; + } + self->needsComma = YES; +} + +- (void)finishHashing { + NSAssert(self->currentPathDepth == 0, @"Can't finish hashing in the middle of processing a child"); + if ([self isBuildingRange] ) { + [self endRange]; + } + + // Always close with the empty hash for the remaining range to allow simple appending + [self.currentHashes addObject:@""]; +} + +- (void)endRange { + NSAssert([self isBuildingRange], @"Can't end range without starting a range!"); + // Add closing parenthesis for current depth + for (NSUInteger i = 0; i < currentPathDepth; i++) { + [self->optHashValueBuilder appendString:@")"]; + } + [self->optHashValueBuilder appendString:@")"]; + + FPath *lastLeafPath = [self currentPathWithDepth:self->lastLeafDepth]; + NSString *hash = [FStringUtilities base64EncodedSha1:self->optHashValueBuilder]; + [self.currentHashes addObject:hash]; + [self.currentPaths addObject:lastLeafPath]; + + self->optHashValueBuilder = nil; +} + +@end + + +@interface FCompoundHash () + +@property (nonatomic, strong, readwrite) NSArray *posts; +@property (nonatomic, strong, readwrite) NSArray *hashes; + +@end + +@implementation FCompoundHash + +- (id)initWithPosts:(NSArray *)posts hashes:(NSArray *)hashes { + self = [super init]; + if (self != nil) { + if (posts.count != hashes.count - 1) { + [NSException raise:NSInvalidArgumentException format:@"Number of posts need to be n-1 for n hashes in FCompoundHash"]; + } + self.posts = posts; + self.hashes = hashes; + } + return self; +} + ++ (FCompoundHashSplitStrategy)simpleSizeSplitStrategyForNode:(id)node { + NSUInteger estimatedSize = [FSnapshotUtilities estimateSerializedNodeSize:node]; + + // Splits for + // 1k -> 512 (2 parts) + // 5k -> 715 (7 parts) + // 100k -> 3.2k (32 parts) + // 500k -> 7k (71 parts) + // 5M -> 23k (228 parts) + NSUInteger splitThreshold = MAX(512, (NSUInteger)sqrt(estimatedSize * 100)); + + return ^BOOL(FCompoundHashBuilder *builder) { + // Never split on priorities + return [builder currentHashLength] > splitThreshold && ![[[builder currentPath] getBack] isEqualToString:@".priority"]; + }; +} + ++ (FCompoundHash *)fromNode:(id)node { + return [FCompoundHash fromNode:node splitStrategy:[FCompoundHash simpleSizeSplitStrategyForNode:node]]; +} + ++ (FCompoundHash *)fromNode:(id)node splitStrategy:(FCompoundHashSplitStrategy)strategy { + if ([node isEmpty]) { + return [[FCompoundHash alloc] initWithPosts:@[] hashes:@[@""]]; + } else { + FCompoundHashBuilder *builder = [[FCompoundHashBuilder alloc] initWithSplitStrategy:strategy]; + [FCompoundHash processNode:node builder:builder]; + [builder finishHashing]; + return [[FCompoundHash alloc] initWithPosts:builder.currentPaths hashes:builder.currentHashes]; + } +} + ++ (void)processNode:(id)node builder:(FCompoundHashBuilder *)builder { + if ([node isLeafNode]) { + [builder processLeaf:node]; + } else { + NSAssert(![node isEmpty], @"Can't calculate hash on empty node!"); + FChildrenNode *childrenNode = (FChildrenNode *)node; + [childrenNode enumerateChildrenAndPriorityUsingBlock:^(NSString *key, id node, BOOL *stop) { + [builder startChild:key]; + [self processNode:node builder:builder]; + [builder endChild]; + }]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.h new file mode 100644 index 0000000..7a41754 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTypedefs_Private.h" + +@class FQuerySpec; +@protocol FSyncTreeHash; + +typedef NSArray* (^fbt_startListeningBlock)(FQuerySpec *query, + NSNumber *tagId, + id hash, + fbt_nsarray_nsstring onComplete); +typedef void (^fbt_stopListeningBlock)(FQuerySpec *query, NSNumber *tagId); + +@interface FListenProvider : NSObject + +@property (nonatomic, copy) fbt_startListeningBlock startListening; +@property (nonatomic, copy) fbt_stopListeningBlock stopListening; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.m new file mode 100644 index 0000000..7a49609 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FListenProvider.m @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FListenProvider.h" +#import "FIRDatabaseQuery.h" + + +@implementation FListenProvider + +@synthesize startListening; +@synthesize stopListening; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.h new file mode 100644 index 0000000..412c874 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.h @@ -0,0 +1,78 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FConnection.h" +#import "FRepoInfo.h" +#import "FTypedefs.h" +#import "FTypedefs_Private.h" + +@protocol FPersistentConnectionDelegate; +@protocol FSyncTreeHash; +@class FQuerySpec; +@class FIRDatabaseConfig; + +@interface FPersistentConnection : NSObject + +@property (nonatomic, weak) id delegate; +@property (nonatomic) BOOL pauseWrites; + +- (id)initWithRepoInfo:(FRepoInfo *)repoInfo + dispatchQueue:(dispatch_queue_t)queue + config:(FIRDatabaseConfig *)config; + +- (void)open; + +- (void) putData:(id)data forPath:(NSString *)pathString withHash:(NSString *)hash withCallback:(fbt_void_nsstring_nsstring)onComplete; +- (void) mergeData:(id)data forPath:(NSString *)pathString withCallback:(fbt_void_nsstring_nsstring)onComplete; + +- (void) listen:(FQuerySpec *)query + tagId:(NSNumber *)tagId + hash:(id)hash + onComplete:(fbt_void_nsstring)onComplete; + +- (void) unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId; +- (void) refreshAuthToken:(NSString *)token; +- (void) onDisconnectPutData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback; +- (void) onDisconnectMergeData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback; +- (void) onDisconnectCancelPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback; +- (void) ackPuts; +- (void) purgeOutstandingWrites; + +- (void) interruptForReason:(NSString *)reason; +- (void) resumeForReason:(NSString *)reason; +- (BOOL) isInterruptedForReason:(NSString *)reason; + +// FConnection delegate methods +- (void)onReady:(FConnection *)fconnection atTime:(NSNumber *)timestamp sessionID:(NSString *)sessionID; +- (void)onDataMessage:(FConnection *)fconnection withMessage:(NSDictionary *)message; +- (void)onDisconnect:(FConnection *)fconnection withReason:(FDisconnectReason)reason; +- (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason; + +// Testing methods +- (NSDictionary *) dumpListens; + +@end + +@protocol FPersistentConnectionDelegate + +- (void)onDataUpdate:(FPersistentConnection *)fpconnection forPath:(NSString *)pathString message:(id)message isMerge:(BOOL)isMerge tagId:(NSNumber *)tagId; +- (void)onRangeMerge:(NSArray *)ranges forPath:(NSString *)path tagId:(NSNumber *)tag; +- (void)onConnect:(FPersistentConnection *)fpconnection; +- (void)onDisconnect:(FPersistentConnection *)fpconnection; +- (void)onServerInfoUpdate:(FPersistentConnection *)fpconnection updates:(NSDictionary *)updates; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.m new file mode 100644 index 0000000..f341bb1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FPersistentConnection.m @@ -0,0 +1,952 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import + +#import +#import +#import +#import +#import "FIRDatabaseReference.h" +#import "FPersistentConnection.h" +#import "FConstants.h" +#import "FAtomicNumber.h" +#import "FQueryParams.h" +#import "FTupleOnDisconnect.h" +#import "FTupleCallbackStatus.h" +#import "FQuerySpec.h" +#import "FIndex.h" +#import "FIRDatabaseConfig.h" +#import "FIRDatabaseConfig_Private.h" +#import "FSnapshotUtilities.h" +#import "FRangeMerge.h" +#import "FCompoundHash.h" +#import "FSyncTree.h" +#import "FIRRetryHelper.h" +#import "FAuthTokenProvider.h" +#import "FUtilities.h" + +@interface FOutstandingQuery : NSObject + +@property (nonatomic, strong) FQuerySpec* query; +@property (nonatomic, strong) NSNumber *tagId; +@property (nonatomic, strong) id syncTreeHash; +@property (nonatomic, copy) fbt_void_nsstring onComplete; + +@end + +@implementation FOutstandingQuery + +@end + + +@interface FOutstandingPut : NSObject + +@property (nonatomic, strong) NSString *action; +@property (nonatomic, strong) NSDictionary *request; +@property (nonatomic, copy) fbt_void_nsstring_nsstring onCompleteBlock; +@property (nonatomic) BOOL sent; + +@end + +@implementation FOutstandingPut + +@end + + +typedef enum { + ConnectionStateDisconnected, + ConnectionStateGettingToken, + ConnectionStateConnecting, + ConnectionStateAuthenticating, + ConnectionStateConnected +} ConnectionState; + +@interface FPersistentConnection () { + ConnectionState connectionState; + BOOL firstConnection; + NSTimeInterval reconnectDelay; + NSTimeInterval lastConnectionAttemptTime; + NSTimeInterval lastConnectionEstablishedTime; + SCNetworkReachabilityRef reachability; +} + +- (int) getNextRequestNumber; +- (void) onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body; +- (void) handleTimestamp:(NSNumber *)timestamp; +- (void) sendOnDisconnectAction:(NSString *)action forPath:(NSString *)pathString withData:(id)data andCallback:(fbt_void_nsstring_nsstring)callback; + +@property (nonatomic, strong) FConnection* realtime; +@property (nonatomic, strong) NSMutableDictionary* listens; +@property (nonatomic, strong) NSMutableDictionary* outstandingPuts; +@property (nonatomic, strong) NSMutableArray* onDisconnectQueue; +@property (nonatomic, strong) FRepoInfo* repoInfo; +@property (nonatomic, strong) FAtomicNumber* putCounter; +@property (nonatomic, strong) FAtomicNumber* requestNumber; +@property (nonatomic, strong) NSMutableDictionary* requestCBHash; +@property (nonatomic, strong) FIRDatabaseConfig *config; +@property (nonatomic) NSUInteger unackedListensCount; +@property (nonatomic, strong) NSMutableArray *putsToAck; +@property (nonatomic, strong) dispatch_queue_t dispatchQueue; +@property (nonatomic, strong) NSString* lastSessionID; +@property (nonatomic, strong) NSMutableSet *interruptReasons; +@property (nonatomic, strong) FIRRetryHelper *retryHelper; +@property (nonatomic, strong) id authTokenProvider; +@property (nonatomic, strong) NSString *authToken; +@property (nonatomic) BOOL forceAuthTokenRefresh; +@property (nonatomic) NSUInteger currentFetchTokenAttempt; + +@end + + +@implementation FPersistentConnection + +- (id)initWithRepoInfo:(FRepoInfo *)repoInfo dispatchQueue:(dispatch_queue_t)dispatchQueue config:(FIRDatabaseConfig *)config { + self = [super init]; + if (self) { + self->_config = config; + self->_repoInfo = repoInfo; + self->_dispatchQueue = dispatchQueue; + self->_authTokenProvider = config.authTokenProvider; + NSAssert(self->_authTokenProvider != nil, @"Expected auth token provider"); + self.interruptReasons = [NSMutableSet set]; + + self.listens = [[NSMutableDictionary alloc] init]; + self.outstandingPuts = [[NSMutableDictionary alloc] init]; + self.onDisconnectQueue = [[NSMutableArray alloc] init]; + self.putCounter = [[FAtomicNumber alloc] init]; + self.requestNumber = [[FAtomicNumber alloc] init]; + self.requestCBHash = [[NSMutableDictionary alloc] init]; + self.unackedListensCount = 0; + self.putsToAck = [NSMutableArray array]; + connectionState = ConnectionStateDisconnected; + firstConnection = YES; + reconnectDelay = kPersistentConnReconnectMinDelay; + + self->_retryHelper = [[FIRRetryHelper alloc] initWithDispatchQueue:dispatchQueue + minRetryDelayAfterFailure:kPersistentConnReconnectMinDelay + maxRetryDelay:kPersistentConnReconnectMaxDelay + retryExponent:kPersistentConnReconnectMultiplier + jitterFactor:0.7]; + + [self setupNotifications]; + // Make sure we don't actually connect until open is called + [self interruptForReason:kFInterruptReasonWaitingForOpen]; + } + // nb: The reason establishConnection isn't called here like the JS version is because + // callers need to set the delegate first. The ctor can be modified to accept the delegate + // but that deviates from normal ios conventions. After the delegate has been set, the caller + // is responsible for calling establishConnection: + return self; +} + +- (void) dealloc { + if (reachability) { + // Unschedule the notifications + SCNetworkReachabilitySetDispatchQueue(reachability, NULL); + CFRelease(reachability); + } +} + +#pragma mark - +#pragma mark Public methods + +- (void) open { + [self resumeForReason:kFInterruptReasonWaitingForOpen]; +} + +/** +* Note that the listens dictionary has a type of Map[String (pathString), Map[FQueryParams, FOutstandingQuery]] +* +* This means, for each path we care about, there are sets of queryParams that correspond to an FOutstandingQuery object. +* There can be multiple sets at a path since we overlap listens for a short time while adding or removing a query from a +* location in the tree. +*/ +- (void) listen:(FQuerySpec *)query + tagId:(NSNumber *)tagId + hash:(id)hash + onComplete:(fbt_void_nsstring)onComplete { + FFLog(@"I-RDB034001", @"Listen called for %@", query); + + NSAssert(self.listens[query] == nil, @"listen() called twice for the same query"); + NSAssert(query.isDefault || !query.loadsAllData, @"listen called for non-default but complete query"); + FOutstandingQuery* outstanding = [[FOutstandingQuery alloc] init]; + outstanding.query = query; + outstanding.tagId = tagId; + outstanding.syncTreeHash = hash; + outstanding.onComplete = onComplete; + [self.listens setObject:outstanding forKey:query]; + if ([self connected]) { + [self sendListen:outstanding]; + } +} + +- (void) putData:(id)data forPath:(NSString *)pathString withHash:(NSString *)hash withCallback:(fbt_void_nsstring_nsstring)onComplete { + [self putInternal:data forAction:kFWPRequestActionPut forPath:pathString withHash:hash withCallback:onComplete]; +} + +- (void) mergeData:(id)data forPath:(NSString *)pathString withCallback:(fbt_void_nsstring_nsstring)onComplete { + [self putInternal:data forAction:kFWPRequestActionMerge forPath:pathString withHash:nil withCallback:onComplete]; +} + +- (void) onDisconnectPutData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback { + if ([self canSendWrites]) { + [self sendOnDisconnectAction:kFWPRequestActionDisconnectPut forPath:[path description] withData:data andCallback:callback]; + } else { + FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init]; + tuple.pathString = [path description]; + tuple.action = kFWPRequestActionDisconnectPut; + tuple.data = data; + tuple.onComplete = callback; + [self.onDisconnectQueue addObject:tuple]; + } +} + +- (void) onDisconnectMergeData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback { + if ([self canSendWrites]) { + [self sendOnDisconnectAction:kFWPRequestActionDisconnectMerge forPath:[path description] withData:data andCallback:callback]; + } else { + FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init]; + tuple.pathString = [path description]; + tuple.action = kFWPRequestActionDisconnectMerge; + tuple.data = data; + tuple.onComplete = callback; + [self.onDisconnectQueue addObject:tuple]; + } +} + +- (void) onDisconnectCancelPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback { + if ([self canSendWrites]) { + [self sendOnDisconnectAction:kFWPRequestActionDisconnectCancel forPath:[path description] withData:[NSNull null] andCallback:callback]; + } else { + FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init]; + tuple.pathString = [path description]; + tuple.action = kFWPRequestActionDisconnectCancel; + tuple.data = [NSNull null]; + tuple.onComplete = callback; + [self.onDisconnectQueue addObject:tuple]; + } +} + +- (void) unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId { + FPath *path = query.path; + FFLog(@"I-RDB034002", @"Unlistening for %@", query); + + NSArray *outstanding = [self removeListen:query]; + if (outstanding.count > 0 && [self connected]) { + [self sendUnlisten:path queryParams:query.params tagId:tagId]; + } +} + +- (void) refreshAuthToken:(NSString *)token { + self.authToken = token; + if ([self connected]) { + if (token != nil) { + [self sendAuthAndRestoreStateAfterComplete:NO]; + } else { + [self sendUnauth]; + } + } +} + +#pragma mark - +#pragma mark Connection status + +- (BOOL)connected { + return self->connectionState == ConnectionStateAuthenticating || self->connectionState == ConnectionStateConnected; +} + +- (BOOL)canSendWrites { + return self->connectionState == ConnectionStateConnected; +} + +#pragma mark - +#pragma mark FConnection delegate methods + +- (void)onReady:(FConnection *)fconnection atTime:(NSNumber *)timestamp sessionID:(NSString *)sessionID { + FFLog(@"I-RDB034003", @"On ready"); + lastConnectionEstablishedTime = [[NSDate date] timeIntervalSince1970]; + [self handleTimestamp:timestamp]; + + if (firstConnection) { + [self sendConnectStats]; + } + + [self restoreAuth]; + firstConnection = NO; + self.lastSessionID = sessionID; + dispatch_async(self.dispatchQueue, ^{ + [self.delegate onConnect:self]; + }); +} + +- (void)onDataMessage:(FConnection *)fconnection withMessage:(NSDictionary *)message { + if (message[kFWPRequestNumber] != nil) { + // this is a response to a request we sent + NSNumber* rn = [NSNumber numberWithInt:[[message objectForKey:kFWPRequestNumber] intValue]]; + if ([self.requestCBHash objectForKey:rn]) { + void (^callback)(NSDictionary*) = [self.requestCBHash objectForKey:rn]; + [self.requestCBHash removeObjectForKey:rn]; + + if (callback) { + //dispatch_async(self.dispatchQueue, ^{ + callback([message objectForKey:kFWPResponseForRNData]); + //}); + } + } + } else if (message[kFWPRequestError] != nil) { + NSString* error = [message objectForKey:kFWPRequestError]; + @throw [[NSException alloc] initWithName:@"FirebaseDatabaseServerError" reason:error userInfo:nil]; + } else if (message[kFWPAsyncServerAction] != nil) { + // this is a server push of some sort + NSString* action = [message objectForKey:kFWPAsyncServerAction]; + NSDictionary* body = [message objectForKey:kFWPAsyncServerPayloadBody]; + [self onDataPushWithAction:action andBody:body]; + } +} + +- (void)onDisconnect:(FConnection *)fconnection withReason:(FDisconnectReason)reason { + FFLog(@"I-RDB034004", @"Got on disconnect due to %s", (reason == DISCONNECT_REASON_SERVER_RESET) ? "server_reset" : "other"); + connectionState = ConnectionStateDisconnected; + // Drop the realtime connection + self.realtime = nil; + [self cancelSentTransactions]; + [self.requestCBHash removeAllObjects]; + self.unackedListensCount = 0; + if ([self shouldReconnect]) { + NSTimeInterval timeSinceLastConnectSucceeded = [[NSDate date] timeIntervalSince1970] - lastConnectionEstablishedTime; + BOOL lastConnectionWasSuccessful; + if (lastConnectionEstablishedTime > 0) { + lastConnectionWasSuccessful = timeSinceLastConnectSucceeded > kPersistentConnSuccessfulConnectionEstablishedDelay; + } else { + lastConnectionWasSuccessful = NO; + } + + if (reason == DISCONNECT_REASON_SERVER_RESET || lastConnectionWasSuccessful) { + [self.retryHelper signalSuccess]; + } + [self tryScheduleReconnect]; + } + lastConnectionEstablishedTime = 0; + [self.delegate onDisconnect:self]; +} + +- (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason { + FFWarn(@"I-RDB034005", @"Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: %@", reason); + [self interruptForReason:kFInterruptReasonServerKill]; +} + +#pragma mark - +#pragma mark Connection handling methods + +- (void) interruptForReason:(NSString *)reason { + FFLog(@"I-RDB034006", @"Connection interrupted for: %@", reason); + + [self.interruptReasons addObject:reason]; + if (self.realtime) { + // Will call onDisconnect and set the connection state to Disconnected + [self.realtime close]; + self.realtime = nil; + } else { + [self.retryHelper cancel]; + self->connectionState = ConnectionStateDisconnected; + } + // Reset timeouts + [self.retryHelper signalSuccess]; +} + +- (void) resumeForReason:(NSString *)reason { + FFLog(@"I-RDB034007", @"Connection no longer interrupted for: %@", reason); + [self.interruptReasons removeObject:reason]; + + if ([self shouldReconnect] && connectionState == ConnectionStateDisconnected) { + [self tryScheduleReconnect]; + } +} + +- (BOOL) shouldReconnect { + return self.interruptReasons.count == 0; +} + +- (BOOL) isInterruptedForReason:(NSString *)reason { + return [self.interruptReasons containsObject:reason]; +} + +#pragma mark - +#pragma mark Private methods + +- (void) tryScheduleReconnect { + if ([self shouldReconnect]) { + NSAssert(self->connectionState == ConnectionStateDisconnected, + @"Not in disconnected state: %d", self->connectionState); + BOOL forceRefresh = self.forceAuthTokenRefresh; + self.forceAuthTokenRefresh = NO; + FFLog(@"I-RDB034008", @"Scheduling connection attempt"); + [self.retryHelper retry:^{ + FFLog(@"I-RDB034009", @"Trying to fetch auth token"); + NSAssert(self->connectionState == ConnectionStateDisconnected, + @"Not in disconnected state: %d", self->connectionState); + self->connectionState = ConnectionStateGettingToken; + self.currentFetchTokenAttempt++; + NSUInteger thisFetchTokenAttempt = self.currentFetchTokenAttempt; + [self.authTokenProvider fetchTokenForcingRefresh:forceRefresh withCallback:^(NSString *token, NSError *error) { + if (thisFetchTokenAttempt == self.currentFetchTokenAttempt) { + if (error != nil) { + self->connectionState = ConnectionStateDisconnected; + FFLog(@"I-RDB034010", @"Error fetching token: %@", error); + [self tryScheduleReconnect]; + } else { + // Someone could have interrupted us while fetching the token, + // marking the connection as Disconnected + if (self->connectionState == ConnectionStateGettingToken) { + FFLog(@"I-RDB034011", @"Successfully fetched token, opening connection"); + [self openNetworkConnectionWithToken:token]; + } else { + NSAssert(self->connectionState == ConnectionStateDisconnected, + @"Expected connection state disconnected, but got %d", self->connectionState); + FFLog(@"I-RDB034012", @"Not opening connection after token refresh, because connection was set to disconnected."); + } + } + } else { + FFLog(@"I-RDB034013", @"Ignoring fetch token result, because this was not the latest attempt."); + } + }]; + }]; + + } +} + +- (void) openNetworkConnectionWithToken:(NSString *)token { + NSAssert(self->connectionState == ConnectionStateGettingToken, + @"Trying to open network connection while in wrong state: %d", self->connectionState); + self.authToken = token; + self->connectionState = ConnectionStateConnecting; + self.realtime = [[FConnection alloc] initWith:self.repoInfo + andDispatchQueue:self.dispatchQueue + lastSessionID:self.lastSessionID]; + self.realtime.delegate = self; + [self.realtime open]; +} + +static void reachabilityCallback(SCNetworkReachabilityRef ref, SCNetworkReachabilityFlags flags, void* info) { + if (flags & kSCNetworkReachabilityFlagsReachable) { + FFLog(@"I-RDB034014", @"Network became reachable. Trigger a connection attempt"); + FPersistentConnection* self = (__bridge FPersistentConnection *)info; + // Reset reconnect delay + [self.retryHelper signalSuccess]; + if (self->connectionState == ConnectionStateDisconnected) { + [self tryScheduleReconnect]; + } + } else { + FFLog(@"I-RDB034015", @"Network is not reachable"); + } +} + +- (void) enteringForeground { + dispatch_async(self.dispatchQueue, ^{ + // Reset reconnect delay + [self.retryHelper signalSuccess]; + if (self->connectionState == ConnectionStateDisconnected) { + [self tryScheduleReconnect]; + } + }); +} + +- (void) setupNotifications { + + NSString * const* foregroundConstant = (NSString * const *) dlsym(RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification"); + if (foregroundConstant) { + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(enteringForeground) + name:*foregroundConstant + object:nil]; + } + // An empty address is interpreted a generic internet access + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress); + SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL, NULL}; + if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback, &ctx)) { + SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue); + } else { + FFLog(@"I-RDB034016", @"Failed to set up network reachability monitoring"); + CFRelease(reachability); + reachability = NULL; + } +} + +- (void) sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete { + NSAssert([self connected], @"Must be connected to send auth"); + NSAssert(self.authToken != nil, @"Can't send auth if there is no credential"); + + NSDictionary* requestData = @{kFWPRequestCredential: self.authToken}; + [self sendAction:kFWPRequestActionAuth body:requestData sensitive:YES callback:^(NSDictionary *data) { + self->connectionState = ConnectionStateConnected; + NSString* status = [data objectForKey:kFWPResponseForActionStatus]; + id responseData = [data objectForKey:kFWPResponseForActionData]; + if (responseData == nil) { + responseData = @"error"; + } + + BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk]; + if (statusOk) { + if (restoreStateAfterComplete) { + [self restoreState]; + } + } else { + self.authToken = nil; + self.forceAuthTokenRefresh = YES; + if ([status isEqualToString:@"expired_token"]) { + FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)", status, responseData); + } else { + FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)", status, responseData); + } + [self.realtime close]; + } + }]; +} + +- (void) sendUnauth { + [self sendAction:kFWPRequestActionUnauth body:@{} sensitive:NO callback:nil]; +} + +- (void) onAuthRevokedWithStatus:(NSString *)status andReason:(NSString *)reason { + // This might be for an earlier token than we just recently sent. But since we need to close the connection anyways, + // we can set it to null here and we will refresh the token later on reconnect + if ([status isEqualToString:@"expired_token"]) { + FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason); + } else { + FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason); + } + self.authToken = nil; + self.forceAuthTokenRefresh = YES; + // Try reconnecting on auth revocation + [self.realtime close]; +} + +- (void) onListenRevoked:(FPath *)path { + NSArray *queries = [self removeAllListensAtPath:path]; + for (FOutstandingQuery* query in queries) { + query.onComplete(@"permission_denied"); + } +} + +- (void) sendOnDisconnectAction:(NSString *)action forPath:(NSString *)pathString withData:(id)data andCallback:(fbt_void_nsstring_nsstring)callback { + + NSDictionary* request = @{kFWPRequestPath: pathString, kFWPRequestData: data}; + FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request); + + [self sendAction:action + body:request + sensitive:NO + callback:^(NSDictionary *data) { + NSString* status = [data objectForKey:kFWPResponseForActionStatus]; + NSString* errorReason = [data objectForKey:kFWPResponseForActionData]; + callback(status, errorReason); + }]; +} + +- (void) sendPut:(NSNumber *) index { + NSAssert([self canSendWrites], @"sendPut called when not able to send writes"); + FOutstandingPut* put = self.outstandingPuts[index]; + assert(put != nil); + fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock; + + // Do not async this block; copying the block insinde sendAction: doesn't happen in time (or something) so coredumps + put.sent = YES; + [self sendAction:put.action + body:put.request + sensitive:NO + callback:^(NSDictionary* data) { + + FOutstandingPut *currentPut = self.outstandingPuts[index]; + if (currentPut == put) { + [self.outstandingPuts removeObjectForKey:index]; + + if (onComplete != nil) { + NSString *status = [data objectForKey:kFWPResponseForActionStatus]; + NSString *errorReason = [data objectForKey:kFWPResponseForActionData]; + if (self.unackedListensCount == 0) { + onComplete(status, errorReason); + } else { + FTupleCallbackStatus *putToAck = [[FTupleCallbackStatus alloc] init]; + putToAck.block = onComplete; + putToAck.status = status; + putToAck.errorReason = errorReason; + [self.putsToAck addObject:putToAck]; + } + } + } else { + FFLog(@"I-RDB034022", @"Ignoring on complete for put %@ because it was already removed", index); + } + }]; +} + +- (void) sendUnlisten:(FPath *)path queryParams:(FQueryParams *)queryParams tagId:(NSNumber *)tagId { + FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams); + + NSMutableDictionary* request = [NSMutableDictionary dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil]; + if (tagId != nil) { + [request setObject:queryParams.wireProtocolParams forKey:kFWPRequestQueries]; + [request setObject:tagId forKey:kFWPRequestTag]; + } + + [self sendAction:kFWPRequestActionTaggedUnlisten + body:request + sensitive:NO + callback:nil]; +} + +- (void) putInternal:(id)data forAction:(NSString *)action forPath:(NSString *)pathString withHash:(NSString *)hash withCallback:(fbt_void_nsstring_nsstring)onComplete { + + NSMutableDictionary *request = [NSMutableDictionary dictionaryWithObjectsAndKeys: + pathString, kFWPRequestPath, + data, kFWPRequestData, nil]; + if(hash) { + [request setObject:hash forKey:kFWPRequestHash]; + } + + FOutstandingPut *put = [[FOutstandingPut alloc] init]; + put.action = action; + put.request = request; + put.onCompleteBlock = onComplete; + put.sent = NO; + + NSNumber* index = [self.putCounter getAndIncrement]; + self.outstandingPuts[index] = put; + + if ([self canSendWrites]) { + FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index); + [self sendPut:index]; + } + else { + FFLog(@"I-RDB034025", @"Wasn't connected or writes paused, so added to outstanding puts only. Path: %@", pathString); + } +} + +- (void) sendListen:(FOutstandingQuery *)listenSpec { + FQuerySpec *query = listenSpec.query; + FFLog(@"I-RDB034026", @"Listen for %@", query); + NSMutableDictionary *request = [NSMutableDictionary dictionaryWithObject:[query.path toString] forKey:kFWPRequestPath]; + + // Only bother to send query if it's non-default + if (listenSpec.tagId != nil) { + [request setObject:[query.params wireProtocolParams] forKey:kFWPRequestQueries]; + [request setObject:listenSpec.tagId forKey:kFWPRequestTag]; + } + + [request setObject:[listenSpec.syncTreeHash simpleHash] forKey:kFWPRequestHash]; + if ([listenSpec.syncTreeHash includeCompoundHash]) { + FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash]; + NSMutableArray *posts = [NSMutableArray array]; + for (FPath *path in compoundHash.posts) { + [posts addObject:path.wireFormat]; + } + request[kFWPRequestCompoundHash] = @{ kFWPRequestCompoundHashHashes: compoundHash.hashes, + kFWPRequestCompoundHashPaths: posts }; + } + + fbt_void_nsdictionary onResponse = ^(NSDictionary *response) { + FFLog(@"I-RDB034027", @"Listen response %@", response); + // warn in any case, even if the listener was removed + [self warnOnListenWarningsForQuery:query payload:response[kFWPResponseForActionData]]; + + FOutstandingQuery *currentListenSpec = self.listens[query]; + + // only trigger actions if the listen hasn't been removed (and maybe readded) + if (currentListenSpec == listenSpec) { + NSString *status = [response objectForKey:kFWPRequestStatus]; + if (![status isEqualToString:@"ok"]) { + [self removeListen:query]; + } + + if (listenSpec.onComplete) { + listenSpec.onComplete(status); + } + } + + self.unackedListensCount--; + NSAssert(self.unackedListensCount >= 0, @"unackedListensCount decremented to be negative."); + if (self.unackedListensCount == 0) { + [self ackPuts]; + } + }; + + [self sendAction:kFWPRequestActionTaggedListen + body:request + sensitive:NO + callback:onResponse]; + + self.unackedListensCount++; +} + +- (void) warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload { + if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) { + NSDictionary *payloadDict = payload; + id warnings = payloadDict[kFWPResponseDataWarnings]; + if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) { + NSArray *warningsArr = warnings; + if ([warningsArr containsObject:@"no_index"]) { + NSString *indexSpec = [NSString stringWithFormat:@"\".indexOn\": \"%@\"", [query.params.index queryDefinition]]; + NSString *indexPath = [query.path description]; + FFWarn(@"I-RDB034028", @"Using an unspecified index. Your data will be downloaded and filtered on the client. " + "Consider adding %@ at %@ to your security rules for better performance", indexSpec, indexPath); + } + } + } +} + +- (int) getNextRequestNumber { + return [[self.requestNumber getAndIncrement] intValue]; +} + +- (void)sendAction:(NSString *)action + body:(NSDictionary *)message + sensitive:(BOOL)sensitive + callback:(void (^)(NSDictionary* data))onMessage { + // Hold onto the onMessage callback for this request before firing it off + NSNumber* rn = [NSNumber numberWithInt:[self getNextRequestNumber]]; + NSDictionary* msg = [NSDictionary dictionaryWithObjectsAndKeys: + rn, kFWPRequestNumber, + action, kFWPRequestAction, + message, kFWPRequestPayloadBody, + nil]; + + [self.realtime sendRequest:msg sensitive:sensitive]; + + if (onMessage) { + // Debug message without a callback; bump the rn, but don't hold onto the cb + [self.requestCBHash setObject:[onMessage copy] forKey:rn]; + } +} + +- (void) cancelSentTransactions { + NSMutableDictionary* cancelledOutstandingPuts = [[NSMutableDictionary alloc] init]; + + for (NSNumber* index in self.outstandingPuts) { + FOutstandingPut* put = self.outstandingPuts[index]; + if (put.request[kFWPRequestHash] && put.sent) { + // This is a sent transaction put. + cancelledOutstandingPuts[index] = put; + } + } + + [cancelledOutstandingPuts enumerateKeysAndObjectsUsingBlock:^(NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) { + // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and enqueue new writes. We defer calling + // it until we have finished enumerating all existing writes. + outstandingPut.onCompleteBlock(kFTransactionDisconnect, @"Client was disconnected while running a transaction"); + [self.outstandingPuts removeObjectForKey:index]; + }]; +} + +- (void) onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body { + FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body); + id delegate = self.delegate; + if ([action isEqualToString:kFWPAsyncServerDataUpdate] || [action isEqualToString:kFWPAsyncServerDataMerge]) { + BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge]; + + if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] && [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) { + NSString* path = [body objectForKey:kFWPAsyncServerDataUpdateBodyPath]; + id payloadData = [body objectForKey:kFWPAsyncServerDataUpdateBodyData]; + if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] && [payloadData count] == 0) { + // ignore empty merge + } else { + [delegate onDataUpdate:self forPath:path message:payloadData isMerge:isMerge tagId:[body objectForKey:kFWPAsyncServerDataUpdateBodyTag]]; + } + } + else { + FFLog(@"I-RDB034030", @"Malformed data response from server missing path or data: %@", body); + } + } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) { + NSString *path = body[kFWPAsyncServerDataUpdateBodyPath]; + NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData]; + NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag]; + NSMutableArray *rangeMerges = [NSMutableArray array]; + for (NSDictionary *range in ranges) { + NSString *startString = range[kFWPAsyncServerDataUpdateStartPath]; + NSString *endString = range[kFWPAsyncServerDataUpdateEndPath]; + id updateData = range[kFWPAsyncServerDataUpdateRangeMerge]; + id updates = [FSnapshotUtilities nodeFrom:updateData]; + FPath *start = (startString != nil) ? [[FPath alloc] initWith:startString] : nil; + FPath *end = (endString != nil) ? [[FPath alloc] initWith:endString] : nil; + FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start end:end updates:updates]; + [rangeMerges addObject:merge]; + } + [delegate onRangeMerge:rangeMerges forPath:path tagId:tag]; + } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) { + NSString* status = [body objectForKey:kFWPResponseForActionStatus]; + NSString* reason = [body objectForKey:kFWPResponseForActionData]; + [self onAuthRevokedWithStatus:status andReason:reason]; + } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) { + NSString* pathString = [body objectForKey:kFWPAsyncServerDataUpdateBodyPath]; + [self onListenRevoked:[[FPath alloc] initWith:pathString]]; + } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) { + NSString* msg = [body objectForKey:@"msg"]; + if (msg != nil) { + NSArray *msgs = [msg componentsSeparatedByString:@"\n"]; + for (NSString* m in msgs) { + FFWarn(@"I-RDB034031", @"%@", m); + } + } + } else { + // TODO: revoke listens, auth, security debug + FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action); + } +} + +- (void) restoreAuth { + FFLog(@"I-RDB034033", @"Calling restore state"); + + NSAssert(self->connectionState == ConnectionStateConnecting, + @"Wanted to restore auth, but was in wrong state: %d", self->connectionState); + if (self.authToken == nil) { + FFLog(@"I-RDB034034", @"Not restoring auth because token is nil"); + self->connectionState = ConnectionStateConnected; + [self restoreState]; + } else { + FFLog(@"I-RDB034035", @"Restoring auth"); + self->connectionState = ConnectionStateAuthenticating; + [self sendAuthAndRestoreStateAfterComplete:YES]; + } +} + +- (void) restoreState { + NSAssert(self->connectionState == ConnectionStateConnected, + @"Should be connected if we're restoring state, but we are: %d", self->connectionState); + + [self.listens enumerateKeysAndObjectsUsingBlock:^(FQuerySpec *query, FOutstandingQuery *outstandingListen, BOOL *stop) { + FFLog(@"I-RDB034036", @"Restoring listen for %@", query); + [self sendListen:outstandingListen]; + }]; + + NSArray* keys = [[self.outstandingPuts allKeys] sortedArrayUsingSelector:@selector(compare:)]; + for(int i = 0; i < [keys count]; i++) { + if([self.outstandingPuts objectForKey:[keys objectAtIndex:i]] != nil) { + FFLog(@"I-RDB034037", @"Restoring put: %d", i); + [self sendPut:[keys objectAtIndex:i]]; + } + else { + FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i); + } + } + + for (FTupleOnDisconnect* tuple in self.onDisconnectQueue) { + [self sendOnDisconnectAction:tuple.action forPath:tuple.pathString withData:tuple.data andCallback:tuple.onComplete]; + } + [self.onDisconnectQueue removeAllObjects]; +} + +- (NSArray *) removeListen:(FQuerySpec *)query { + NSAssert(query.isDefault || !query.loadsAllData, @"removeListen called for non-default but complete query"); + + FOutstandingQuery* outstanding = self.listens[query]; + if (!outstanding) { + FFLog(@"I-RDB034039", @"Trying to remove listener for query %@ but no listener exists", query); + return @[]; + } else { + [self.listens removeObjectForKey:query]; + return @[outstanding]; + } +} + +- (NSArray *) removeAllListensAtPath:(FPath *)path { + FFLog(@"I-RDB034040", @"Removing all listens at path %@", path); + NSMutableArray *removed = [NSMutableArray array]; + NSMutableArray *toRemove = [NSMutableArray array]; + [self.listens enumerateKeysAndObjectsUsingBlock:^(FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) { + if ([spec.path isEqual:path]) { + [removed addObject:outstanding]; + [toRemove addObject:spec]; + } + }]; + [self.listens removeObjectsForKeys:toRemove]; + return removed; +} + +- (void) purgeOutstandingWrites { + // We might have unacked puts in our queue that we need to ack now before we send out any cancels... + [self ackPuts]; + // Cancel in order + NSArray* keys = [[self.outstandingPuts allKeys] sortedArrayUsingSelector:@selector(compare:)]; + for (NSNumber *key in keys) { + FOutstandingPut *put = self.outstandingPuts[key]; + if (put.onCompleteBlock != nil) { + put.onCompleteBlock(kFErrorWriteCanceled, nil); + } + } + for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) { + if (onDisconnect.onComplete != nil) { + onDisconnect.onComplete(kFErrorWriteCanceled, nil); + } + } + [self.outstandingPuts removeAllObjects]; + [self.onDisconnectQueue removeAllObjects]; +} + +- (void) ackPuts { + for (FTupleCallbackStatus *put in self.putsToAck) { + put.block(put.status, put.errorReason); + } + [self.putsToAck removeAllObjects]; +} + +- (void) handleTimestamp:(NSNumber *)timestamp { + FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp); + double timestampDeltaMs = [timestamp doubleValue] - ([[NSDate date] timeIntervalSince1970] * 1000); + [self.delegate onServerInfoUpdate:self updates:@{kDotInfoServerTimeOffset: [NSNumber numberWithDouble:timestampDeltaMs]}]; +} + +- (void) sendStats:(NSDictionary *)stats { + if ([stats count] > 0) { + NSDictionary *request = @{ kFWPRequestCounters: stats }; + [self sendAction:kFWPRequestActionStats body:request sensitive:NO callback:^(NSDictionary *data) { + NSString* status = [data objectForKey:kFWPResponseForActionStatus]; + NSString* errorReason = [data objectForKey:kFWPResponseForActionData]; + BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk]; + if (!statusOk) { + FFLog(@"I-RDB034042", @"Failed to send stats: %@", errorReason); + } + }]; + } else { + FFLog(@"I-RDB034043", @"Not sending stats because stats are empty"); + } +} + +- (void) sendConnectStats { + NSMutableDictionary *stats = [NSMutableDictionary dictionary]; + + #if TARGET_OS_IOS || TARGET_OS_TV + if (self.config.persistenceEnabled) { + stats[@"persistence.ios.enabled"] = @1; + } + #elif TARGET_OS_OSX + if (self.config.persistenceEnabled) { + stats[@"persistence.osx.enabled"] = @1; + } + #endif + NSString *sdkVersion = [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"." withString:@"-"]; + NSString *sdkStatName = [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion]; + stats[sdkStatName] = @1; + FFLog(@"I-RDB034044", @"Sending first connection stats"); + [self sendStats:stats]; +} + +- (NSDictionary *) dumpListens { + return self.listens; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.h new file mode 100644 index 0000000..e9728e7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.h @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FIndex, FNodeFilter, FNode; + +@interface FQueryParams : NSObject + +@property (nonatomic, readonly) BOOL limitSet; +@property (nonatomic, readonly) NSInteger limit; + +@property (nonatomic, strong, readonly) NSString *viewFrom; +@property (nonatomic, strong, readonly) id indexStartValue; +@property (nonatomic, strong, readonly) NSString *indexStartKey; +@property (nonatomic, strong, readonly) id indexEndValue; +@property (nonatomic, strong, readonly) NSString *indexEndKey; + +@property (nonatomic, strong, readonly) id index; + +- (BOOL)loadsAllData; +- (BOOL)isDefault; +- (BOOL)isValid; +- (BOOL)hasAnchoredLimit; + +- (FQueryParams *) limitTo:(NSInteger) limit; +- (FQueryParams *) limitToFirst:(NSInteger) newLimit; +- (FQueryParams *) limitToLast:(NSInteger) newLimit; + +- (FQueryParams *) startAt:(id)indexValue childKey:(NSString *)key; +- (FQueryParams *) startAt:(id)indexValue; +- (FQueryParams *) endAt:(id)indexValue childKey:(NSString *)key; +- (FQueryParams *) endAt:(id)indexValue; + +- (FQueryParams *) orderBy:(id) index; + ++ (FQueryParams *) defaultInstance; ++ (FQueryParams *) fromQueryObject:(NSDictionary *)dict; + +- (BOOL)hasStart; +- (BOOL)hasEnd; + +- (NSDictionary *) wireProtocolParams; +- (BOOL) isViewFromLeft; +- (id) nodeFilter; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.m new file mode 100644 index 0000000..7920358 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQueryParams.m @@ -0,0 +1,372 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FQueryParams.h" +#import "FValidation.h" +#import "FConstants.h" +#import "FIndex.h" +#import "FPriorityIndex.h" +#import "FUtilities.h" +#import "FNodeFilter.h" +#import "FIndexedFilter.h" +#import "FLimitedFilter.h" +#import "FRangedFilter.h" +#import "FNode.h" +#import "FSnapshotUtilities.h" + +@interface FQueryParams () + +@property (nonatomic, readwrite) BOOL limitSet; +@property (nonatomic, readwrite) NSInteger limit; + +@property (nonatomic, strong, readwrite) NSString *viewFrom; +/** +* indexStartValue is anything you can store as a priority / value. +*/ +@property (nonatomic, strong, readwrite) id indexStartValue; +@property (nonatomic, strong, readwrite) NSString *indexStartKey; +/** +* indexStartValue is anything you can store as a priority / value. +*/ +@property (nonatomic, strong, readwrite) id indexEndValue; +@property (nonatomic, strong, readwrite) NSString *indexEndKey; + +@property (nonatomic, strong, readwrite) id index; + +@end + +@implementation FQueryParams + ++ (FQueryParams *) defaultInstance { + static FQueryParams *defaultParams = nil; + static dispatch_once_t defaultParamsToken; + dispatch_once(&defaultParamsToken, ^{ + defaultParams = [[FQueryParams alloc] init]; + }); + return defaultParams; +} + + +- (id)init { + self = [super init]; + if (self) { + self->_limitSet = NO; + self->_limit = 0; + + self->_viewFrom = nil; + self->_indexStartValue = nil; + self->_indexStartKey = nil; + self->_indexEndValue = nil; + self->_indexEndKey = nil; + + self->_index = [FPriorityIndex priorityIndex]; + } + return self; +} + +/** +* Only valid if hasStart is true +*/ +- (id) indexStartValue { + NSAssert([self hasStart], @"Only valid if start has been set"); + return _indexStartValue; +} + +/** +* Only valid if hasStart is true. +* @return The starting key name for the range defined by these query parameters +*/ +- (NSString *) indexStartKey { + NSAssert([self hasStart], @"Only valid if start has been set"); + if (_indexStartKey == nil) { + return [FUtilities minName]; + } else { + return _indexStartKey; + } +} + +/** +* Only valid if hasEnd is true. +*/ +- (id) indexEndValue { + NSAssert([self hasEnd], @"Only valid if end has been set"); + return _indexEndValue; +} + +/** +* Only valid if hasEnd is true. +* @return The end key name for the range defined by these query parameters +*/ +- (NSString *) indexEndKey { + NSAssert([self hasEnd], @"Only valid if end has been set"); + if (_indexEndKey == nil) { + return [FUtilities maxName]; + } else { + return _indexEndKey; + } +} + +/** +* @return true if a limit has been set and has been explicitly anchored +*/ +- (BOOL) hasAnchoredLimit { + return self.limitSet && self.viewFrom != nil; +} + +/** +* Only valid to call if limitSet returns true +*/ +- (NSInteger) limit { + NSAssert(self.limitSet, @"Only valid if limit has been set"); + return _limit; +} + +- (BOOL)hasStart { + return self->_indexStartValue != nil; +} + +- (BOOL)hasEnd { + return self->_indexEndValue != nil; +} + +- (id) copyWithZone:(NSZone *)zone { + // Immutable + return self; +} + +- (id) mutableCopy { + FQueryParams* other = [[[self class] alloc] init]; + // Maybe need to do extra copying here + other->_limitSet = _limitSet; + other->_limit = _limit; + other->_indexStartValue = _indexStartValue; + other->_indexStartKey = _indexStartKey; + other->_indexEndValue = _indexEndValue; + other->_indexEndKey = _indexEndKey; + other->_viewFrom = _viewFrom; + other->_index = _index; + return other; +} + +- (FQueryParams *) limitTo:(NSInteger)newLimit { + FQueryParams *newParams = [self mutableCopy]; + newParams->_limitSet = YES; + newParams->_limit = newLimit; + newParams->_viewFrom = nil; + return newParams; +} + +- (FQueryParams *) limitToFirst:(NSInteger)newLimit { + FQueryParams *newParams = [self mutableCopy]; + newParams->_limitSet = YES; + newParams->_limit = newLimit; + newParams->_viewFrom = kFQPViewFromLeft; + return newParams; +} + +- (FQueryParams *) limitToLast:(NSInteger)newLimit { + FQueryParams *newParams = [self mutableCopy]; + newParams->_limitSet = YES; + newParams->_limit = newLimit; + newParams->_viewFrom = kFQPViewFromRight; + return newParams; +} + +- (FQueryParams *) startAt:(id)indexValue childKey:(NSString *)key { + NSAssert([indexValue isLeafNode] || [indexValue isEmpty], nil); + FQueryParams *newParams = [self mutableCopy]; + newParams->_indexStartValue = indexValue; + newParams->_indexStartKey = key; + return newParams; +} + +- (FQueryParams *) startAt:(id)indexValue { + return [self startAt:indexValue childKey:nil]; +} + +- (FQueryParams *) endAt:(id)indexValue childKey:(NSString *)key { + NSAssert([indexValue isLeafNode] || [indexValue isEmpty], nil); + FQueryParams *newParams = [self mutableCopy]; + newParams->_indexEndValue = indexValue; + newParams->_indexEndKey = key; + return newParams; +} + +- (FQueryParams *) endAt:(id)indexValue { + return [self endAt:indexValue childKey:nil]; +} + +- (FQueryParams *) orderBy:(id)newIndex { + FQueryParams *newParams = [self mutableCopy]; + newParams->_index = newIndex; + return newParams; +} + +- (NSDictionary *) wireProtocolParams { + NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; + if ([self hasStart]) { + [dict setObject:[self.indexStartValue valForExport:YES] forKey:kFQPIndexStartValue]; + + // Don't use property as it will be [MIN-NAME] + if (self->_indexStartKey != nil) { + [dict setObject:self->_indexStartKey forKey:kFQPIndexStartName]; + } + } + + if ([self hasEnd]) { + [dict setObject:[self.indexEndValue valForExport:YES] forKey:kFQPIndexEndValue]; + + // Don't use property as it will be [MAX-NAME] + if (self->_indexEndKey != nil) { + [dict setObject:self->_indexEndKey forKey:kFQPIndexEndName]; + } + } + + if (self.limitSet) { + [dict setObject:[NSNumber numberWithInteger:self.limit] forKey:kFQPLimit]; + NSString *vf = self.viewFrom; + if (vf == nil) { + // limit() rather than limitToFirst or limitToLast was called. + // This means that only one of startSet or endSet is true. Use them + // to calculate which side of the view to anchor to. If neither is set, + // Anchor to end + if ([self hasStart]) { + vf = kFQPViewFromLeft; + } else { + vf = kFQPViewFromRight; + } + } + [dict setObject:vf forKey:kFQPViewFrom]; + } + + // For now, priority index is the default, so we only specify if it's some other index. + if (![self.index isEqual:[FPriorityIndex priorityIndex]]) { + [dict setObject:[self.index queryDefinition] forKey:kFQPIndex]; + } + + return dict; +} + ++ (FQueryParams *)fromQueryObject:(NSDictionary *)dict { + if (dict.count == 0) { + return [FQueryParams defaultInstance]; + } + + FQueryParams *params = [[FQueryParams alloc] init]; + if (dict[kFQPLimit] != nil) { + params->_limitSet = YES; + params->_limit = [dict[kFQPLimit] integerValue]; + } + + if (dict[kFQPIndexStartValue] != nil) { + params->_indexStartValue = [FSnapshotUtilities nodeFrom:dict[kFQPIndexStartValue]]; + if (dict[kFQPIndexStartName] != nil) { + params->_indexStartKey = dict[kFQPIndexStartName]; + } + } + + if (dict[kFQPIndexEndValue] != nil) { + params->_indexEndValue = [FSnapshotUtilities nodeFrom:dict[kFQPIndexEndValue]]; + if (dict[kFQPIndexEndName] != nil) { + params->_indexEndKey = dict[kFQPIndexEndName]; + } + } + + if (dict[kFQPViewFrom] != nil) { + NSString *viewFrom = dict[kFQPViewFrom]; + if (![viewFrom isEqualToString:kFQPViewFromLeft] && ![viewFrom isEqualToString:kFQPViewFromRight]) { + [NSException raise:NSInvalidArgumentException format:@"Unknown view from paramter: %@", viewFrom]; + } + params->_viewFrom = viewFrom; + } + + NSString *index = dict[kFQPIndex]; + if (index != nil) { + params->_index = [FIndex indexFromQueryDefinition:index]; + } + + return params; +} + +- (BOOL) isViewFromLeft { + if (self.viewFrom != nil) { + // Not null, we can just check + return [self.viewFrom isEqualToString:kFQPViewFromLeft]; + } else { + // If start is set, it's view from left. Otherwise not. + return self.hasStart; + } +} + +- (id) nodeFilter { + if (self.loadsAllData) { + return [[FIndexedFilter alloc] initWithIndex:self.index]; + } else if (self.limitSet) { + return [[FLimitedFilter alloc] initWithQueryParams:self]; + } else { + return [[FRangedFilter alloc] initWithQueryParams:self]; + } +} + + +- (BOOL) isValid { + return !(self.hasStart && self.hasEnd && self.limitSet && !self.hasAnchoredLimit); +} + +- (BOOL) loadsAllData { + return !(self.hasStart || self.hasEnd || self.limitSet); +} + +- (BOOL) isDefault { + return [self loadsAllData] && [self.index isEqual:[FPriorityIndex priorityIndex]]; +} + +- (NSString *) description { + return [[self wireProtocolParams] description]; +} + +- (BOOL) isEqual:(id)obj { + if (self == obj) { + return YES; + } + if (![obj isKindOfClass:[self class]]) { + return NO; + } + FQueryParams *other = (FQueryParams *)obj; + if (self->_limitSet != other->_limitSet) return NO; + if (self->_limit != other->_limit) return NO; + if ((self->_index != other->_index) && ![self->_index isEqual:other->_index]) return NO; + if ((self->_indexStartKey != other->_indexStartKey) && ![self->_indexStartKey isEqualToString:other->_indexStartKey]) return NO; + if ((self->_indexStartValue != other->_indexStartValue) && ![self->_indexStartValue isEqual:other->_indexStartValue]) return NO; + if ((self->_indexEndKey != other->_indexEndKey) && ![self->_indexEndKey isEqualToString:other->_indexEndKey]) return NO; + if ((self->_indexEndValue != other->_indexEndValue) && ![self->_indexEndValue isEqual:other->_indexEndValue]) return NO; + if ([self isViewFromLeft] != [other isViewFromLeft]) return NO; + + return YES; +} + +- (NSUInteger) hash { + NSUInteger result = _limitSet ? _limit : 0; + result = 31 * result + ([self isViewFromLeft] ? 1231 : 1237); + result = 31 * result + [_indexStartKey hash]; + result = 31 * result + [_indexStartValue hash]; + result = 31 * result + [_indexEndKey hash]; + result = 31 * result + [_indexEndValue hash]; + result = 31 * result + [_index hash]; + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.h new file mode 100644 index 0000000..49ed536 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FQueryParams.h" +#import "FPath.h" +#import "FIndex.h" + +@interface FQuerySpec : NSObject + +@property (nonatomic, strong, readonly) FPath* path; +@property (nonatomic, strong, readonly) FQueryParams *params; + +- (id)initWithPath:(FPath *)path params:(FQueryParams *)params; + ++ (FQuerySpec *)defaultQueryAtPath:(FPath *)path; + +- (id)index; +- (BOOL)isDefault; +- (BOOL)loadsAllData; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.m new file mode 100644 index 0000000..24be433 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FQuerySpec.m @@ -0,0 +1,85 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FQuerySpec.h" + +@interface FQuerySpec () + +@property (nonatomic, strong, readwrite) FPath* path; +@property (nonatomic, strong, readwrite) FQueryParams *params; + + +@end + +@implementation FQuerySpec + +- (id)initWithPath:(FPath *)path params:(FQueryParams *)params { + self = [super init]; + if (self != nil) { + self->_path = path; + self->_params = params; + } + return self; +} + ++ (FQuerySpec *)defaultQueryAtPath:(FPath *)path { + return [[FQuerySpec alloc] initWithPath:path params:[FQueryParams defaultInstance]]; +} + +- (id)copyWithZone:(NSZone *)zone { + // Immutable + return self; +} + +- (id)index { + return self.params.index; +} + +- (BOOL)isDefault { + return self.params.isDefault; +} + +- (BOOL)loadsAllData { + return self.params.loadsAllData; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[FQuerySpec class]]) { + return NO; + } + + FQuerySpec *other = (FQuerySpec *)object; + + if (![self.path isEqual:other.path]) { + return NO; + } + + return [self.params isEqual:other.params]; +} + +- (NSUInteger)hash { + return self.path.hash * 31 + self.params.hash; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"FQuerySpec (path: %@, params: %@)", self.path, self.params]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.h new file mode 100644 index 0000000..8825e0e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FNode.h" + +/** + * Applies a merge of a snap for a given interval of paths. + * Each leaf in the current node which the relative path lies *after* (the optional) start and lies *before or at* + * (the optional) end will be deleted. Each leaf in snap that lies in the interval will be added to the resulting node. + * Nodes outside of the range are ignored. nil for start and end are sentinel values that represent -infinity and + * +infinity respectively (aka includes any path). + * Priorities of children nodes are treated as leaf children of that node. + */ +@interface FRangeMerge : NSObject + +- (instancetype)initWithStart:(FPath *)start end:(FPath *)end updates:(id)updates; + +- (id)applyToNode:(id)node; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.m new file mode 100644 index 0000000..8bc67bf --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRangeMerge.m @@ -0,0 +1,107 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRangeMerge.h" + +#import "FEmptyNode.h" + +@interface FRangeMerge () + +@property (nonatomic, strong) FPath *optExclusiveStart; +@property (nonatomic, strong) FPath *optInclusiveEnd; +@property (nonatomic, strong) id updates; + +@end + +@implementation FRangeMerge + +- (instancetype)initWithStart:(FPath *)start end:(FPath *)end updates:(id)updates { + self = [super init]; + if (self != nil) { + self->_optExclusiveStart = start; + self->_optInclusiveEnd = end; + self->_updates = updates; + } + return self; +} + +- (id)applyToNode:(id)node { + return [self updateRangeInNode:[FPath empty] node:node updates:self.updates]; +} + +- (id)updateRangeInNode:(FPath *)currentPath node:(id)node updates:(id)updates { + NSComparisonResult startComparison = (self.optExclusiveStart == nil) ? NSOrderedDescending : [currentPath compare:self.optExclusiveStart]; + NSComparisonResult endComparison = (self.optInclusiveEnd == nil) ? NSOrderedAscending : [currentPath compare:self.optInclusiveEnd]; + BOOL startInNode = self.optExclusiveStart != nil && [currentPath contains:self.optExclusiveStart]; + BOOL endInNode = self.optInclusiveEnd != nil && [currentPath contains:self.optInclusiveEnd]; + if (startComparison == NSOrderedDescending && endComparison == NSOrderedAscending && !endInNode) { + // child is completly contained + return updates; + } else if (startComparison == NSOrderedDescending && endInNode && [updates isLeafNode]) { + return updates; + } else if (startComparison == NSOrderedDescending && endComparison == NSOrderedSame) { + NSAssert(endInNode, @"End not in node"); + NSAssert(![updates isLeafNode], @"Found leaf node update, this case should have been handled above."); + if ([node isLeafNode]) { + // Update node was not a leaf node, so we can delete it + return [FEmptyNode emptyNode]; + } else { + // Unaffected by range, ignore + return node; + } + } else if (startInNode || endInNode) { + // There is a partial update we need to do, so collect all relevant children + NSMutableSet *allChildren = [NSMutableSet set]; + [node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + [allChildren addObject:key]; + }]; + [updates enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + [allChildren addObject:key]; + }]; + + __block id newNode = node; + void (^action)(id, BOOL *) = ^void(NSString *key, BOOL *stop) { + id currentChild = [node getImmediateChild:key]; + id updatedChild = [self updateRangeInNode:[currentPath childFromString:key] + node:currentChild + updates:[updates getImmediateChild:key]]; + // Only need to update if the node changed + if (updatedChild != currentChild) { + newNode = [newNode updateImmediateChild:key withNewChild:updatedChild]; + } + }; + + [allChildren enumerateObjectsUsingBlock:action]; + + // Add priority last, so the node is not empty when applying + if (!updates.getPriority.isEmpty || !node.getPriority.isEmpty) { + BOOL stop = NO; + action(@".priority", &stop); + } + return newNode; + } else { + // Unaffected by this range + NSAssert(endComparison == NSOrderedDescending || startComparison <= NSOrderedSame, @"Invalid range for update"); + return node; + } +} + +- (NSString *)description { + return [NSString stringWithFormat:@"RangeMerge (optExclusiveStart = %@, optExclusiveEng = %@, updates = %@)", + self.optExclusiveStart, self.optInclusiveEnd, self.updates]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.h new file mode 100644 index 0000000..ab0b074 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.h @@ -0,0 +1,76 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FRepoInfo.h" +#import "FPersistentConnection.h" +#import "FIRDataEventType.h" +#import "FTupleUserCallback.h" + +@class FQuerySpec; +@class FPersistence; +@class FAuthenticationManager; +@class FIRDatabaseConfig; +@protocol FEventRegistration; +@class FCompoundWrite; +@protocol FClock; +@class FIRDatabase; + +@interface FRepo : NSObject + +@property (nonatomic, strong) FIRDatabaseConfig *config; + +- (id)initWithRepoInfo:(FRepoInfo *)info config:(FIRDatabaseConfig *)config database:(FIRDatabase *)database; + +- (void) set:(FPath *)path withNode:(id)node withCallback:(fbt_void_nserror_ref)onComplete; +- (void) update:(FPath *)path withNodes:(FCompoundWrite *)compoundWrite withCallback:(fbt_void_nserror_ref)callback; +- (void) purgeOutstandingWrites; + +- (void) addEventRegistration:(id)eventRegistration forQuery:(FQuerySpec *)query; +- (void) removeEventRegistration:(id)eventRegistration forQuery:(FQuerySpec *)query; +- (void) keepQuery:(FQuerySpec *)query synced:(BOOL)synced; + +- (NSString*)name; +- (NSTimeInterval)serverTime; + +- (void) onDataUpdate:(FPersistentConnection *)fpconnection forPath:(NSString *)pathString message:(id)message isMerge:(BOOL)isMerge tagId:(NSNumber *)tagId; +- (void) onConnect:(FPersistentConnection *)fpconnection; +- (void) onDisconnect:(FPersistentConnection *)fpconnection; + +// Disconnect methods +- (void) onDisconnectCancel:(FPath *)path withCallback:(fbt_void_nserror_ref)callback; +- (void) onDisconnectSet:(FPath *)path withNode:(id)node withCallback:(fbt_void_nserror_ref)callback; +- (void) onDisconnectUpdate:(FPath *)path withNodes:(FCompoundWrite *)compoundWrite withCallback:(fbt_void_nserror_ref)callback; + +// Connection Management. +- (void) interrupt; +- (void) resume; + +// Transactions +- (void) startTransactionOnPath:(FPath *)path + update:(fbt_transactionresult_mutabledata)update + onComplete:(fbt_void_nserror_bool_datasnapshot)onComplete + withLocalEvents:(BOOL)applyLocally; + +// Testing methods +- (NSDictionary *) dumpListens; +- (void) dispose; +- (void) setHijackHash:(BOOL)hijack; + +@property (nonatomic, strong, readonly) FAuthenticationManager *auth; +@property (nonatomic, strong, readonly) FIRDatabase *database; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.m new file mode 100644 index 0000000..ae1d8e8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo.m @@ -0,0 +1,1119 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import +#import +#import "FRepo.h" +#import "FSnapshotUtilities.h" +#import "FConstants.h" +#import "FIRDatabaseQuery_Private.h" +#import "FQuerySpec.h" +#import "FTupleNodePath.h" +#import "FRepo_Private.h" +#import "FRepoManager.h" +#import "FServerValues.h" +#import "FTupleSetIdPath.h" +#import "FSyncTree.h" +#import "FEventRegistration.h" +#import "FAtomicNumber.h" +#import "FSyncTree.h" +#import "FListenProvider.h" +#import "FEventRaiser.h" +#import "FSnapshotHolder.h" +#import "FIRDatabaseConfig_Private.h" +#import "FLevelDBStorageEngine.h" +#import "FPersistenceManager.h" +#import "FWriteRecord.h" +#import "FCachePolicy.h" +#import "FClock.h" +#import "FIRDatabase_Private.h" +#import "FTree.h" +#import "FTupleTransaction.h" +#import "FIRTransactionResult.h" +#import "FIRTransactionResult_Private.h" +#import "FIRMutableData.h" +#import "FIRMutableData_Private.h" +#import "FIRDataSnapshot.h" +#import "FIRDataSnapshot_Private.h" +#import "FValueEventRegistration.h" +#import "FEmptyNode.h" + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#endif + +@interface FRepo() + +@property (nonatomic, strong) FOffsetClock *serverClock; +@property (nonatomic, strong) FPersistenceManager* persistenceManager; +@property (nonatomic, strong) FIRDatabase *database; +@property (nonatomic, strong, readwrite) FAuthenticationManager *auth; +@property (nonatomic, strong) FSyncTree *infoSyncTree; +@property (nonatomic) NSInteger writeIdCounter; +@property (nonatomic) BOOL hijackHash; +@property (nonatomic, strong) FTree *transactionQueueTree; +@property (nonatomic) BOOL loggedTransactionPersistenceWarning; + +/** +* Test only. For load testing the server. +*/ +@property (nonatomic, strong) id (^interceptServerDataCallback)(NSString *pathString, id data); +@end + + +@implementation FRepo + +- (id)initWithRepoInfo:(FRepoInfo*)info config:(FIRDatabaseConfig *)config database:(FIRDatabase *)database { + self = [super init]; + if (self) { + self.repoInfo = info; + self.config = config; + self.database = database; + + // Access can occur outside of shared queue, so the clock needs to be initialized here + self.serverClock = [[FOffsetClock alloc] initWithClock:[FSystemClock clock] offset:0]; + + self.connection = [[FPersistentConnection alloc] initWithRepoInfo:self.repoInfo dispatchQueue:[FIRDatabaseQuery sharedQueue] config:self.config]; + + // Needs to be called before authentication manager is instantiated + self.eventRaiser = [[FEventRaiser alloc] initWithQueue:self.config.callbackQueue]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self deferredInit]; + }); + } + return self; +} + +- (void)deferredInit { + // TODO: cleanup on dealloc + __weak FRepo *weakSelf = self; + [self.config.authTokenProvider listenForTokenChanges:^(NSString *token) { + [weakSelf.connection refreshAuthToken:token]; + }]; + + // Open connection now so that by the time we are connected the deferred init has run + // This relies on the fact that all callbacks run on repos queue + self.connection.delegate = self; + [self.connection open]; + + self.dataUpdateCount = 0; + self.rangeMergeUpdateCount = 0; + self.interceptServerDataCallback = nil; + + if (self.config.persistenceEnabled) { + NSString* repoHashString = [NSString stringWithFormat:@"%@_%@", self.repoInfo.host, self.repoInfo.namespace]; + NSString* persistencePrefix = [NSString stringWithFormat:@"%@/%@", self.config.sessionIdentifier, repoHashString]; + + id cachePolicy = [[FLRUCachePolicy alloc] initWithMaxSize:self.config.persistenceCacheSizeBytes]; + + id engine; + if (self.config.forceStorageEngine != nil) { + engine = self.config.forceStorageEngine; + } else { + FLevelDBStorageEngine *levelDBEngine = [[FLevelDBStorageEngine alloc] initWithPath:persistencePrefix]; + // We need the repo info to run the legacy migration. Future migrations will be managed by the database itself + // Remove this once we are confident that no-one is using legacy migration anymore... + [levelDBEngine runLegacyMigration:self.repoInfo]; + engine = levelDBEngine; + } + + self.persistenceManager = [[FPersistenceManager alloc] initWithStorageEngine:engine cachePolicy:cachePolicy]; + } else { + self.persistenceManager = nil; + } + + [self initTransactions]; + + // A list of data pieces and paths to be set when this client disconnects + self.onDisconnect = [[FSparseSnapshotTree alloc] init]; + self.infoData = [[FSnapshotHolder alloc] init]; + + FListenProvider *infoListenProvider = [[FListenProvider alloc] init]; + infoListenProvider.startListening = ^(FQuerySpec *query, + NSNumber *tagId, + id hash, + fbt_nsarray_nsstring onComplete) { + NSArray *infoEvents = @[]; + FRepo *strongSelf = weakSelf; + id node = [strongSelf.infoData getNode:query.path]; + // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events + // on initial data... + if (![node isEmpty]) { + infoEvents = [strongSelf.infoSyncTree applyServerOverwriteAtPath:query.path newData:node]; + [strongSelf.eventRaiser raiseCallback:^{ + onComplete(kFWPResponseForActionStatusOk); + }]; + } + return infoEvents; + }; + infoListenProvider.stopListening = ^(FQuerySpec *query, NSNumber *tagId) {}; + self.infoSyncTree = [[FSyncTree alloc] initWithListenProvider:infoListenProvider]; + + FListenProvider *serverListenProvider = [[FListenProvider alloc] init]; + serverListenProvider.startListening = ^(FQuerySpec *query, + NSNumber *tagId, + id hash, + fbt_nsarray_nsstring onComplete) { + [weakSelf.connection listen:query tagId:tagId hash:hash onComplete:^(NSString *status) { + NSArray *events = onComplete(status); + [weakSelf.eventRaiser raiseEvents:events]; + }]; + // No synchronous events for network-backed sync trees + return @[]; + }; + serverListenProvider.stopListening = ^(FQuerySpec *query, NSNumber *tag) { + [weakSelf.connection unlisten:query tagId:tag]; + }; + self.serverSyncTree = [[FSyncTree alloc] initWithPersistenceManager:self.persistenceManager + listenProvider:serverListenProvider]; + + [self restoreWrites]; + + [self updateInfo:kDotInfoConnected withValue:@NO]; + + [self setupNotifications]; +} + + +- (void) restoreWrites { + NSArray *writes = self.persistenceManager.userWrites; + + NSDictionary *serverValues = [FServerValues generateServerValues:self.serverClock]; + __block NSInteger lastWriteId = NSIntegerMin; + [writes enumerateObjectsUsingBlock:^(FWriteRecord *write, NSUInteger idx, BOOL *stop) { + NSInteger writeId = write.writeId; + fbt_void_nsstring_nsstring callback = ^(NSString *status, NSString *errorReason) { + [self warnIfWriteFailedAtPath:write.path status:status message:@"Persisted write"]; + [self ackWrite:writeId rerunTransactionsAtPath:write.path status:status]; + }; + if (lastWriteId >= writeId) { + [NSException raise:NSInternalInconsistencyException format:@"Restored writes were not in order!"]; + } + lastWriteId = writeId; + self.writeIdCounter = writeId + 1; + if ([write isOverwrite]) { + FFLog(@"I-RDB038001", @"Restoring overwrite with id %ld", (long)write.writeId); + [self.connection putData:[write.overwrite valForExport:YES] + forPath:[write.path toString] + withHash:nil + withCallback:callback]; + id resolved = [FServerValues resolveDeferredValueSnapshot:write.overwrite withServerValues:serverValues]; + [self.serverSyncTree applyUserOverwriteAtPath:write.path newData:resolved writeId:writeId isVisible:YES]; + } else { + FFLog(@"I-RDB038002", @"Restoring merge with id %ld", (long)write.writeId); + [self.connection mergeData:[write.merge valForExport:YES] + forPath:[write.path toString] + withCallback:callback]; + FCompoundWrite *resolved = [FServerValues resolveDeferredValueCompoundWrite:write.merge withServerValues:serverValues]; + [self.serverSyncTree applyUserMergeAtPath:write.path changedChildren:resolved writeId:writeId]; + } + }]; +} + +- (NSString*)name { + return self.repoInfo.namespace; +} + +- (NSString *) description { + return [self.repoInfo description]; +} + +- (void) interrupt { + [self.connection interruptForReason:kFInterruptReasonRepoInterrupt]; +} + +- (void) resume { + [self.connection resumeForReason:kFInterruptReasonRepoInterrupt]; +} + +// NOTE: Typically if you're calling this, you should be in an @autoreleasepool block to make sure that ARC kicks +// in and cleans up things no longer referenced (i.e. pendingPutsDB). +- (void) dispose { + [self.connection interruptForReason:kFInterruptReasonRepoInterrupt]; + + // We need to nil out any references to LevelDB, to make sure the + // LevelDB exclusive locks are released. + [self.persistenceManager close]; +} + +- (NSInteger) nextWriteId { + return self->_writeIdCounter++; +} + +- (NSTimeInterval) serverTime { + return [self.serverClock currentTime]; +} + +- (void) set:(FPath *)path withNode:(id)node withCallback:(fbt_void_nserror_ref)onComplete { + id value = [node valForExport:YES]; + FFLog(@"I-RDB038003", @"Setting: %@ with %@ pri: %@", [path toString], [value description], [[node getPriority] val]); + + // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or + // (b) store unresolved paths on JSON parse + NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock]; + id newNode = [FServerValues resolveDeferredValueSnapshot:node withServerValues:serverValues]; + + NSInteger writeId = [self nextWriteId]; + [self.persistenceManager saveUserOverwrite:node atPath:path writeId:writeId]; + NSArray *events = [self.serverSyncTree applyUserOverwriteAtPath:path newData:newNode writeId:writeId isVisible:YES]; + [self.eventRaiser raiseEvents:events]; + + [self.connection putData:value forPath:[path toString] withHash:nil withCallback:^(NSString *status, NSString *errorReason) { + [self warnIfWriteFailedAtPath:path status:status message:@"setValue: or removeValue:"]; + [self ackWrite:writeId rerunTransactionsAtPath:path status:status]; + [self callOnComplete:onComplete withStatus:status errorReason:errorReason andPath:path]; + }]; + + FPath* affectedPath = [self abortTransactionsAtPath:path error:kFTransactionSet]; + [self rerunTransactionsForPath:affectedPath]; +} + +- (void) update:(FPath *)path withNodes:(FCompoundWrite *)nodes withCallback:(fbt_void_nserror_ref)callback { + NSDictionary *values = [nodes valForExport:YES]; + + FFLog(@"I-RDB038004", @"Updating: %@ with %@", [path toString], [values description]); + NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock]; + FCompoundWrite *resolved = [FServerValues resolveDeferredValueCompoundWrite:nodes withServerValues:serverValues]; + + if (!resolved.isEmpty) { + NSInteger writeId = [self nextWriteId]; + [self.persistenceManager saveUserMerge:nodes atPath:path writeId:writeId]; + NSArray *events = [self.serverSyncTree applyUserMergeAtPath:path changedChildren:resolved writeId:writeId]; + [self.eventRaiser raiseEvents:events]; + + [self.connection mergeData:values forPath:[path description] withCallback:^(NSString *status, NSString *errorReason) { + [self warnIfWriteFailedAtPath:path status:status message:@"updateChildValues:"]; + [self ackWrite:writeId rerunTransactionsAtPath:path status:status]; + [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path]; + }]; + + [nodes enumerateWrites:^(FPath *childPath, id node, BOOL *stop) { + FPath* pathFromRoot = [path child:childPath]; + FFLog(@"I-RDB038005", @"Cancelling transactions at path: %@", pathFromRoot); + FPath *affectedPath = [self abortTransactionsAtPath:pathFromRoot error:kFTransactionSet]; + [self rerunTransactionsForPath:affectedPath]; + }]; + } else { + FFLog(@"I-RDB038006", @"update called with empty data. Doing nothing"); + // Do nothing, just call the callback + [self callOnComplete:callback withStatus:@"ok" errorReason:nil andPath:path]; + } +} + +- (void) onDisconnectCancel:(FPath *)path withCallback:(fbt_void_nserror_ref)callback { + [self.connection onDisconnectCancelPath:path withCallback:^(NSString *status, NSString *errorReason) { + BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk]; + if (success) { + [self.onDisconnect forgetPath:path]; + } else { + FFLog(@"I-RDB038007", @"cancelDisconnectOperations: at %@ failed: %@", path, status); + } + + [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path]; + }]; +} + +- (void) onDisconnectSet:(FPath *)path withNode:(id)node withCallback:(fbt_void_nserror_ref)callback { + [self.connection onDisconnectPutData:[node valForExport:YES] forPath:path withCallback:^(NSString *status, NSString *errorReason) { + BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk]; + if (success) { + [self.onDisconnect rememberData:node onPath:path]; + } else { + FFWarn(@"I-RDB038008", @"onDisconnectSetValue: or onDisconnectRemoveValue: at %@ failed: %@", path, status); + } + + [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path]; + }]; +} + +- (void) onDisconnectUpdate:(FPath *)path withNodes:(FCompoundWrite *)nodes withCallback:(fbt_void_nserror_ref)callback { + if (!nodes.isEmpty) { + NSDictionary *values = [nodes valForExport:YES]; + + [self.connection onDisconnectMergeData:values forPath:path withCallback:^(NSString *status, NSString *errorReason) { + BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk]; + if (success) { + [nodes enumerateWrites:^(FPath *relativePath, id nodeUnresolved, BOOL *stop) { + FPath* childPath = [path child:relativePath]; + [self.onDisconnect rememberData:nodeUnresolved onPath:childPath]; + }]; + } else { + FFWarn(@"I-RDB038009", @"onDisconnectUpdateChildValues: at %@ failed %@", path, status); + } + + [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path]; + }]; + } else { + // Do nothing, just call the callback + [self callOnComplete:callback withStatus:@"ok" errorReason:nil andPath:path]; + } +} + +- (void) purgeOutstandingWrites { + FFLog(@"I-RDB038010", @"Purging outstanding writes"); + NSArray *events = [self.serverSyncTree removeAllWrites]; + [self.eventRaiser raiseEvents:events]; + // Abort any transactions + [self abortTransactionsAtPath:[FPath empty] error:kFErrorWriteCanceled]; + // Remove outstanding writes from connection + [self.connection purgeOutstandingWrites]; +} + +- (void) addEventRegistration:(id )eventRegistration forQuery:(FQuerySpec *)query { + NSArray *events = nil; + if ([[query.path getFront] isEqualToString:kDotInfoPrefix]) { + events = [self.infoSyncTree addEventRegistration:eventRegistration forQuery:query]; + } else { + events = [self.serverSyncTree addEventRegistration:eventRegistration forQuery:query]; + } + [self.eventRaiser raiseEvents:events]; +} + +- (void) removeEventRegistration:(id)eventRegistration forQuery:(FQuerySpec *)query { + // These are guaranteed not to raise events, since we're not passing in a cancelError. However we can future-proof + // a little bit by handling the return values anyways. + FFLog(@"I-RDB038011", @"Removing event registration with hande: %lu", (unsigned long)eventRegistration.handle); + NSArray *events = nil; + if ([[query.path getFront] isEqualToString:kDotInfoPrefix]) { + events = [self.infoSyncTree removeEventRegistration:eventRegistration forQuery:query cancelError:nil]; + } else { + events = [self.serverSyncTree removeEventRegistration:eventRegistration forQuery:query cancelError:nil]; + } + [self.eventRaiser raiseEvents:events]; +} + +- (void) keepQuery:(FQuerySpec *)query synced:(BOOL)synced { + NSAssert(![[query.path getFront] isEqualToString:kDotInfoPrefix], @"Can't keep .info tree synced!"); + [self.serverSyncTree keepQuery:query synced:synced]; +} + +- (void) updateInfo:(NSString *) pathString withValue:(id)value { + // hack to make serverTimeOffset available in a threadsafe way. Property is marked as atomic + if ([pathString isEqualToString:kDotInfoServerTimeOffset]) { + NSTimeInterval offset = [(NSNumber *)value doubleValue]/1000.0; + self.serverClock = [[FOffsetClock alloc] initWithClock:[FSystemClock clock] offset:offset]; + } + + FPath* path = [[FPath alloc] initWith:[NSString stringWithFormat:@"%@/%@", kDotInfoPrefix, pathString]]; + id newNode = [FSnapshotUtilities nodeFrom:value]; + [self.infoData updateSnapshot:path withNewSnapshot:newNode]; + NSArray *events = [self.infoSyncTree applyServerOverwriteAtPath:path newData:newNode]; + [self.eventRaiser raiseEvents:events]; +} + +- (void) callOnComplete:(fbt_void_nserror_ref)onComplete withStatus:(NSString *)status errorReason:(NSString *)errorReason andPath:(FPath *)path { + if (onComplete) { + FIRDatabaseReference * ref = [[FIRDatabaseReference alloc] initWithRepo:self path:path]; + BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk]; + NSError* err = nil; + if (!statusOk) { + err = [FUtilities errorForStatus:status andReason:errorReason]; + } + [self.eventRaiser raiseCallback:^{ + onComplete(err, ref); + }]; + } +} + +- (void)ackWrite:(NSInteger)writeId rerunTransactionsAtPath:(FPath *)path status:(NSString *)status { + if ([status isEqualToString:kFErrorWriteCanceled]) { + // This write was already removed, we just need to ignore it... + } else { + BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk]; + NSArray *clearEvents = [self.serverSyncTree ackUserWriteWithWriteId:writeId revert:!success persist:YES clock:self.serverClock]; + if ([clearEvents count] > 0) { + [self rerunTransactionsForPath:path]; + } + [self.eventRaiser raiseEvents:clearEvents]; + } +} + +- (void) warnIfWriteFailedAtPath:(FPath *)path status:(NSString *)status message:(NSString *)message { + if (!([status isEqualToString:kFWPResponseForActionStatusOk] || [status isEqualToString:kFErrorWriteCanceled])) { + FFWarn(@"I-RDB038012", @"%@ at %@ failed: %@", message, path, status); + } +} + +#pragma mark - +#pragma mark FPersistentConnectionDelegate methods + +- (void) onDataUpdate:(FPersistentConnection *)fpconnection forPath:(NSString *)pathString message:(id)data isMerge:(BOOL)isMerge tagId:(NSNumber *)tagId { + FFLog(@"I-RDB038013", @"onDataUpdateForPath: %@ withMessage: %@", pathString, data); + + // For testing. + self.dataUpdateCount++; + + FPath* path = [[FPath alloc] initWith:pathString]; + data = self.interceptServerDataCallback ? self.interceptServerDataCallback(pathString, data) : data; + NSArray *events = nil; + + if (tagId != nil) { + if (isMerge) { + NSDictionary *message = data; + FCompoundWrite *taggedChildren = [FCompoundWrite compoundWriteWithValueDictionary:message]; + events = [self.serverSyncTree applyTaggedQueryMergeAtPath:path changedChildren:taggedChildren tagId:tagId]; + } else { + id taggedSnap = [FSnapshotUtilities nodeFrom:data]; + events = [self.serverSyncTree applyTaggedQueryOverwriteAtPath:path newData:taggedSnap tagId:tagId]; + } + } else if (isMerge) { + NSDictionary *message = data; + FCompoundWrite *changedChildren = [FCompoundWrite compoundWriteWithValueDictionary:message]; + events = [self.serverSyncTree applyServerMergeAtPath:path changedChildren:changedChildren]; + } else { + id snap = [FSnapshotUtilities nodeFrom:data]; + events = [self.serverSyncTree applyServerOverwriteAtPath:path newData:snap]; + } + + if ([events count] > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + [self rerunTransactionsForPath:path]; + } + + [self.eventRaiser raiseEvents:events]; +} + +- (void)onRangeMerge:(NSArray *)ranges forPath:(NSString *)pathString tagId:(NSNumber *)tag { + FFLog(@"I-RDB038014", @"onRangeMerge: %@ => %@", pathString, ranges); + + // For testing + self.rangeMergeUpdateCount++; + + FPath* path = [[FPath alloc] initWith:pathString]; + NSArray *events; + if (tag != nil) { + events = [self.serverSyncTree applyTaggedServerRangeMergeAtPath:path updates:ranges tagId:tag]; + } else { + events = [self.serverSyncTree applyServerRangeMergeAtPath:path updates:ranges]; + } + if (events.count > 0) { + // Since we have a listener outstanding for each transaction, receiving any events + // is a proxy for some change having occurred. + [self rerunTransactionsForPath:path]; + } + + [self.eventRaiser raiseEvents:events]; +} + +- (void)onConnect:(FPersistentConnection *)fpconnection { + [self updateInfo:kDotInfoConnected withValue:@YES]; +} + +- (void)onDisconnect:(FPersistentConnection *)fpconnection { + [self updateInfo:kDotInfoConnected withValue:@NO]; + [self runOnDisconnectEvents]; +} + +- (void)onServerInfoUpdate:(FPersistentConnection *)fpconnection updates:(NSDictionary *)updates { + for (NSString* key in updates) { + id val = [updates objectForKey:key]; + [self updateInfo:key withValue:val]; + } +} + +- (void) setupNotifications { + NSString * const *backgroundConstant = (NSString * const *) dlsym(RTLD_DEFAULT, "UIApplicationDidEnterBackgroundNotification"); + if (backgroundConstant) { + FFLog(@"I-RDB038015", @"Registering for background notification."); + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(didEnterBackground) + name:*backgroundConstant + object:nil]; + } else { + FFLog(@"I-RDB038016", @"Skipped registering for background notification."); + } +} + +- (void) didEnterBackground { + if (!self.config.persistenceEnabled) + return; + + // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual release build. + #if TARGET_OS_IOS || TARGET_OS_TV + // The idea is to wait until any outstanding sets get written to disk. Since the sets might still be in our + // dispatch queue, we wait for the dispatch queue to catch up and for persistence to catch up. + // This may be undesirable though. The dispatch queue might just be processing a bunch of incoming data or + // something. We might want to keep track of whether there are any unpersisted sets or something. + FFLog(@"I-RDB038017", @"Entering background. Starting background task to finish work."); + Class uiApplicationClass = NSClassFromString(@"UIApplication"); + assert(uiApplicationClass); // If we are here, we should be on iOS and UIApplication should be available. + + UIApplication *application = [uiApplicationClass sharedApplication]; + __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ + [application endBackgroundTask:bgTask]; + }]; + + NSDate *start = [NSDate date]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + NSTimeInterval finishTime = [start timeIntervalSinceNow]*-1; + FFLog(@"I-RDB038018", @"Background task completed. Queue time: %f", finishTime); + [application endBackgroundTask:bgTask]; + }); + #endif +} + +#pragma mark - +#pragma mark Internal methods + +/** +* Applies all the changes stored up in the onDisconnect tree +*/ +- (void) runOnDisconnectEvents { + FFLog(@"I-RDB038019", @"Running onDisconnectEvents"); + NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock]; + FSparseSnapshotTree* resolvedTree = [FServerValues resolveDeferredValueTree:self.onDisconnect withServerValues:serverValues]; + NSMutableArray *events = [[NSMutableArray alloc] init]; + + [resolvedTree forEachTreeAtPath:[FPath empty] do:^(FPath *path, id node) { + [events addObjectsFromArray:[self.serverSyncTree applyServerOverwriteAtPath:path newData:node]]; + FPath* affectedPath = [self abortTransactionsAtPath:path error:kFTransactionSet]; + [self rerunTransactionsForPath:affectedPath]; + }]; + + self.onDisconnect = [[FSparseSnapshotTree alloc] init]; + [self.eventRaiser raiseEvents:events]; +} + +- (NSDictionary *) dumpListens { + return [self.connection dumpListens]; +} + +#pragma mark - +#pragma mark Transactions + +/** + * Setup the transaction data structures + */ +- (void) initTransactions { + self.transactionQueueTree = [[FTree alloc] init]; + self.hijackHash = NO; + self.loggedTransactionPersistenceWarning = NO; +} + +/** + * Creates a new transaction, add its to the transactions we're tracking, and sends it to the server if possible + */ +- (void) startTransactionOnPath:(FPath *)path update:(fbt_transactionresult_mutabledata)update onComplete:(fbt_void_nserror_bool_datasnapshot)onComplete withLocalEvents:(BOOL)applyLocally { + if (self.config.persistenceEnabled && !self.loggedTransactionPersistenceWarning) { + self.loggedTransactionPersistenceWarning = YES; + FFInfo(@"I-RDB038020", @"runTransactionBlock: usage detected while persistence is enabled. Please be aware that transactions " + @"*will not* be persisted across app restarts. " + @"See https://www.firebase.com/docs/ios/guide/offline-capabilities.html#section-handling-transactions-offline for more details."); + } + + FIRDatabaseReference * watchRef = [[FIRDatabaseReference alloc] initWithRepo:self path:path]; + // make sure we're listening on this node + // Note: we can't do this asynchronously. To preserve event ordering, it has to be done in this block. + // This is ok, this block is guaranteed to be our own event loop + NSUInteger handle = [[FUtilities LUIDGenerator] integerValue]; + fbt_void_datasnapshot cb = ^(FIRDataSnapshot *snapshot) {}; + FValueEventRegistration *registration = [[FValueEventRegistration alloc] initWithRepo:self + handle:handle + callback:cb + cancelCallback:nil]; + [watchRef.repo addEventRegistration:registration forQuery:watchRef.querySpec]; + fbt_void_void unwatcher = ^{ [watchRef removeObserverWithHandle:handle]; }; + + // Save all the data that represents this transaction + FTupleTransaction* transaction = [[FTupleTransaction alloc] init]; + transaction.path = path; + transaction.update = update; + transaction.onComplete = onComplete; + transaction.status = FTransactionInitializing; + transaction.order = [FUtilities LUIDGenerator]; + transaction.applyLocally = applyLocally; + transaction.retryCount = 0; + transaction.unwatcher = unwatcher; + transaction.currentWriteId = nil; + transaction.currentInputSnapshot = nil; + transaction.currentOutputSnapshotRaw = nil; + transaction.currentOutputSnapshotResolved = nil; + + // Run transaction initially + id currentState = [self latestStateAtPath:path excludeWriteIds:nil]; + transaction.currentInputSnapshot = currentState; + FIRMutableData * mutableCurrent = [[FIRMutableData alloc] initWithNode:currentState]; + FIRTransactionResult * result = transaction.update(mutableCurrent); + + if (!result.isSuccess) { + // Abort the transaction + transaction.unwatcher(); + transaction.currentOutputSnapshotRaw = nil; + transaction.currentOutputSnapshotResolved = nil; + if (transaction.onComplete) { + FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path]; + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:transaction.currentInputSnapshot]; + FIRDataSnapshot *snap = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:indexedNode]; + [self.eventRaiser raiseCallback:^{ + transaction.onComplete(nil, NO, snap); + }]; + } + } else { + // Note: different from js. We don't need to validate, FIRMutableData does validation. + // We also don't have to worry about priorities. Just mark as run and add to queue. + transaction.status = FTransactionRun; + FTree* queueNode = [self.transactionQueueTree subTree:transaction.path]; + NSMutableArray* nodeQueue = [queueNode getValue]; + if (nodeQueue == nil) { + nodeQueue = [[NSMutableArray alloc] init]; + } + [nodeQueue addObject:transaction]; + [queueNode setValue:nodeQueue]; + + // Update visibleData and raise events + // Note: We intentionally raise events after updating all of our transaction state, since the user could + // start new transactions from the event callbacks + NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock]; + id newValUnresolved = [result.update nodeValue]; + id newVal = [FServerValues resolveDeferredValueSnapshot:newValUnresolved withServerValues:serverValues]; + transaction.currentOutputSnapshotRaw = newValUnresolved; + transaction.currentOutputSnapshotResolved = newVal; + transaction.currentWriteId = [NSNumber numberWithInteger:[self nextWriteId]]; + + NSArray *events = [self.serverSyncTree applyUserOverwriteAtPath:path newData:newVal + writeId:[transaction.currentWriteId integerValue] + isVisible:transaction.applyLocally]; + [self.eventRaiser raiseEvents:events]; + + [self sendAllReadyTransactions]; + } +} + +/** + * @param writeIdsToExclude A specific set to exclude + */ +- (id) latestStateAtPath:(FPath *)path excludeWriteIds:(NSArray *)writeIdsToExclude { + id latestState = [self.serverSyncTree calcCompleteEventCacheAtPath:path excludeWriteIds:writeIdsToExclude]; + return latestState ? latestState : [FEmptyNode emptyNode]; +} + +/** + * Sends any already-run transactions that aren't waiting for outstanding transactions to complete. + * + * Externally, call the version with no arguments. + * Internally, calls itself recursively with a particular transactionQueueTree node to recurse through the tree + */ +- (void) sendAllReadyTransactions { + FTree* node = self.transactionQueueTree; + + [self pruneCompletedTransactionsBelowNode:node]; + [self sendReadyTransactionsForTree:node]; +} + +- (void) sendReadyTransactionsForTree:(FTree *)node { + NSMutableArray* queue = [node getValue]; + if (queue != nil) { + queue = [self buildTransactionQueueAtNode:node]; + NSAssert([queue count] > 0, @"Sending zero length transaction queue"); + + NSUInteger notRunIndex = [queue indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { + return ((FTupleTransaction*)obj).status != FTransactionRun; + }]; + + // If they're all run (and not sent), we can send them. Else, we must wait. + if (notRunIndex == NSNotFound) { + [self sendTransactionQueue:queue atPath:node.path]; + } + } else if ([node hasChildren]) { + [node forEachChild:^(FTree *child) { + [self sendReadyTransactionsForTree:child]; + }]; + } +} + +/** + * Given a list of run transactions, send them to the server and then handle the result (success or failure). + */ +- (void) sendTransactionQueue:(NSMutableArray *)queue atPath:(FPath *)path { + // Mark transactions as sent and bump the retry count + NSMutableArray *writeIdsToExclude = [[NSMutableArray alloc] init]; + for (FTupleTransaction *transaction in queue) { + [writeIdsToExclude addObject:transaction.currentWriteId]; + } + id latestState = [self latestStateAtPath:path excludeWriteIds:writeIdsToExclude]; + id snapToSend = latestState; + NSString *latestHash = [latestState dataHash]; + for (FTupleTransaction* transaction in queue) { + NSAssert(transaction.status == FTransactionRun, @"[FRepo sendTransactionQueue:] items in queue should all be run."); + FFLog(@"I-RDB038021", @"Transaction at %@ set to SENT", transaction.path); + transaction.status = FTransactionSent; + transaction.retryCount++; + FPath *relativePath = [FPath relativePathFrom:path to:transaction.path]; + // If we've gotten to this point, the output snapshot must be defined. + snapToSend = [snapToSend updateChild:relativePath withNewChild:transaction.currentOutputSnapshotRaw]; + } + + id dataToSend = [snapToSend valForExport:YES]; + NSString *pathToSend = [path description]; + latestHash = self.hijackHash ? @"badhash" : latestHash; + + // Send the put + [self.connection putData:dataToSend forPath:pathToSend withHash:latestHash withCallback:^(NSString *status, NSString *errorReason) { + FFLog(@"I-RDB038022", @"Transaction put response: %@ : %@", pathToSend, status); + + NSMutableArray *events = [[NSMutableArray alloc] init]; + if ([status isEqualToString:kFWPResponseForActionStatusOk]) { + // Queue up the callbacks and fire them after cleaning up all of our transaction state, since + // the callback could trigger more transactions or sets. + NSMutableArray *callbacks = [[NSMutableArray alloc] init]; + for (FTupleTransaction *transaction in queue) { + transaction.status = FTransactionCompleted; + [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue] + revert:NO + persist:NO + clock:self.serverClock]]; + if (transaction.onComplete) { + // We never unset the output snapshot, and given that this transaction is complete, it should be set + id node = transaction.currentOutputSnapshotResolved; + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:node]; + FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path]; + FIRDataSnapshot *snapshot = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:indexedNode]; + fbt_void_void cb = ^{ + transaction.onComplete(nil, YES, snapshot); + }; + [callbacks addObject:[cb copy]]; + } + transaction.unwatcher(); + } + + // Now remove the completed transactions. + [self pruneCompletedTransactionsBelowNode:[self.transactionQueueTree subTree:path]]; + // There may be pending transactions that we can now send. + [self sendAllReadyTransactions]; + + // Finally, trigger onComplete callbacks + [self.eventRaiser raiseCallbacks:callbacks]; + } else { + // transactions are no longer sent. Update their status appropriately. + if ([status isEqualToString:kFWPResponseForActionStatusDataStale]) { + for (FTupleTransaction *transaction in queue) { + if (transaction.status == FTransactionSentNeedsAbort) { + transaction.status = FTransactionNeedsAbort; + } else { + transaction.status = FTransactionRun; + } + } + } else { + FFWarn(@"I-RDB038023", @"runTransactionBlock: at %@ failed: %@", path, status); + for (FTupleTransaction *transaction in queue) { + transaction.status = FTransactionNeedsAbort; + [transaction setAbortStatus:status reason:errorReason]; + } + } + } + + [self rerunTransactionsForPath:path]; + [self.eventRaiser raiseEvents:events]; + }]; +} + +/** + * Finds all transactions dependent on the data at changed Path and reruns them. + * + * Should be called any time cached data changes. + * + * Return the highest path that was affected by rerunning transactions. This is the path at which events need to + * be raised for. + */ +- (FPath *) rerunTransactionsForPath:(FPath *)changedPath { + // For the common case that there are no transactions going on, skip all this! + if ([self.transactionQueueTree isEmpty]) { + return changedPath; + } else { + FTree* rootMostTransactionNode = [self getAncestorTransactionNodeForPath:changedPath]; + FPath* path = rootMostTransactionNode.path; + + NSArray* queue = [self buildTransactionQueueAtNode:rootMostTransactionNode]; + [self rerunTransactionQueue:queue atPath:path]; + + return path; + } +} + +/** + * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot). + */ +- (void) rerunTransactionQueue:(NSArray *)queue atPath:(FPath *)path { + if (queue.count == 0) { + return; // nothing to do + } + + // Queue up the callbacks and fire them after cleaning up all of our transaction state, since + // the callback could trigger more transactions or sets. + NSMutableArray *events = [[NSMutableArray alloc] init]; + NSMutableArray *callbacks = [[NSMutableArray alloc] init]; + + // Ignore, by default, all of the sets in this queue, since we're re-running all of them. However, we want to include + // the results of new sets triggered as part of this re-run, so we don't want to ignore a range, just these specific + // sets. + NSMutableArray *writeIdsToExclude = [[NSMutableArray alloc] init]; + for (FTupleTransaction *transaction in queue) { + [writeIdsToExclude addObject:transaction.currentWriteId]; + } + + for (FTupleTransaction* transaction in queue) { + FPath* relativePath __unused = [FPath relativePathFrom:path to:transaction.path]; + BOOL abortTransaction = NO; + NSAssert(relativePath != nil, @"[FRepo rerunTransactionsQueue:] relativePath should not be null."); + + if (transaction.status == FTransactionNeedsAbort) { + abortTransaction = YES; + if (![transaction.abortStatus isEqualToString:kFErrorWriteCanceled]) { + NSArray *ackEvents = [self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue] + revert:YES + persist:NO + clock:self.serverClock]; + [events addObjectsFromArray:ackEvents]; + } + } else if (transaction.status == FTransactionRun) { + if (transaction.retryCount >= kFTransactionMaxRetries) { + abortTransaction = YES; + [transaction setAbortStatus:kFTransactionTooManyRetries reason:nil]; + [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue] + revert:YES + persist:NO + clock:self.serverClock]]; + } else { + // This code reruns a transaction + id currentNode = [self latestStateAtPath:transaction.path excludeWriteIds:writeIdsToExclude]; + transaction.currentInputSnapshot = currentNode; + FIRMutableData * mutableCurrent = [[FIRMutableData alloc] initWithNode:currentNode]; + FIRTransactionResult * result = transaction.update(mutableCurrent); + if (result.isSuccess) { + NSNumber *oldWriteId = transaction.currentWriteId; + NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock]; + + id newVal = [result.update nodeValue]; + id newValResolved = [FServerValues resolveDeferredValueSnapshot:newVal withServerValues:serverValues]; + + transaction.currentOutputSnapshotRaw = newVal; + transaction.currentOutputSnapshotResolved = newValResolved; + + transaction.currentWriteId = [NSNumber numberWithInteger:[self nextWriteId]]; + // Mutates writeIdsToExclude in place + [writeIdsToExclude removeObject:oldWriteId]; + [events addObjectsFromArray:[self.serverSyncTree applyUserOverwriteAtPath:transaction.path + newData:transaction.currentOutputSnapshotResolved + writeId:[transaction.currentWriteId integerValue] + isVisible:transaction.applyLocally]]; + [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[oldWriteId integerValue] + revert:YES + persist:NO + clock:self.serverClock]]; + } else { + abortTransaction = YES; + // The user aborted the transaction. JS treats ths as a "nodata" abort, but it's not an error, so we don't send them an error. + [transaction setAbortStatus:nil reason:nil]; + [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue] + revert:YES + persist:NO + clock:self.serverClock]]; + } + } + } + + [self.eventRaiser raiseEvents:events]; + events = nil; + + if (abortTransaction) { + // Abort + transaction.status = FTransactionCompleted; + transaction.unwatcher(); + if (transaction.onComplete) { + FIRDatabaseReference * ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path]; + FIndexedNode *lastInput = [FIndexedNode indexedNodeWithNode:transaction.currentInputSnapshot]; + FIRDataSnapshot * snap = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:lastInput]; + fbt_void_void cb = ^{ + // Unlike JS, no need to check for "nodata" because ObjC has abortError = nil + transaction.onComplete(transaction.abortError, NO, snap); + }; + [callbacks addObject:[cb copy]]; + } + } + } + + // Note: unlike current js client, we don't need to preserve priority. Users can set priority via FIRMutableData + + // Clean up completed transactions. + [self pruneCompletedTransactionsBelowNode:self.transactionQueueTree]; + + // Now fire callbacks, now that we're in a good, known state. + [self.eventRaiser raiseCallbacks:callbacks]; + + // Try to send the transaction result to the server + [self sendAllReadyTransactions]; +} + +- (FTree *) getAncestorTransactionNodeForPath:(FPath *)path { + FTree* transactionNode = self.transactionQueueTree; + + while (![path isEmpty] && [transactionNode getValue] == nil) { + NSString* front = [path getFront]; + transactionNode = [transactionNode subTree:[[FPath alloc] initWith:front]]; + path = [path popFront]; + } + + return transactionNode; +} + +- (NSMutableArray *) buildTransactionQueueAtNode:(FTree *)node { + NSMutableArray* queue = [[NSMutableArray alloc] init]; + [self aggregateTransactionQueuesForNode:node andQueue:queue]; + + [queue sortUsingComparator:^NSComparisonResult(FTupleTransaction* obj1, FTupleTransaction* obj2) { + return [obj1.order compare:obj2.order]; + }]; + + return queue; +} + +- (void) aggregateTransactionQueuesForNode:(FTree *)node andQueue:(NSMutableArray *)queue { + NSArray* nodeQueue = [node getValue]; + [queue addObjectsFromArray:nodeQueue]; + + [node forEachChild:^(FTree *child) { + [self aggregateTransactionQueuesForNode:child andQueue:queue]; + }]; +} + +/** + * Remove COMPLETED transactions at or below this node in the transactionQueueTree + */ +- (void) pruneCompletedTransactionsBelowNode:(FTree *)node { + NSMutableArray* queue = [node getValue]; + if (queue != nil) { + int i = 0; + // remove all of the completed transactions from the queue + while (i < queue.count) { + FTupleTransaction* transaction = [queue objectAtIndex:i]; + if (transaction.status == FTransactionCompleted) { + [queue removeObjectAtIndex:i]; + } else { + i++; + } + } + if (queue.count > 0) { + [node setValue:queue]; + } else { + [node setValue:nil]; + } + } + + [node forEachChildMutationSafe:^(FTree *child) { + [self pruneCompletedTransactionsBelowNode:child]; + }]; +} + +/** + * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a setValue: or + * updateChildValues: since we consider them incompatible with transactions + * + * @param path path for which we want to abort related transactions. + */ +- (FPath *) abortTransactionsAtPath:(FPath *)path error:(NSString *)error { + // For the common case that there are no transactions going on, skip all this! + if ([self.transactionQueueTree isEmpty]) { + return path; + } else { + FPath* affectedPath = [self getAncestorTransactionNodeForPath:path].path; + + FTree* transactionNode = [self.transactionQueueTree subTree:path]; + [transactionNode forEachAncestor:^BOOL(FTree *ancestor) { + [self abortTransactionsAtNode:ancestor error:error]; + return NO; + }]; + + [self abortTransactionsAtNode:transactionNode error:error]; + + [transactionNode forEachDescendant:^(FTree *child) { + [self abortTransactionsAtNode:child error:error]; + }]; + + return affectedPath; + } +} + +/** + * Abort transactions stored in this transactions queue node. + * + * @param node Node to abort transactions for. + */ +- (void) abortTransactionsAtNode:(FTree *)node error:(NSString *)error { + NSMutableArray* queue = [node getValue]; + if (queue != nil) { + + // Queue up the callbacks and fire them after cleaning up all of our transaction state, since + // can be immediately aborted and removed. + NSMutableArray* callbacks = [[NSMutableArray alloc] init]; + + // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones + // can be immediately aborted and removed + NSMutableArray *events = [[NSMutableArray alloc] init]; + int lastSent = -1; + // Note: all of the sent transactions will be at the front of the queue, so safe to increment lastSent + for (FTupleTransaction* transaction in queue) { + if (transaction.status == FTransactionSentNeedsAbort) { + // No-op. already marked. + } else if (transaction.status == FTransactionSent) { + // Mark this transaction for abort when it returns + lastSent++; + transaction.status = FTransactionSentNeedsAbort; + [transaction setAbortStatus:error reason:nil]; + } else { + // we can abort this immediately + transaction.unwatcher(); + if ([error isEqualToString:kFTransactionSet]) { + [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue] + revert:YES + persist:NO + clock:self.serverClock]]; + } else { + // If it was cancelled it was already removed from the sync tree, no need to ack + NSAssert([error isEqualToString:kFErrorWriteCanceled], nil); + } + + if (transaction.onComplete) { + NSError* abortReason = [FUtilities errorForStatus:error andReason:nil]; + FIRDataSnapshot * snapshot = nil; + fbt_void_void cb = ^{ + transaction.onComplete(abortReason, NO, snapshot); + }; + [callbacks addObject:[cb copy]]; + } + } + } + if (lastSent == -1) { + // We're not waiting for any sent transactions. We can clear the queue. + [node setValue:nil]; + } else { + // Remove the transactions we aborted + NSRange theRange; + theRange.location = lastSent + 1; + theRange.length = queue.count - theRange.location; + [queue removeObjectsInRange:theRange]; + } + + // Now fire the callbacks + [self.eventRaiser raiseEvents:events]; + [self.eventRaiser raiseCallbacks:callbacks]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.h new file mode 100644 index 0000000..433bf35 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FRepoInfo : NSObject + +@property (nonatomic, readonly, strong) NSString* host; +@property (nonatomic, readonly, strong) NSString* namespace; +@property (nonatomic, strong) NSString* internalHost; +@property (nonatomic, readonly) bool secure; + +- (id) initWithHost:(NSString*)host isSecure:(bool)secure withNamespace:(NSString*)namespace; + +- (NSString *) connectionURLWithLastSessionID:(NSString*)lastSessionID; +- (NSString *) connectionURL; +- (void) clearInternalHostCache; +- (BOOL) isDemoHost; +- (BOOL) isCustomHost; + +- (id)copyWithZone:(NSZone *)zone; +- (NSUInteger)hash; +- (BOOL)isEqual:(id)anObject; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.m new file mode 100644 index 0000000..925163e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoInfo.m @@ -0,0 +1,134 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRepoInfo.h" +#import "FConstants.h" + +@interface FRepoInfo () + +@property (nonatomic, strong) NSString *domain; + +@end + + +@implementation FRepoInfo + +@synthesize namespace; +@synthesize host; +@synthesize internalHost; +@synthesize secure; +@synthesize domain; + +- (id) initWithHost:(NSString*)aHost isSecure:(bool)isSecure withNamespace:(NSString*)aNamespace { + self = [super init]; + if (self) { + host = aHost; + domain = [host substringFromIndex:[host rangeOfString:@"."].location+1]; + secure = isSecure; + namespace = aNamespace; + + // Get cached internal host if it exists + NSString* internalHostKey = [NSString stringWithFormat:@"firebase:host:%@", self.host]; + NSString* cachedInternalHost = [[NSUserDefaults standardUserDefaults] stringForKey:internalHostKey]; + if (cachedInternalHost != nil) { + internalHost = cachedInternalHost; + } else { + internalHost = self.host; + } + } + return self; +} + +- (NSString *)description { + // The namespace is encoded in the hostname, so we can just return this. + return [NSString stringWithFormat:@"http%@://%@", (self.secure ? @"s" : @""), self.host]; +} + +- (void) setInternalHost:(NSString *)newHost { + if (![internalHost isEqualToString:newHost]) { + internalHost = newHost; + + // Cache the internal host so we don't need to redirect later on + NSString* internalHostKey = [NSString stringWithFormat:@"firebase:host:%@", self.host]; + NSUserDefaults* cache = [NSUserDefaults standardUserDefaults]; + [cache setObject:internalHost forKey:internalHostKey]; + [cache synchronize]; + } +} + +- (void) clearInternalHostCache { + internalHost = self.host; + + // Remove the cached entry + NSString* internalHostKey = [NSString stringWithFormat:@"firebase:host:%@", self.host]; + NSUserDefaults* cache = [NSUserDefaults standardUserDefaults]; + [cache removeObjectForKey:internalHostKey]; + [cache synchronize]; +} + +- (BOOL) isDemoHost { + return [self.domain isEqualToString:@"firebaseio-demo.com"]; +} + +- (BOOL) isCustomHost { + return ![self.domain isEqualToString:@"firebaseio-demo.com"] && ![self.domain isEqualToString:@"firebaseio.com"]; +} + + +- (NSString *) connectionURL { + return [self connectionURLWithLastSessionID:nil]; +} + +- (NSString *) connectionURLWithLastSessionID:(NSString*)lastSessionID { + NSString *scheme; + if (self.secure) { + scheme = @"wss"; + } else { + scheme = @"ws"; + } + NSString *url = [NSString stringWithFormat:@"%@://%@/.ws?%@=%@&ns=%@", + scheme, + self.internalHost, + kWireProtocolVersionParam, + kWebsocketProtocolVersion, + self.namespace]; + + if (lastSessionID != nil) { + url = [NSString stringWithFormat:@"%@&ls=%@", url, lastSessionID]; + } + return url; +} + +- (id)copyWithZone:(NSZone *)zone; { + return self; // Immutable +} + +- (NSUInteger)hash { + NSUInteger result = host.hash; + result = 31 * result + (secure ? 1 : 0); + result = 31 * result + namespace.hash; + result = 31 * result + host.hash; + return result; +} + +- (BOOL)isEqual:(id)anObject { + if (![anObject isKindOfClass:[FRepoInfo class]]) return NO; + FRepoInfo *other = (FRepoInfo *)anObject; + return secure == other.secure && [host isEqualToString:other.host] && + [namespace isEqualToString:other.namespace]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.h new file mode 100644 index 0000000..c492861 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.h @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FRepoInfo.h" +#import "FRepo.h" +#import "FIRDatabaseConfig.h" + +@interface FRepoManager : NSObject + ++ (FRepo *) getRepo:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config; ++ (FRepo *) createRepo:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config database:(FIRDatabase *)database; ++ (void) interruptAll; ++ (void) interrupt:(FIRDatabaseConfig *)config; ++ (void) resumeAll; ++ (void) resume:(FIRDatabaseConfig *)config; ++ (void) disposeRepos:(FIRDatabaseConfig *)config; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.m new file mode 100644 index 0000000..31c3efc --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepoManager.m @@ -0,0 +1,135 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FRepoManager.h" +#import "FRepo.h" +#import "FIRDatabaseQuery_Private.h" +#import "FAtomicNumber.h" +#import "FIRDatabaseConfig_Private.h" +#import "FIRDatabase_Private.h" + +@implementation FRepoManager + +typedef NSMutableDictionary *> + FRepoDictionary; + ++ (FRepoDictionary *)configs { + static dispatch_once_t pred = 0; + static FRepoDictionary *configs; + dispatch_once(&pred, ^{ + configs = [NSMutableDictionary dictionary]; + }); + return configs; +} + +/** + * Used for legacy unit tests. The public API should go through FirebaseDatabase which + * calls createRepo. + */ ++ (FRepo *) getRepo:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config { + [config freeze]; + FRepoDictionary *configs = [FRepoManager configs]; + @synchronized(configs) { + NSMutableDictionary *repos = configs[config.sessionIdentifier]; + if (!repos || repos[repoInfo] == nil) { + // Calling this should create the repo. + [FIRDatabase createDatabaseForTests:repoInfo config:config]; + } + + return configs[config.sessionIdentifier][repoInfo]; + } +} + ++ (FRepo *) createRepo:(FRepoInfo *)repoInfo config:(FIRDatabaseConfig *)config database:(FIRDatabase *)database { + [config freeze]; + FRepoDictionary *configs = [FRepoManager configs]; + @synchronized(configs) { + NSMutableDictionary *repos = + configs[config.sessionIdentifier]; + if (!repos) { + repos = [NSMutableDictionary dictionary]; + configs[config.sessionIdentifier] = repos; + } + FRepo *repo = repos[repoInfo]; + if (repo == nil) { + repo = [[FRepo alloc] initWithRepoInfo:repoInfo config:config database:database]; + repos[repoInfo] = repo; + return repo; + } else { + [NSException raise:@"RepoExists" format:@"createRepo called for Repo that already exists."]; + return nil; + } + } +} + ++ (void) interrupt:(FIRDatabaseConfig *)config { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + FRepoDictionary *configs = [FRepoManager configs]; + NSMutableDictionary *repos = configs[config.sessionIdentifier]; + for (FRepo *repo in [repos allValues]) { + [repo interrupt]; + } + }); +} + ++ (void) interruptAll { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + FRepoDictionary *configs = [FRepoManager configs]; + for (NSMutableDictionary *repos in [configs allValues]) { + for (FRepo *repo in [repos allValues]) { + [repo interrupt]; + } + } + }); +} + ++ (void) resume:(FIRDatabaseConfig *)config { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + FRepoDictionary *configs = [FRepoManager configs]; + NSMutableDictionary *repos = configs[config.sessionIdentifier]; + for (FRepo *repo in [repos allValues]) { + [repo resume]; + } + }); +} + ++ (void) resumeAll { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + FRepoDictionary *configs = [FRepoManager configs]; + for (NSMutableDictionary *repos in [configs allValues]) { + for (FRepo *repo in [repos allValues]) { + [repo resume]; + } + } + }); +} + ++ (void)disposeRepos:(FIRDatabaseConfig *)config { + // Do this synchronously to make sure we release our references to LevelDB before returning, allowing LevelDB + // to close and release its exclusive locks. + dispatch_sync([FIRDatabaseQuery sharedQueue], ^{ + FFLog(@"I-RDB040001", @"Disposing all repos for Config with name %@", config.sessionIdentifier); + NSMutableDictionary *configs = [FRepoManager configs]; + for (FRepo* repo in [configs[config.sessionIdentifier] allValues]) { + [repo dispose]; + } + [configs removeObjectForKey:config.sessionIdentifier]; + }); +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo_Private.h new file mode 100644 index 0000000..109edac --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FRepo_Private.h @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRepo.h" +#import "FSparseSnapshotTree.h" + +@class FSyncTree; +@class FAtomicNumber; +@class FEventRaiser; +@class FSnapshotHolder; + +@interface FRepo () + +- (void) runOnDisconnectEvents; + +@property (nonatomic, strong) FRepoInfo* repoInfo; +@property (nonatomic, strong) FPersistentConnection* connection; +@property (nonatomic, strong) FSnapshotHolder* infoData; +@property (nonatomic, strong) FSparseSnapshotTree* onDisconnect; +@property (nonatomic, strong) FEventRaiser *eventRaiser; +@property (nonatomic, strong) FSyncTree *serverSyncTree; + +// For testing. +@property (nonatomic) long dataUpdateCount; +@property (nonatomic) long rangeMergeUpdateCount; + +- (NSInteger)nextWriteId; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.h new file mode 100644 index 0000000..2540c12 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FSparseSnapshotTree.h" +#import "FNode.h" +#import "FCompoundWrite.h" +#import "FClock.h" + +@interface FServerValues : NSObject + ++ (NSDictionary*) generateServerValues:(id)clock; ++ (id) resolveDeferredValueCompoundWrite:(FCompoundWrite*)write withServerValues:(NSDictionary*)serverValues; ++ (id) resolveDeferredValueSnapshot:(id)node withServerValues:(NSDictionary*)serverValues; ++ (id) resolveDeferredValueTree:(FSparseSnapshotTree*)tree withServerValues:(NSDictionary*)serverValues; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.m new file mode 100644 index 0000000..89ee5d0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FServerValues.m @@ -0,0 +1,93 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FServerValues.h" +#import "FConstants.h" +#import "FLeafNode.h" +#import "FChildrenNode.h" +#import "FSnapshotUtilities.h" + +@implementation FServerValues + ++ (NSDictionary*) generateServerValues:(id)clock { + long long millis = (long long)([clock currentTime] * 1000); + return @{ @"timestamp": [NSNumber numberWithLongLong:millis] }; +} + ++ (id) resolveDeferredValue:(id)val withServerValues:(NSDictionary*)serverValues { + if ([val isKindOfClass:[NSDictionary class]]) { + NSDictionary* dict = val; + if (dict[kServerValueSubKey] != nil) { + NSString* serverValueType = [dict objectForKey:kServerValueSubKey]; + if (serverValues[serverValueType] != nil) { + return [serverValues objectForKey:serverValueType]; + } else { + // TODO: Throw unrecognizedServerValue error here + } + } + } + return val; +} + ++ (FCompoundWrite *) resolveDeferredValueCompoundWrite:(FCompoundWrite *)write withServerValues:(NSDictionary *)serverValues { + __block FCompoundWrite *resolved = write; + [write enumerateWrites:^(FPath *path, id node, BOOL *stop) { + id resolvedNode = [FServerValues resolveDeferredValueSnapshot:node withServerValues:serverValues]; + // Node actually changed, use pointer inequality here + if (resolvedNode != node) { + resolved = [resolved addWrite:resolvedNode atPath:path]; + } + }]; + return resolved; +} + ++ (id) resolveDeferredValueTree:(FSparseSnapshotTree*)tree withServerValues:(NSDictionary*)serverValues { + FSparseSnapshotTree* resolvedTree = [[FSparseSnapshotTree alloc] init]; + [tree forEachTreeAtPath:[FPath empty] do:^(FPath* path, id node) { + [resolvedTree rememberData:[FServerValues resolveDeferredValueSnapshot:node withServerValues:serverValues] onPath:path]; + }]; + return resolvedTree; +} + ++ (id) resolveDeferredValueSnapshot:(id)node withServerValues:(NSDictionary*)serverValues { + id priorityVal = [FServerValues resolveDeferredValue:[[node getPriority] val] withServerValues:serverValues]; + id priority = [FSnapshotUtilities nodeFrom:priorityVal]; + + if ([node isLeafNode]) { + id value = [self resolveDeferredValue:[node val] withServerValues:serverValues]; + if (![value isEqual:[node val]] || ![priority isEqual:[node getPriority]]) { + return [[FLeafNode alloc] initWithValue:value withPriority:priority]; + } else { + return node; + } + } else { + __block FChildrenNode* newNode = node; + if (![priority isEqual:[node getPriority]]) { + newNode = [newNode updatePriority:priority]; + } + + [node enumerateChildrenUsingBlock:^(NSString *childKey, id childNode, BOOL *stop) { + id newChildNode = [FServerValues resolveDeferredValueSnapshot:childNode withServerValues:serverValues]; + if (![newChildNode isEqual:childNode]) { + newNode = [newNode updateImmediateChild:childKey withNewChild:newChildNode]; + } + }]; + return newNode; + } +} + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.h new file mode 100644 index 0000000..9a1d871 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@interface FSnapshotHolder : NSObject + +- (id) getNode:(FPath *)path; +- (void) updateSnapshot:(FPath *)path withNewSnapshot:(id)newSnapshotNode; + +@property (nonatomic, strong) id rootNode; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.m new file mode 100644 index 0000000..25c4625 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSnapshotHolder.m @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FSnapshotHolder.h" +#import "FEmptyNode.h" + +@interface FSnapshotHolder() + + +@end + +@implementation FSnapshotHolder + +@synthesize rootNode; + +- (id)init +{ + self = [super init]; + if (self) { + self.rootNode = [FEmptyNode emptyNode]; + } + return self; +} + +- (id) getNode:(FPath *)path { + return [self.rootNode getChild:path]; +} + +- (void) updateSnapshot:(FPath *)path withNewSnapshot:(id)newSnapshotNode { + self.rootNode = [self.rootNode updateChild:path withNewChild:newSnapshotNode]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.h new file mode 100644 index 0000000..b860c9d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" +#import "FPath.h" +#import "FTypedefs_Private.h" + +@class FSparseSnapshotTree; + +typedef void (^fbt_void_nsstring_sstree) (NSString*, FSparseSnapshotTree*); + +@interface FSparseSnapshotTree : NSObject + +- (id) findPath:(FPath *)path; +- (void) rememberData:(id)data onPath:(FPath *)path; +- (BOOL) forgetPath:(FPath *)path; +- (void) forEachTreeAtPath:(FPath *)prefixPath do:(fbt_void_path_node)func; +- (void) forEachChild:(fbt_void_nsstring_sstree)func; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.m new file mode 100644 index 0000000..1f16888 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSparseSnapshotTree.m @@ -0,0 +1,144 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FSparseSnapshotTree.h" +#import "FChildrenNode.h" + +@interface FSparseSnapshotTree () { + id value; + NSMutableDictionary* children; +} + +@end + +@implementation FSparseSnapshotTree + +- (id) init { + self = [super init]; + if (self) { + value = nil; + children = nil; + } + return self; +} + +- (id) findPath:(FPath *)path { + if (value != nil) { + return [value getChild:path]; + } else if (![path isEmpty] && children != nil) { + NSString* childKey = [path getFront]; + path = [path popFront]; + FSparseSnapshotTree* childTree = children[childKey]; + if (childTree != nil) { + return [childTree findPath:path]; + } else { + return nil; + } + } else { + return nil; + } +} + +- (void) rememberData:(id)data onPath:(FPath *)path { + if ([path isEmpty]) { + value = data; + children = nil; + } else if (value != nil) { + value = [value updateChild:path withNewChild:data]; + } else { + if (children == nil) { + children = [[NSMutableDictionary alloc] init]; + } + + NSString* childKey = [path getFront]; + if (children[childKey] == nil) { + children[childKey] = [[FSparseSnapshotTree alloc] init]; + } + + FSparseSnapshotTree* child = children[childKey]; + path = [path popFront]; + [child rememberData:data onPath:path]; + } +} + +- (BOOL) forgetPath:(FPath *)path { + if ([path isEmpty]) { + value = nil; + children = nil; + return YES; + } else { + if (value != nil) { + if ([value isLeafNode]) { + // non-empty path at leaf. the path leads to nowhere + return NO; + } else { + id tmp = value; + value = nil; + + [tmp enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + [self rememberData:node onPath:[[FPath alloc] initWith:key]]; + }]; + + // we've cleared out the value and set children. Call ourself again to hit the next case + return [self forgetPath:path]; + } + } else if (children != nil) { + NSString* childKey = [path getFront]; + path = [path popFront]; + + if (children[childKey] != nil) { + FSparseSnapshotTree* child = children[childKey]; + BOOL safeToRemove = [child forgetPath:path]; + if (safeToRemove) { + [children removeObjectForKey:childKey]; + } + } + + if ([children count] == 0) { + children = nil; + return YES; + } else { + return NO; + } + } else { + return YES; + } + } +} + +- (void) forEachTreeAtPath:(FPath *)prefixPath do:(fbt_void_path_node)func { + if (value != nil) { + func(prefixPath, value); + } else { + [self forEachChild:^(NSString* key, FSparseSnapshotTree* tree) { + FPath* path = [prefixPath childFromString:key]; + [tree forEachTreeAtPath:path do:func]; + }]; + } +} + + +- (void) forEachChild:(fbt_void_nsstring_sstree)func { + if (children != nil) { + for (NSString* key in children) { + FSparseSnapshotTree* tree = [children objectForKey:key]; + func(key, tree); + } + } +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.h new file mode 100644 index 0000000..4e5a4e2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.h @@ -0,0 +1,66 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FOperation; +@class FWriteTreeRef; +@protocol FNode; +@protocol FEventRegistration; +@class FQuerySpec; +@class FChildrenNode; +@class FTupleRemovedQueriesEvents; +@class FView; +@class FPath; +@class FCacheNode; +@class FPersistenceManager; + +@interface FSyncPoint : NSObject + +- (id)initWithPersistenceManager:(FPersistenceManager *)persistence; + +- (BOOL) isEmpty; + +/** +* Returns array of FEvent +*/ +- (NSArray *) applyOperation:(id)operation writesCache:(FWriteTreeRef *)writesCache serverCache:(id)optCompleteServerCache; + +/** +* Returns array of FEvent +*/ +- (NSArray *) addEventRegistration:(id )eventRegistration + forNonExistingViewForQuery:(FQuerySpec *)query + writesCache:(FWriteTreeRef *)writesCache + serverCache:(FCacheNode *)serverCache; + +- (NSArray *) addEventRegistration:(id )eventRegistration + forExistingViewForQuery:(FQuerySpec *)query; + +- (FTupleRemovedQueriesEvents *) removeEventRegistration:(id )eventRegistration + forQuery:(FQuerySpec *)query + cancelError:(NSError *)cancelError; +/** +* Returns array of FViews +*/ +- (NSArray *) queryViews; +- (id) completeServerCacheAtPath:(FPath *)path; +- (FView *) viewForQuery:(FQuerySpec *)query; +- (BOOL) viewExistsForQuery:(FQuerySpec *)query; +- (BOOL) hasCompleteView; +- (FView *) completeView; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.m new file mode 100644 index 0000000..cd429f1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncPoint.m @@ -0,0 +1,257 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FSyncPoint.h" +#import "FOperation.h" +#import "FWriteTreeRef.h" +#import "FNode.h" +#import "FEventRegistration.h" +#import "FIRDatabaseQuery.h" +#import "FChildrenNode.h" +#import "FTupleRemovedQueriesEvents.h" +#import "FView.h" +#import "FOperationSource.h" +#import "FQuerySpec.h" +#import "FQueryParams.h" +#import "FPath.h" +#import "FEmptyNode.h" +#import "FViewCache.h" +#import "FCacheNode.h" +#import "FPersistenceManager.h" +#import "FDataEvent.h" + +/** +* SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to +* maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes +* and user writes (set, transaction, update). +* +* It's responsible for: +* - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). +* - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, +* applyUserOverwrite, etc.) +*/ +@interface FSyncPoint () +/** +* The Views being tracked at this location in the tree, stored as a map where the key is a +* queryParams and the value is the View for that query. +* +* NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). +* +* Maps NSString -> FView +*/ +@property (nonatomic, strong) NSMutableDictionary *views; + +@property (nonatomic, strong) FPersistenceManager *persistenceManager; +@end + +@implementation FSyncPoint + +- (id) initWithPersistenceManager:(FPersistenceManager *)persistence { + self = [super init]; + if (self) { + self.persistenceManager = persistence; + self.views = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (BOOL) isEmpty { + return [self.views count] == 0; +} + +- (NSArray *) applyOperation:(id)operation + toView:(FView *)view + writesCache:(FWriteTreeRef *)writesCache + serverCache:(id)optCompleteServerCache { + FViewOperationResult *result = [view applyOperation:operation writesCache:writesCache serverCache:optCompleteServerCache]; + if (!view.query.loadsAllData) { + NSMutableSet *removed = [NSMutableSet set]; + NSMutableSet *added = [NSMutableSet set]; + [result.changes enumerateObjectsUsingBlock:^(FChange *change, NSUInteger idx, BOOL *stop) { + if (change.type == FIRDataEventTypeChildAdded) { + [added addObject:change.childKey]; + } else if (change.type == FIRDataEventTypeChildRemoved) { + [removed addObject:change.childKey]; + } + }]; + if ([removed count] > 0 || [added count] > 0) { + [self.persistenceManager updateTrackedQueryKeysWithAddedKeys:added removedKeys:removed forQuery:view.query]; + } + } + return result.events; +} + +- (NSArray *) applyOperation:(id )operation writesCache:(FWriteTreeRef *)writesCache serverCache:(id )optCompleteServerCache { + FQueryParams *queryParams = operation.source.queryParams; + if (queryParams != nil) { + FView *view = [self.views objectForKey:queryParams]; + NSAssert(view != nil, @"SyncTree gave us an op for an invalid query."); + return [self applyOperation:operation toView:view writesCache:writesCache serverCache:optCompleteServerCache]; + } else { + NSMutableArray *events = [[NSMutableArray alloc] init]; + [self.views enumerateKeysAndObjectsUsingBlock:^(FQueryParams *key, FView *view, BOOL *stop) { + NSArray *eventsForView = [self applyOperation:operation toView:view writesCache:writesCache serverCache:optCompleteServerCache]; + [events addObjectsFromArray:eventsForView]; + }]; + return events; + } +} + +/** +* Add an event callback for the specified query +* Returns Array of FEvent events to raise. +*/ +- (NSArray *) addEventRegistration:(id )eventRegistration + forNonExistingViewForQuery:(FQuerySpec *)query + writesCache:(FWriteTreeRef *)writesCache + serverCache:(FCacheNode *)serverCache { + NSAssert(self.views[query.params] == nil, @"Found view for query: %@", query.params); + // TODO: make writesCache take flag for complete server node + id eventCache = [writesCache calculateCompleteEventCacheWithCompleteServerCache:serverCache.isFullyInitialized ? serverCache.node : nil]; + BOOL eventCacheComplete; + if (eventCache != nil) { + eventCacheComplete = YES; + } else { + eventCache = [writesCache calculateCompleteEventChildrenWithCompleteServerChildren:serverCache.node]; + eventCacheComplete = NO; + } + + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:eventCache index:query.index]; + FCacheNode *eventCacheNode = [[FCacheNode alloc] initWithIndexedNode:indexed + isFullyInitialized:eventCacheComplete + isFiltered:NO]; + FViewCache *viewCache = [[FViewCache alloc] initWithEventCache:eventCacheNode serverCache:serverCache]; + FView *view = [[FView alloc] initWithQuery:query initialViewCache:viewCache]; + // If this is a non-default query we need to tell persistence our current view of the data + if (!query.loadsAllData) { + NSMutableSet *allKeys = [NSMutableSet set]; + [view.eventCache enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + [allKeys addObject:key]; + }]; + [self.persistenceManager setTrackedQueryKeys:allKeys forQuery:query]; + } + self.views[query.params] = view; + return [self addEventRegistration:eventRegistration forExistingViewForQuery:query]; +} + +- (NSArray *)addEventRegistration:(id)eventRegistration + forExistingViewForQuery:(FQuerySpec *)query { + FView *view = self.views[query.params]; + NSAssert(view != nil, @"No view for query: %@", query); + [view addEventRegistration:eventRegistration]; + return [view initialEvents:eventRegistration]; +} + +/** +* Remove event callback(s). Return cancelEvents if a cancelError is specified. +* +* If query is the default query, we'll check all views for the specified eventRegistration. +* If eventRegistration is nil, we'll remove all callbacks for the specified view(s). +* +* @return FTupleRemovedQueriesEvents removed queries and any cancel events +*/ +- (FTupleRemovedQueriesEvents *) removeEventRegistration:(id )eventRegistration + forQuery:(FQuerySpec *)query + cancelError:(NSError *)cancelError { + NSMutableArray *removedQueries = [[NSMutableArray alloc] init]; + __block NSMutableArray *cancelEvents = [[NSMutableArray alloc] init]; + BOOL hadCompleteView = [self hasCompleteView]; + if ([query isDefault]) { + // When you do [ref removeObserverWithHandle:], we search all views for the registration to remove. + [self.views enumerateKeysAndObjectsUsingBlock:^(FQueryParams *viewQueryParams, FView *view, BOOL *stop) { + [cancelEvents addObjectsFromArray:[view removeEventRegistration:eventRegistration cancelError:cancelError]]; + if ([view isEmpty]) { + [self.views removeObjectForKey:viewQueryParams]; + + // We'll deal with complete views later + if (![view.query loadsAllData]) { + [removedQueries addObject:view.query]; + } + } + }]; + } else { + // remove the callback from the specific view + FView *view = [self.views objectForKey:query.params]; + if (view != nil) { + [cancelEvents addObjectsFromArray:[view removeEventRegistration:eventRegistration cancelError:cancelError]]; + + if ([view isEmpty]) { + [self.views removeObjectForKey:query.params]; + + // We'll deal with complete views later + if (![view.query loadsAllData]) { + [removedQueries addObject:view.query]; + } + } + } + } + + if (hadCompleteView && ![self hasCompleteView]) { + // We removed our last complete view + [removedQueries addObject:[FQuerySpec defaultQueryAtPath:query.path]]; + } + + return [[FTupleRemovedQueriesEvents alloc] initWithRemovedQueries:removedQueries cancelEvents:cancelEvents]; +} + +- (NSArray *) queryViews { + __block NSMutableArray *filteredViews = [[NSMutableArray alloc] init]; + + [self.views enumerateKeysAndObjectsUsingBlock:^(FQueryParams *key, FView *view, BOOL *stop) { + if (![view.query loadsAllData]) { + [filteredViews addObject:view]; + } + }]; + + return filteredViews; +} + +- (id ) completeServerCacheAtPath:(FPath *)path { + __block id serverCache = nil; + [self.views enumerateKeysAndObjectsUsingBlock:^(FQueryParams *key, FView *view, BOOL *stop) { + serverCache = [view completeServerCacheFor:path]; + *stop = (serverCache != nil); + }]; + return serverCache; +} + +- (FView *) viewForQuery:(FQuerySpec *)query { + return [self.views objectForKey:query.params]; +} + +- (BOOL) viewExistsForQuery:(FQuerySpec *)query { + return [self viewForQuery:query] != nil; +} + +- (BOOL) hasCompleteView { + return [self completeView] != nil; +} + +- (FView *) completeView { + __block FView *completeView = nil; + + [self.views enumerateKeysAndObjectsUsingBlock:^(FQueryParams *key, FView *view, BOOL *stop) { + if ([view.query loadsAllData]) { + completeView = view; + *stop = YES; + } + }]; + + return completeView; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.h new file mode 100644 index 0000000..887f721 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.h @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FListenProvider; +@protocol FNode; +@class FPath; +@protocol FEventRegistration; +@protocol FPersistedServerCache; +@class FQuerySpec; +@class FCompoundWrite; +@class FPersistenceManager; +@class FCompoundHash; +@protocol FClock; + +@protocol FSyncTreeHash + +- (NSString *)simpleHash; +- (FCompoundHash *)compoundHash; +- (BOOL)includeCompoundHash; + +@end + +@interface FSyncTree : NSObject + +- (id) initWithListenProvider:(FListenProvider *)provider; +- (id) initWithPersistenceManager:(FPersistenceManager *)persistenceManager + listenProvider:(FListenProvider *)provider; + +// These methods all return NSArray of FEvent +- (NSArray *) applyUserOverwriteAtPath:(FPath *)path newData:(id )newData writeId:(NSInteger)writeId isVisible:(BOOL)visible; +- (NSArray *) applyUserMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren writeId:(NSInteger)writeId; +- (NSArray *) ackUserWriteWithWriteId:(NSInteger)writeId revert:(BOOL)revert persist:(BOOL)persist clock:(id)clock; +- (NSArray *) applyServerOverwriteAtPath:(FPath *)path newData:(id)newData; +- (NSArray *) applyServerMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren; +- (NSArray *) applyServerRangeMergeAtPath:(FPath *)path updates:(NSArray *)ranges; +- (NSArray *) applyTaggedQueryOverwriteAtPath:(FPath *)path newData:(id )newData tagId:(NSNumber *)tagId; +- (NSArray *) applyTaggedQueryMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren tagId:(NSNumber *)tagId; +- (NSArray *) applyTaggedServerRangeMergeAtPath:(FPath *)path updates:(NSArray *)ranges tagId:(NSNumber *)tagId; +- (NSArray *) addEventRegistration:(id)eventRegistration forQuery:(FQuerySpec *)query; +- (NSArray *) removeEventRegistration:(id )eventRegistration forQuery:(FQuerySpec *)query cancelError:(NSError *)cancelError; +- (void)keepQuery:(FQuerySpec *)query synced:(BOOL)keepSynced; +- (NSArray *) removeAllWrites; + +- (id) calcCompleteEventCacheAtPath:(FPath *)path excludeWriteIds:(NSArray *)writeIdsToExclude; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.m new file mode 100644 index 0000000..688a43b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FSyncTree.m @@ -0,0 +1,818 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FSyncTree.h" +#import "FListenProvider.h" +#import "FWriteTree.h" +#import "FNode.h" +#import "FPath.h" +#import "FEventRegistration.h" +#import "FImmutableTree.h" +#import "FOperation.h" +#import "FWriteTreeRef.h" +#import "FOverwrite.h" +#import "FOperationSource.h" +#import "FMerge.h" +#import "FAckUserWrite.h" +#import "FView.h" +#import "FSyncPoint.h" +#import "FEmptyNode.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FSnapshotHolder.h" +#import "FChildrenNode.h" +#import "FTupleRemovedQueriesEvents.h" +#import "FAtomicNumber.h" +#import "FEventRaiser.h" +#import "FListenComplete.h" +#import "FSnapshotUtilities.h" +#import "FCacheNode.h" +#import "FUtilities.h" +#import "FCompoundWrite.h" +#import "FWriteRecord.h" +#import "FPersistenceManager.h" +#import "FKeepSyncedEventRegistration.h" +#import "FServerValues.h" +#import "FCompoundHash.h" +#import "FRangeMerge.h" + +// Size after which we start including the compound hash +static const NSUInteger kFSizeThresholdForCompoundHash = 1024; + +@interface FListenContainer : NSObject + +@property (nonatomic, strong) FView *view; +@property (nonatomic, copy) fbt_nsarray_nsstring onComplete; + +@end + +@implementation FListenContainer + +- (instancetype)initWithView:(FView *)view onComplete:(fbt_nsarray_nsstring)onComplete { + self = [super init]; + if (self != nil) { + self->_view = view; + self->_onComplete = onComplete; + } + return self; +} + +- (id)serverCache { + return self.view.serverCache; +} + +- (FCompoundHash *)compoundHash { + return [FCompoundHash fromNode:[self serverCache]]; +} + +- (NSString *)simpleHash { + return [[self serverCache] dataHash]; +} + +- (BOOL)includeCompoundHash { + return [FSnapshotUtilities estimateSerializedNodeSize:[self serverCache]] > kFSizeThresholdForCompoundHash; +} + +@end + +@interface FSyncTree () + +/** +* Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. +*/ +@property (nonatomic, strong) FImmutableTree *syncPointTree; + +/** +* A tree of all pending user writes (user-initiated set, transactions, updates, etc) +*/ +@property (nonatomic, strong) FWriteTree *pendingWriteTree; + +/** +* Maps tagId -> FTuplePathQueryParams +*/ +@property (nonatomic, strong) NSMutableDictionary *tagToQueryMap; +@property (nonatomic, strong) NSMutableDictionary *queryToTagMap; +@property (nonatomic, strong) FListenProvider *listenProvider; +@property (nonatomic, strong) FPersistenceManager *persistenceManager; +@property (nonatomic, strong) FAtomicNumber *queryTagCounter; +@property (nonatomic, strong) NSMutableSet *keepSyncedQueries; + +@end + +/** +* SyncTree is the central class for managing event callback registration, data caching, views +* (query processing), and event generation. There are typically two SyncTree instances for +* each Repo, one for the normal Firebase data, and one for the .info data. +* +* It has a number of responsibilities, including: +* - Tracking all user event callbacks (registered via addEventRegistration: and removeEventRegistration:). +* - Applying and caching data changes for user setValue:, runTransactionBlock:, and updateChildValues: calls +* (applyUserOverwriteAtPath:, applyUserMergeAtPath:). +* - Applying and caching data changes for server data changes (applyServerOverwriteAtPath:, +* applyServerMergeAtPath:). +* - Generating user-facing events for server and user changes (all of the apply* methods +* return the set of events that need to be raised as a result). +* - Maintaining the appropriate set of server listens to ensure we are always subscribed +* to the correct set of paths and queries to satisfy the current set of user event +* callbacks (listens are started/stopped using the provided listenProvider). +* +* NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual +* events are returned to the caller rather than raised synchronously. +*/ +@implementation FSyncTree + +- (id) initWithListenProvider:(FListenProvider *)provider { + return [self initWithPersistenceManager:nil listenProvider:provider]; +} + +- (id) initWithPersistenceManager:(FPersistenceManager *)persistenceManager listenProvider:(FListenProvider *)provider { + self = [super init]; + if (self) { + self.syncPointTree = [FImmutableTree empty]; + self.pendingWriteTree = [[FWriteTree alloc] init]; + self.tagToQueryMap = [[NSMutableDictionary alloc] init]; + self.queryToTagMap = [[NSMutableDictionary alloc] init]; + self.listenProvider = provider; + self.persistenceManager = persistenceManager; + self.queryTagCounter = [[FAtomicNumber alloc] init]; + self.keepSyncedQueries = [NSMutableSet set]; + } + return self; +} + +#pragma mark - +#pragma mark Apply Operations + +/** +* Apply data changes for a user-generated setValue: runTransactionBlock: updateChildValues:, etc. +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyUserOverwriteAtPath:(FPath *)path newData:(id )newData writeId:(NSInteger)writeId isVisible:(BOOL)visible { + // Record pending write + [self.pendingWriteTree addOverwriteAtPath:path newData:newData writeId:writeId isVisible:visible]; + if (!visible) { + return @[]; + } else { + FOverwrite *operation = [[FOverwrite alloc] initWithSource:[FOperationSource userInstance] path:path snap:newData]; + return [self applyOperationToSyncPoints:operation]; + } +} + +/** +* Apply the data from a user-generated updateChildValues: call +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyUserMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren writeId:(NSInteger)writeId { + // Record pending merge + [self.pendingWriteTree addMergeAtPath:path changedChildren:changedChildren writeId:writeId]; + + FMerge *operation = [[FMerge alloc] initWithSource:[FOperationSource userInstance] path:path children:changedChildren]; + return [self applyOperationToSyncPoints:operation]; +} + +/** + * Acknowledge a pending user write that was previously registered with applyUserOverwriteAtPath: or applyUserMergeAtPath: + * TODO[offline]: Taking a serverClock here is awkward, but server values are awkward. :-( + * @return NSArray of FEvent to raise. + */ +- (NSArray *) ackUserWriteWithWriteId:(NSInteger)writeId revert:(BOOL)revert persist:(BOOL)persist clock:(id)clock { + FWriteRecord *write = [self.pendingWriteTree writeForId:writeId]; + BOOL needToReevaluate = [self.pendingWriteTree removeWriteId:writeId]; + if (write.visible) { + if (persist) { + [self.persistenceManager removeUserWrite:writeId]; + } + if (!revert) { + NSDictionary *serverValues = [FServerValues generateServerValues:clock]; + if ([write isOverwrite]) { + id resolvedNode = [FServerValues resolveDeferredValueSnapshot:write.overwrite withServerValues:serverValues]; + [self.persistenceManager applyUserWrite:resolvedNode toServerCacheAtPath:write.path]; + } else { + FCompoundWrite *resolvedMerge = [FServerValues resolveDeferredValueCompoundWrite:write.merge withServerValues:serverValues]; + [self.persistenceManager applyUserMerge:resolvedMerge toServerCacheAtPath:write.path]; + } + } + } + if (!needToReevaluate) { + return @[]; + } else { + __block FImmutableTree *affectedTree = [FImmutableTree empty]; + if (write.isOverwrite) { + affectedTree = [affectedTree setValue:@YES atPath:[FPath empty]]; + } else { + [write.merge enumerateWrites:^(FPath *path, id node, BOOL *stop) { + affectedTree = [affectedTree setValue:@YES atPath:path]; + }]; + } + FAckUserWrite *operation = [[FAckUserWrite alloc] initWithPath:write.path affectedTree:affectedTree revert:revert]; + return [self applyOperationToSyncPoints:operation]; + } +} + +/** +* Apply new server data for the specified path +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyServerOverwriteAtPath:(FPath *)path newData:(id )newData { + [self.persistenceManager updateServerCacheWithNode:newData forQuery:[FQuerySpec defaultQueryAtPath:path]]; + FOverwrite *operation = [[FOverwrite alloc] initWithSource:[FOperationSource serverInstance] path:path snap:newData]; + return [self applyOperationToSyncPoints:operation]; +} + +/** +* Applied new server data to be merged in at the specified path +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyServerMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren { + [self.persistenceManager updateServerCacheWithMerge:changedChildren atPath:path]; + FMerge *operation = [[FMerge alloc] initWithSource:[FOperationSource serverInstance] path:path children:changedChildren]; + return [self applyOperationToSyncPoints:operation]; +} + +- (NSArray *) applyServerRangeMergeAtPath:(FPath *)path updates:(NSArray *)ranges { + FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path]; + if (syncPoint == nil) { + // Removed view, so it's safe to just ignore this update + return @[]; + } else { + // This could be for any "complete" (unfiltered) view, and if there is more than one complete view, they should + // each have the same cache so it doesn't matter which one we use. + FView *view = [syncPoint completeView]; + if (view != nil) { + id serverNode = [view serverCache]; + for (FRangeMerge *merge in ranges) { + serverNode = [merge applyToNode:serverNode]; + } + return [self applyServerOverwriteAtPath:path newData:serverNode]; + } else { + // There doesn't exist a view for this update, so it was removed and it's safe to just ignore this range + // merge + return @[]; + } + } +} + +/** +* Apply a listen complete to a path +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyListenCompleteAtPath:(FPath *)path { + [self.persistenceManager setQueryComplete:[FQuerySpec defaultQueryAtPath:path]]; + id operation = [[FListenComplete alloc] initWithSource:[FOperationSource serverInstance] path:path]; + return [self applyOperationToSyncPoints:operation]; +} + +/** +* Apply a listen complete to a path +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyTaggedListenCompleteAtPath:(FPath *)path tagId:(NSNumber *)tagId { + FQuerySpec *query = [self queryForTag:tagId]; + if (query != nil) { + [self.persistenceManager setQueryComplete:query]; + FPath *relativePath = [FPath relativePathFrom:query.path to:path]; + id op = [[FListenComplete alloc] initWithSource:[FOperationSource forServerTaggedQuery:query.params] + path:relativePath]; + return [self applyTaggedOperation:op atPath:query.path]; + } else { + // We've already removed the query. No big deal, ignore the update. + return @[]; + } +} + +/** +* Internal helper method to apply tagged operation +*/ +- (NSArray *) applyTaggedOperation:(id)operation atPath:(FPath *)path { + FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path]; + NSAssert(syncPoint != nil, @"Missing sync point for query tag that we're tracking."); + FWriteTreeRef *writesCache = [self.pendingWriteTree childWritesForPath:path]; + return [syncPoint applyOperation:operation writesCache:writesCache serverCache:nil]; +} + +/** +* Apply new server data for the specified tagged query +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyTaggedQueryOverwriteAtPath:(FPath *)path newData:(id )newData tagId:(NSNumber *)tagId { + FQuerySpec *query = [self queryForTag:tagId]; + if (query != nil) { + FPath *relativePath = [FPath relativePathFrom:query.path to:path]; + FQuerySpec *queryToOverwrite = relativePath.isEmpty ? query : [FQuerySpec defaultQueryAtPath:path]; + [self.persistenceManager updateServerCacheWithNode:newData forQuery:queryToOverwrite]; + FOverwrite *operation = [[FOverwrite alloc] initWithSource:[FOperationSource forServerTaggedQuery:query.params] + path:relativePath snap:newData]; + return [self applyTaggedOperation:operation atPath:query.path]; + } else { + // Query must have been removed already + return @[]; + } +} + +/** +* Apply server data to be merged in for the specified tagged query +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) applyTaggedQueryMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren tagId:(NSNumber *)tagId { + FQuerySpec *query = [self queryForTag:tagId]; + if (query != nil) { + FPath *relativePath = [FPath relativePathFrom:query.path to:path]; + [self.persistenceManager updateServerCacheWithMerge:changedChildren atPath:path]; + FMerge *operation = [[FMerge alloc] initWithSource:[FOperationSource forServerTaggedQuery:query.params] + path:relativePath + children:changedChildren]; + return [self applyTaggedOperation:operation atPath:query.path]; + } else { + // We've already removed the query. No big deal, ignore the update. + return @[]; + } +} + +- (NSArray *) applyTaggedServerRangeMergeAtPath:(FPath *)path updates:(NSArray *)ranges tagId:(NSNumber *)tagId { + FQuerySpec *query = [self queryForTag:tagId]; + if (query != nil) { + NSAssert([path isEqual:query.path], @"Tagged update path and query path must match"); + FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path]; + NSAssert(syncPoint != nil, @"Missing sync point for query tag that we're tracking."); + FView *view = [syncPoint viewForQuery:query]; + NSAssert(view != nil, @"Missing view for query tag that we're tracking"); + id serverNode = [view serverCache]; + for (FRangeMerge *merge in ranges) { + serverNode = [merge applyToNode:serverNode]; + } + return [self applyTaggedQueryOverwriteAtPath:path newData:serverNode tagId:tagId]; + } else { + // We've already removed the query. No big deal, ignore the update. + return @[]; + } +} + +/** +* Add an event callback for the specified query +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) addEventRegistration:(id)eventRegistration forQuery:(FQuerySpec *)query { + FPath *path = query.path; + + __block BOOL foundAncestorDefaultView = NO; + [self.syncPointTree forEachOnPath:query.path whileBlock:^BOOL(FPath *pathToSyncPoint, FSyncPoint *syncPoint) { + foundAncestorDefaultView = foundAncestorDefaultView || [syncPoint hasCompleteView]; + return !foundAncestorDefaultView; + }]; + + [self.persistenceManager setQueryActive:query]; + + FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path]; + if (syncPoint == nil) { + syncPoint = [[FSyncPoint alloc] initWithPersistenceManager:self.persistenceManager]; + self.syncPointTree = [self.syncPointTree setValue:syncPoint atPath:path]; + } + + BOOL viewAlreadyExists = [syncPoint viewExistsForQuery:query]; + NSArray *events; + if (viewAlreadyExists) { + events = [syncPoint addEventRegistration:eventRegistration forExistingViewForQuery:query]; + } else { + if (![query loadsAllData]) { + // We need to track a tag for this query + NSAssert(self.queryToTagMap[query] == nil, @"View does not exist, but we have a tag"); + NSNumber *tagId = [self.queryTagCounter getAndIncrement]; + self.queryToTagMap[query] = tagId; + self.tagToQueryMap[tagId] = query; + } + + FWriteTreeRef *writesCache = [self.pendingWriteTree childWritesForPath:path]; + FCacheNode *serverCache = [self serverCacheForQuery:query]; + events = [syncPoint addEventRegistration:eventRegistration + forNonExistingViewForQuery:query + writesCache:writesCache + serverCache:serverCache]; + + // There was no view and no default listen + if (!foundAncestorDefaultView) { + FView *view = [syncPoint viewForQuery:query]; + NSMutableArray *mutableEvents = [events mutableCopy]; + [mutableEvents addObjectsFromArray:[self setupListenerOnQuery:query view:view]]; + events = mutableEvents; + } + } + + return events; +} + +- (FCacheNode *)serverCacheForQuery:(FQuerySpec *)query { + __block id serverCacheNode = nil; + + [self.syncPointTree forEachOnPath:query.path whileBlock:^BOOL(FPath *pathToSyncPoint, FSyncPoint *syncPoint) { + FPath *relativePath = [FPath relativePathFrom:pathToSyncPoint to:query.path]; + serverCacheNode = [syncPoint completeServerCacheAtPath:relativePath]; + return serverCacheNode == nil; + }]; + + FCacheNode *serverCache; + if (serverCacheNode != nil) { + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:serverCacheNode index:query.index]; + serverCache = [[FCacheNode alloc] initWithIndexedNode:indexed isFullyInitialized:YES isFiltered:NO]; + } else { + FCacheNode *persistenceServerCache = [self.persistenceManager serverCacheForQuery:query]; + if (persistenceServerCache.isFullyInitialized) { + serverCache = persistenceServerCache; + } else { + serverCacheNode = [FEmptyNode emptyNode]; + + FImmutableTree *subtree = [self.syncPointTree subtreeAtPath:query.path]; + [subtree forEachChild:^(NSString *childKey, FSyncPoint *childSyncPoint) { + id completeCache = [childSyncPoint completeServerCacheAtPath:[FPath empty]]; + if (completeCache) { + serverCacheNode = [serverCacheNode updateImmediateChild:childKey withNewChild:completeCache]; + } + }]; + // Fill the node with any available children we have + [persistenceServerCache.node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + if (![serverCacheNode hasChild:key]) { + serverCacheNode = [serverCacheNode updateImmediateChild:key withNewChild:node]; + } + }]; + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:serverCacheNode index:query.index]; + serverCache = [[FCacheNode alloc] initWithIndexedNode:indexed isFullyInitialized:NO isFiltered:NO]; + } + } + + return serverCache; +} + +/** +* Remove event callback(s). +* +* If query is the default query, we'll check all queries for the specified eventRegistration. +* If eventRegistration is null, we'll remove all callbacks for the specified query/queries. +* +* @param eventRegistration if nil, all callbacks are removed +* @param cancelError If provided, appropriate cancel events will be returned +* @return NSArray of FEvent to raise. +*/ +- (NSArray *) removeEventRegistration:(id )eventRegistration + forQuery:(FQuerySpec *)query + cancelError:(NSError *)cancelError { + // Find the syncPoint first. Then deal with whether or not it has matching listeners + FPath *path = query.path; + FSyncPoint *maybeSyncPoint = [self.syncPointTree valueAtPath:path]; + NSArray *cancelEvents = @[]; + + // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without + // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and + // not loadsAllData: + if (maybeSyncPoint && ([query isDefault] || [maybeSyncPoint viewExistsForQuery:query])) { + FTupleRemovedQueriesEvents *removedAndEvents = [maybeSyncPoint removeEventRegistration:eventRegistration forQuery:query cancelError:cancelError]; + if ([maybeSyncPoint isEmpty]) { + self.syncPointTree = [self.syncPointTree removeValueAtPath:path]; + } + NSArray *removed = removedAndEvents.removedQueries; + cancelEvents = removedAndEvents.cancelEvents; + + // We may have just removed one of many listeners and can short-circuit this whole process + // We may also not have removed a default listener, in which case all of the descendant listeners should already + // be properly set up. + // + // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData: instead + // of isDefault: + NSUInteger defaultQueryIndex = [removed indexOfObjectPassingTest:^BOOL(FQuerySpec *q, NSUInteger idx, BOOL *stop) { + return [q loadsAllData]; + }]; + BOOL removingDefault = defaultQueryIndex != NSNotFound; + [removed enumerateObjectsUsingBlock:^(FQuerySpec *query, NSUInteger idx, BOOL *stop) { + [self.persistenceManager setQueryInactive:query]; + }]; + NSNumber *covered = [self.syncPointTree findOnPath:path andApplyBlock:^id(FPath *relativePath, FSyncPoint *parentSyncPoint) { + return [NSNumber numberWithBool:[parentSyncPoint hasCompleteView]]; + }]; + + if (removingDefault && ![covered boolValue]) { + FImmutableTree *subtree = [self.syncPointTree subtreeAtPath:path]; + // There are potentially child listeners. Determine what if any listens we need to send before executing + // the removal + if (![subtree isEmpty]) { + // We need to fold over our subtree and collect the listeners to send + NSArray *newViews = [self collectDistinctViewsForSubTree:subtree]; + + // Ok, we've collected all the listens we need. Set them up. + [newViews enumerateObjectsUsingBlock:^(FView *view, NSUInteger idx, BOOL *stop) { + FQuerySpec *newQuery = view.query; + FListenContainer *listenContainer = [self createListenerForView:view]; + self.listenProvider.startListening([self queryForListening:newQuery], [self tagForQuery:newQuery], + listenContainer, listenContainer.onComplete); + }]; + } else { + // There's nothing below us, so nothing we need to start listening on + } + } + + // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query. + // The above block has us covered in terms of making sure we're set up on listens lower in the tree. + // Also, note that if we have a cancelError, it's already been removed at the provider level. + if (![covered boolValue] && [removed count] > 0 && cancelError == nil) { + // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one + // default. Otherwise, we need to iterate through and cancel each individual query + if (removingDefault) { + // We don't tag default listeners + self.listenProvider.stopListening([self queryForListening:query], nil); + } else { + [removed enumerateObjectsUsingBlock:^(FQuerySpec *queryToRemove, NSUInteger idx, BOOL *stop) { + NSNumber *tagToRemove = [self.queryToTagMap objectForKey:queryToRemove]; + self.listenProvider.stopListening([self queryForListening:queryToRemove], tagToRemove); + }]; + } + } + // Now, clear all the tags we're tracking for the removed listens. + [self removeTags:removed]; + } else { + // No-op, this listener must've been already removed + } + return cancelEvents; +} + +- (void)keepQuery:(FQuerySpec *)query synced:(BOOL)keepSynced { + // Only do something if we actually need to add/remove an event registration + if (keepSynced && ![self.keepSyncedQueries containsObject:query]) { + [self addEventRegistration:[FKeepSyncedEventRegistration instance] forQuery:query]; + [self.keepSyncedQueries addObject:query]; + } else if (!keepSynced && [self.keepSyncedQueries containsObject:query]) { + [self removeEventRegistration:[FKeepSyncedEventRegistration instance] forQuery:query cancelError:nil]; + [self.keepSyncedQueries removeObject:query]; + } +} + +- (NSArray *) removeAllWrites { + [self.persistenceManager removeAllUserWrites]; + NSArray *removedWrites = [self.pendingWriteTree removeAllWrites]; + if (removedWrites.count > 0) { + FImmutableTree *affectedTree = [[FImmutableTree empty] setValue:@YES atPath:[FPath empty]]; + return [self applyOperationToSyncPoints:[[FAckUserWrite alloc] initWithPath:[FPath empty] + affectedTree:affectedTree revert:YES]]; + } else { + return @[]; + } +} + +/** +* Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above +* it, but as this is only used by transaction code, that should always be the case anyways. +* +* Note: this method will *include* hidden writes from transaction with applyLocally set to false. +* @param path The path to the data we want +* @param writeIdsToExclude A specific set to be excluded +*/ +- (id ) calcCompleteEventCacheAtPath:(FPath *)path excludeWriteIds:(NSArray *)writeIdsToExclude { + BOOL includeHiddenSets = YES; + FWriteTree *writeTree = self.pendingWriteTree; + id serverCache = [self.syncPointTree findOnPath:path andApplyBlock:^id(FPath *pathSoFar, FSyncPoint *syncPoint) { + FPath *relativePath = [FPath relativePathFrom:pathSoFar to:path]; + id serverCache = [syncPoint completeServerCacheAtPath:relativePath]; + if (serverCache) { + return serverCache; + } else { + return nil; + } + }]; + return [writeTree calculateCompleteEventCacheAtPath:path completeServerCache:serverCache excludeWriteIds:writeIdsToExclude includeHiddenWrites:includeHiddenSets]; +} + +#pragma mark - +#pragma mark Private Methods +/** +* This collapses multiple unfiltered views into a single view, since we only need a single +* listener for them. +* @return NSArray of FView +*/ +- (NSArray *) collectDistinctViewsForSubTree:(FImmutableTree *)subtree { + return [subtree foldWithBlock:^NSArray *(FPath *relativePath, FSyncPoint *maybeChildSyncPoint, NSDictionary *childMap) { + if (maybeChildSyncPoint && [maybeChildSyncPoint hasCompleteView]) { + FView *completeView = [maybeChildSyncPoint completeView]; + return @[completeView]; + } else { + // No complete view here, flatten any deeper listens into an array + NSMutableArray *views = [[NSMutableArray alloc] init]; + if (maybeChildSyncPoint) { + views = [[maybeChildSyncPoint queryViews] mutableCopy]; + } + [childMap enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, NSArray *childViews, BOOL *stop) { + [views addObjectsFromArray:childViews]; + }]; + return views; + } + }]; +} + +/** +* @param queries NSArray of FQuerySpec +*/ +- (void) removeTags:(NSArray *)queries { + [queries enumerateObjectsUsingBlock:^(FQuerySpec *removedQuery, NSUInteger idx, BOOL *stop) { + if (![removedQuery loadsAllData]) { + // We should have a tag for this + NSNumber *removedQueryTag = self.queryToTagMap[removedQuery]; + [self.queryToTagMap removeObjectForKey:removedQuery]; + [self.tagToQueryMap removeObjectForKey:removedQueryTag]; + } + }]; +} + +- (FQuerySpec *) queryForListening:(FQuerySpec *)query { + if (query.loadsAllData && !query.isDefault) { + // We treat queries that load all data as default queries + return [FQuerySpec defaultQueryAtPath:query.path]; + } else { + return query; + } +} + +/** +* For a given new listen, manage the de-duplication of outstanding subscriptions. +* @return NSArray of FEvent events to support synchronous data sources +*/ +- (NSArray *) setupListenerOnQuery:(FQuerySpec *)query view:(FView *)view { + FPath *path = query.path; + NSNumber *tagId = [self tagForQuery:query]; + FListenContainer *listenContainer = [self createListenerForView:view]; + + NSArray *events = self.listenProvider.startListening([self queryForListening:query], tagId, listenContainer, + listenContainer.onComplete); + + FImmutableTree *subtree = [self.syncPointTree subtreeAtPath:path]; + // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we + // may need to shadow other listens as well. + if (tagId != nil) { + NSAssert(![subtree.value hasCompleteView], @"If we're adding a query, it shouldn't be shadowed"); + } else { + // Shadow everything at or below this location, this is a default listener. + NSArray *queriesToStop = [subtree foldWithBlock:^id(FPath *relativePath, FSyncPoint *maybeChildSyncPoint, NSDictionary *childMap) { + if (![relativePath isEmpty] && maybeChildSyncPoint != nil && [maybeChildSyncPoint hasCompleteView]) { + return @[[maybeChildSyncPoint completeView].query]; + } else { + // No default listener here, flatten any deeper queries into an array + NSMutableArray *queries = [[NSMutableArray alloc] init]; + if (maybeChildSyncPoint != nil) { + for (FView *view in [maybeChildSyncPoint queryViews]) { + [queries addObject:view.query]; + } + } + [childMap enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *childQueries, BOOL *stop) { + [queries addObjectsFromArray:childQueries]; + }]; + return queries; + } + }]; + for (FQuerySpec *queryToStop in queriesToStop) { + self.listenProvider.stopListening([self queryForListening:queryToStop], [self tagForQuery:queryToStop]); + } + } + return events; +} + +- (FListenContainer *) createListenerForView:(FView *)view { + FQuerySpec *query = view.query; + NSNumber *tagId = [self tagForQuery:query]; + + FListenContainer *listenContainer = [[FListenContainer alloc] initWithView:view + onComplete:^(NSString *status) { + if ([status isEqualToString:@"ok"]) { + if (tagId != nil) { + return [self applyTaggedListenCompleteAtPath:query.path tagId:tagId]; + } else { + return [self applyListenCompleteAtPath:query.path]; + } + } else { + // If a listen failed, kill all of the listeners here, not just the one that triggered the error. + // Note that this may need to be scoped to just this listener if we change permissions on filtered children + NSError *error = [FUtilities errorForStatus:status andReason:nil]; + FFWarn(@"I-RDB038012", @"Listener at %@ failed: %@", query.path, status); + return [self removeEventRegistration:nil forQuery:query cancelError:error]; + } + }]; + + return listenContainer; +} + +/** +* @return The query associated with the given tag, if we have one +*/ +- (FQuerySpec *) queryForTag:(NSNumber *)tagId { + return self.tagToQueryMap[tagId]; +} + +/** +* @return The tag associated with the given query +*/ +- (NSNumber *) tagForQuery:(FQuerySpec *)query { + return self.queryToTagMap[query]; +} + +#pragma mark - +#pragma mark applyOperation Helpers + +/** +* A helper method that visits all descendant and ancestor SyncPoints, applying the operation. +* +* NOTES: +* - Descendant SyncPoints will be visited first (since we raise events depth-first). + +* - We call applyOperation: on each SyncPoint passing three things: +* 1. A version of the Operation that has been made relative to the SyncPoint location. +* 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. +* 3. A snapshot Node with cached server data, if we have it. + +* - We concatenate all of the events returned by each SyncPoint and return the result. +* +* @return Array of FEvent +*/ +- (NSArray *) applyOperationToSyncPoints:(id)operation { + return [self applyOperationHelper:operation syncPointTree:self.syncPointTree serverCache:nil + writesCache:[self.pendingWriteTree childWritesForPath:[FPath empty]]]; +} + +/** +* Recursive helper for applyOperationToSyncPoints_ +*/ +- (NSArray *) applyOperationHelper:(id)operation syncPointTree:(FImmutableTree *)syncPointTree + serverCache:(id)serverCache writesCache:(FWriteTreeRef *)writesCache { + if ([operation.path isEmpty]) { + return [self applyOperationDescendantsHelper:operation syncPointTree:syncPointTree serverCache:serverCache writesCache:writesCache]; + } else { + FSyncPoint *syncPoint = syncPointTree.value; + + // If we don't have cached server data, see if we can get it from this SyncPoint + if (serverCache == nil && syncPoint != nil) { + serverCache = [syncPoint completeServerCacheAtPath:[FPath empty]]; + } + + NSMutableArray *events = [[NSMutableArray alloc] init]; + NSString *childKey = [operation.path getFront]; + id childOperation = [operation operationForChild:childKey]; + FImmutableTree *childTree = [syncPointTree.children get:childKey]; + if (childTree != nil && childOperation != nil) { + id childServerCache = serverCache ? [serverCache getImmediateChild:childKey] : nil; + FWriteTreeRef *childWritesCache = [writesCache childWriteTreeRef:childKey]; + [events addObjectsFromArray:[self applyOperationHelper:childOperation syncPointTree:childTree serverCache:childServerCache writesCache:childWritesCache]]; + } + + if (syncPoint) { + [events addObjectsFromArray:[syncPoint applyOperation:operation writesCache:writesCache serverCache:serverCache]]; + } + + return events; + } +} + +/** +* Recursive helper for applyOperationToSyncPoints: +*/ +- (NSArray *) applyOperationDescendantsHelper:(id)operation syncPointTree:(FImmutableTree *)syncPointTree + serverCache:(id)serverCache writesCache:(FWriteTreeRef *)writesCache { + FSyncPoint *syncPoint = syncPointTree.value; + + // If we don't have cached server data, see if we can get it from this SyncPoint + id resolvedServerCache; + if (serverCache == nil & syncPoint != nil) { + resolvedServerCache = [syncPoint completeServerCacheAtPath:[FPath empty]]; + } else { + resolvedServerCache = serverCache; + } + + NSMutableArray *events = [[NSMutableArray alloc] init]; + [syncPointTree.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + id childServerCache = nil; + if (resolvedServerCache != nil) { + childServerCache = [resolvedServerCache getImmediateChild:childKey]; + } + FWriteTreeRef *childWritesCache = [writesCache childWriteTreeRef:childKey]; + id childOperation = [operation operationForChild:childKey]; + if (childOperation != nil) { + [events addObjectsFromArray:[self applyOperationDescendantsHelper:childOperation + syncPointTree:childTree + serverCache:childServerCache + writesCache:childWritesCache]]; + } + }]; + + if (syncPoint) { + [events addObjectsFromArray:[syncPoint applyOperation:operation writesCache:writesCache serverCache:resolvedServerCache]]; + } + + return events; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.h new file mode 100644 index 0000000..a9b53fe --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FPath; +@class FCompoundWrite; +@protocol FNode; + +@interface FWriteRecord : NSObject + +- initWithPath:(FPath *)path overwrite:(id)overwrite writeId:(NSInteger)writeId visible:(BOOL)isVisible; +- initWithPath:(FPath *)path merge:(FCompoundWrite *)merge writeId:(NSInteger)writeId; + +@property (nonatomic, readonly) NSInteger writeId; +@property (nonatomic, strong, readonly) FPath *path; +@property (nonatomic, strong, readonly) id overwrite; +/** +* Maps NSString -> id +*/ +@property (nonatomic, strong, readonly) FCompoundWrite *merge; +@property (nonatomic, readonly) BOOL visible; + +- (BOOL)isMerge; +- (BOOL)isOverwrite; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.m new file mode 100644 index 0000000..47c952c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteRecord.m @@ -0,0 +1,117 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FWriteRecord.h" +#import "FPath.h" +#import "FNode.h" +#import "FCompoundWrite.h" + +@interface FWriteRecord () +@property (nonatomic, readwrite) NSInteger writeId; +@property (nonatomic, strong, readwrite) FPath *path; +@property (nonatomic, strong, readwrite) id overwrite; +@property (nonatomic, strong, readwrite) FCompoundWrite *merge; +@property (nonatomic, readwrite) BOOL visible; +@end + +@implementation FWriteRecord + +- (id)initWithPath:(FPath *)path overwrite:(id)overwrite writeId:(NSInteger)writeId visible:(BOOL)isVisible { + self = [super init]; + if (self) { + self.path = path; + if (overwrite == nil) { + [NSException raise:NSInvalidArgumentException format:@"Can't pass nil as overwrite parameter to an overwrite write record"]; + } + self.overwrite = overwrite; + self.merge = nil; + self.writeId = writeId; + self.visible = isVisible; + } + return self; +} + +- (id)initWithPath:(FPath *)path merge:(FCompoundWrite *)merge writeId:(NSInteger)writeId { + self = [super init]; + if (self) { + self.path = path; + if (merge == nil) { + [NSException raise:NSInvalidArgumentException format:@"Can't pass nil as merge parameter to an merge write record"]; + } + self.overwrite = nil; + self.merge = merge; + self.writeId = writeId; + self.visible = YES; + } + return self; +} + +- (id)overwrite { + if (self->_overwrite == nil) { + [NSException raise:NSInvalidArgumentException format:@"Can't get overwrite for merge write record!"]; + } + return self->_overwrite; +} + +- (FCompoundWrite *)compoundWrite { + if (self->_merge == nil) { + [NSException raise:NSInvalidArgumentException format:@"Can't get merge for overwrite write record!"]; + } + return self->_merge; +} + +- (BOOL)isMerge { + return self->_merge != nil; +} + +- (BOOL)isOverwrite { + return self->_overwrite != nil; +} + +- (NSString *)description { + if (self.isOverwrite) { + return [NSString stringWithFormat:@"FWriteRecord { writeId = %lu, path = %@, overwrite = %@, visible = %d }", + (unsigned long)self.writeId, self.path, self.overwrite, self.visible]; + } else { + return [NSString stringWithFormat:@"FWriteRecord { writeId = %lu, path = %@, merge = %@ }", + (unsigned long)self.writeId, self.path, self.merge]; + } +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[self class]]) { + return NO; + } + FWriteRecord *other = (FWriteRecord *)object; + if (self->_writeId != other->_writeId) return NO; + if (self->_path != other->_path && ![self->_path isEqual:other->_path]) return NO; + if (self->_overwrite != other->_overwrite && ![self->_overwrite isEqual:other->_overwrite]) return NO; + if (self->_merge != other->_merge && ![self->_merge isEqual:other->_merge]) return NO; + if (self->_visible != other->_visible) return NO; + + return YES; +} + +- (NSUInteger)hash { + NSUInteger hash = self->_writeId * 17; + hash = hash * 31 + self->_path.hash; + hash = hash * 31 + self->_overwrite.hash; + hash = hash * 31 + self->_merge.hash; + hash = hash * 31 + ((self->_visible) ? 1 : 0); + return hash; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.h new file mode 100644 index 0000000..243bc9f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.h @@ -0,0 +1,63 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FPath; +@protocol FNode; +@class FCompoundWrite; +@class FWriteTreeRef; +@class FChildrenNode; +@class FNamedNode; +@class FWriteRecord; +@protocol FIndex; +@class FCacheNode; + +@interface FWriteTree : NSObject + +- (FWriteTreeRef *) childWritesForPath:(FPath *)path; +- (void) addOverwriteAtPath:(FPath *)path newData:(id)newData writeId:(NSInteger)writeId isVisible:(BOOL)visible; +- (void) addMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren writeId:(NSInteger)writeId; +- (BOOL) removeWriteId:(NSInteger)writeId; +- (NSArray *) removeAllWrites; +- (FWriteRecord *)writeForId:(NSInteger)writeId; + +- (id) calculateCompleteEventCacheAtPath:(FPath *)treePath + completeServerCache:(id)completeServerCache + excludeWriteIds:(NSArray *)writeIdsToExclude + includeHiddenWrites:(BOOL)includeHiddenWrites; + +- (id) calculateCompleteEventChildrenAtPath:(FPath *)treePath + completeServerChildren:(id)completeServerChildren; + +- (id) calculateEventCacheAfterServerOverwriteAtPath:(FPath *)treePath + childPath:(FPath *)childPath + existingEventSnap:(id)existingEventSnap + existingServerSnap:(id)existingServerSnap; + +- (id) calculateCompleteChildAtPath:(FPath *)treePath + childKey:(NSString *)childKey + cache:(FCacheNode *)existingServerCache; + +- (id) shadowingWriteAtPath:(FPath *)path; + +- (FNamedNode *) calculateNextNodeAfterPost:(FNamedNode *)post + atPath:(FPath *)path + completeServerData:(id)completeServerData + reverse:(BOOL)reverse + index:(id)index; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.m new file mode 100644 index 0000000..c5b08ea --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTree.m @@ -0,0 +1,458 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FWriteTree.h" +#import "FImmutableTree.h" +#import "FPath.h" +#import "FNode.h" +#import "FWriteTreeRef.h" +#import "FChildrenNode.h" +#import "FNamedNode.h" +#import "FWriteRecord.h" +#import "FEmptyNode.h" +#import "FIndex.h" +#import "FCompoundWrite.h" +#import "FCacheNode.h" + +@interface FWriteTree () +/** +* A tree tracking the results of applying all visible writes. This does not include transactions with +* applyLocally=false or writes that are completely shadowed by other writes. +* Contains id as values. +*/ +@property (nonatomic, strong) FCompoundWrite *visibleWrites; +/** +* A list of pending writes, regardless of visibility and shadowed-ness. Used to calcuate arbitrary +* sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also +* used by transactions). +* Contains FWriteRecords. +*/ +@property (nonatomic, strong) NSMutableArray *allWrites; +@property (nonatomic) NSInteger lastWriteId; +@end + +/** +* FWriteTree tracks all pending user-initiated writes and has methods to calcuate the result of merging them with +* underlying server data (to create "event cache" data). Pending writes are added with addOverwriteAtPath: and +* addMergeAtPath: and removed with removeWriteId:. +*/ +@implementation FWriteTree + +@synthesize allWrites; +@synthesize lastWriteId; + +- (id) init { + self = [super init]; + if (self) { + self.visibleWrites = [FCompoundWrite emptyWrite]; + self.allWrites = [[NSMutableArray alloc] init]; + self.lastWriteId = -1; + } + return self; +} + +/** +* Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. +*/ +- (FWriteTreeRef *) childWritesForPath:(FPath *)path { + return [[FWriteTreeRef alloc] initWithPath:path writeTree:self]; +} + +/** +* Record a new overwrite from user code. +* @param visible Is set to false by some transactions. It should be excluded from event caches. +*/ +- (void) addOverwriteAtPath:(FPath *)path newData:(id )newData writeId:(NSInteger)writeId isVisible:(BOOL)visible { + NSAssert(writeId > self.lastWriteId, @"Stacking an older write on top of a newer one"); + FWriteRecord *record = [[FWriteRecord alloc] initWithPath:path overwrite:newData writeId:writeId visible:visible]; + [self.allWrites addObject:record]; + + if (visible) { + self.visibleWrites = [self.visibleWrites addWrite:newData atPath:path]; + } + + self.lastWriteId = writeId; +} + +/** +* Record a new merge from user code. +* @param changedChildren maps NSString -> id +*/ +- (void) addMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren writeId:(NSInteger)writeId { + NSAssert(writeId > self.lastWriteId, @"Stacking an older merge on top of newer one"); + FWriteRecord *record = [[FWriteRecord alloc] initWithPath:path merge:changedChildren writeId:writeId]; + [self.allWrites addObject:record]; + + self.visibleWrites = [self.visibleWrites addCompoundWrite:changedChildren atPath:path]; + self.lastWriteId = writeId; +} + +- (FWriteRecord *)writeForId:(NSInteger)writeId { + NSUInteger index = [self.allWrites indexOfObjectPassingTest:^BOOL(FWriteRecord *write, NSUInteger idx, BOOL *stop) { + return write.writeId == writeId; + }]; + return (index == NSNotFound) ? nil : self.allWrites[index]; +} + +/** +* Remove a write (either an overwrite or merge) that has been successfully acknowledged by the server. Recalculates the +* tree if necessary. We return the path of the write and whether it may have been visible, meaning views need to +* reevaluate. +* +* @return YES if the write may have been visible (meaning we'll need to reevaluate / raise events as a result). +*/ +- (BOOL) removeWriteId:(NSInteger)writeId { + NSUInteger index = [self.allWrites indexOfObjectPassingTest:^BOOL(FWriteRecord *record, NSUInteger idx, BOOL *stop) { + if (record.writeId == writeId) { + return YES; + } else { + return NO; + } + }]; + NSAssert(index != NSNotFound, @"[FWriteTree removeWriteId:] called with nonexistent writeId."); + FWriteRecord *writeToRemove = self.allWrites[index]; + [self.allWrites removeObjectAtIndex:index]; + + BOOL removedWriteWasVisible = writeToRemove.visible; + BOOL removedWriteOverlapsWithOtherWrites = NO; + NSInteger i = [self.allWrites count] - 1; + + while (removedWriteWasVisible && i >= 0) { + FWriteRecord *currentWrite = [self.allWrites objectAtIndex:i]; + if (currentWrite.visible) { + if (i >= index && [self record:currentWrite containsPath:writeToRemove.path]) { + // The removed write was completely shadowed by a subsequent write. + removedWriteWasVisible = NO; + } else if ([writeToRemove.path contains:currentWrite.path]) { + // Either we're covering some writes or they're covering part of us (depending on which came first). + removedWriteOverlapsWithOtherWrites = YES; + } + } + i--; + } + + if (!removedWriteWasVisible) { + return NO; + } else if (removedWriteOverlapsWithOtherWrites) { + // There's some shadowing going on. Just rebuild the visible writes from scratch. + [self resetTree]; + return YES; + } else { + // There's no shadowing. We can safely just remove the write(s) from visibleWrites. + if ([writeToRemove isOverwrite]) { + self.visibleWrites = [self.visibleWrites removeWriteAtPath:writeToRemove.path]; + } else { + FCompoundWrite *merge = writeToRemove.merge; + [merge enumerateWrites:^(FPath *path, id node, BOOL *stop) { + self.visibleWrites = [self.visibleWrites removeWriteAtPath:[writeToRemove.path child:path]]; + }]; + } + return YES; + } +} + +- (NSArray *) removeAllWrites { + NSArray *writes = self.allWrites; + self.visibleWrites = [FCompoundWrite emptyWrite]; + self.allWrites = [NSMutableArray array]; + return writes; +} + +/** +* @return A complete snapshot for the given path if there's visible write data at that path, else nil. +* No server data is considered. +*/ +- (id ) completeWriteDataAtPath:(FPath *)path { + return [self.visibleWrites completeNodeAtPath:path]; +} + +/** +* Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden +* writes), attempt to calculate a complete snapshot for the given path +* @param includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false +*/ +- (id ) calculateCompleteEventCacheAtPath:(FPath *)treePath completeServerCache:(id )completeServerCache + excludeWriteIds:(NSArray *)writeIdsToExclude includeHiddenWrites:(BOOL)includeHiddenWrites { + if (writeIdsToExclude == nil && !includeHiddenWrites) { + id shadowingNode = [self.visibleWrites completeNodeAtPath:treePath]; + if (shadowingNode != nil) { + return shadowingNode; + } else { + // No cache here. Can't claim complete knowledge. + FCompoundWrite *subMerge = [self.visibleWrites childCompoundWriteAtPath:treePath]; + if (subMerge.isEmpty) { + return completeServerCache; + } else if (completeServerCache == nil && ![subMerge hasCompleteWriteAtPath:[FPath empty]]) { + // We wouldn't have a complete snapshot since there's no underlying data and no complete shadow + return nil; + } else { + id layeredCache = completeServerCache != nil ? completeServerCache : [FEmptyNode emptyNode]; + return [subMerge applyToNode:layeredCache]; + } + } + } else { + FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath]; + if (!includeHiddenWrites && merge.isEmpty) { + return completeServerCache; + } else { + // If the server cache is null and we don't have a complete cache, we need to return nil + if (!includeHiddenWrites && completeServerCache == nil && ![merge hasCompleteWriteAtPath:[FPath empty]]) { + return nil; + } else { + BOOL (^filter) (FWriteRecord *) = ^(FWriteRecord *record) { + return (BOOL) ((record.visible || includeHiddenWrites) && + (writeIdsToExclude == nil || ![writeIdsToExclude containsObject:[NSNumber numberWithInteger:record.writeId]]) && + ([record.path contains:treePath] || [treePath contains:record.path])); + }; + FCompoundWrite *mergeAtPath = [FWriteTree layerTreeFromWrites:self.allWrites filter:filter treeRoot:treePath]; + id layeredCache = completeServerCache ? completeServerCache : [FEmptyNode emptyNode]; + return [mergeAtPath applyToNode:layeredCache]; + } + } + } +} + +/** +* With optional, underlying server data, attempt to return a children node of children that we have complete data for. +* Used when creating new views, to pre-fill their complete event children snapshot. +*/ +- (FChildrenNode *) calculateCompleteEventChildrenAtPath:(FPath *)treePath + completeServerChildren:(id)completeServerChildren { + __block id completeChildren = [FEmptyNode emptyNode]; + id topLevelSet = [self.visibleWrites completeNodeAtPath:treePath]; + if (topLevelSet != nil) { + if (![topLevelSet isLeafNode]) { + // We're shadowing everything. Return the children. + FChildrenNode *topChildrenNode = topLevelSet; + [topChildrenNode enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + completeChildren = [completeChildren updateImmediateChild:key withNewChild:node]; + }]; + } + return completeChildren; + } else { + // Layer any children we have on top of this + // We know we don't have a top-level set, so just enumerate existing children, and apply any updates + FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath]; + [completeServerChildren enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + FCompoundWrite *childMerge = [merge childCompoundWriteAtPath:[[FPath alloc] initWith:key]]; + id newChildNode = [childMerge applyToNode:node]; + completeChildren = [completeChildren updateImmediateChild:key withNewChild:newChildNode]; + }]; + // Add any complete children we have from the set. + for (FNamedNode *node in merge.completeChildren) { + completeChildren = [completeChildren updateImmediateChild:node.name withNewChild:node.node]; + } + return completeChildren; + } +} + +/** +* Given that the underlying server data has updated, determine what, if anything, needs to be applied to the event cache. +* +* Possibilities +* +* 1. No write are shadowing. Events should be raised, the snap to be applied comes from the server data. +* +* 2. Some write is completely shadowing. No events to be raised. +* +* 3. Is partially shadowed. Events .. +* +* Either existingEventSnap or existingServerSnap must exist. +*/ +- (id ) calculateEventCacheAfterServerOverwriteAtPath:(FPath *)treePath childPath:(FPath *)childPath existingEventSnap:(id )existingEventSnap existingServerSnap:(id )existingServerSnap { + NSAssert(existingEventSnap != nil || existingServerSnap != nil, + @"Either existingEventSnap or existingServerSanp must exist."); + + FPath *path = [treePath child:childPath]; + if ([self.visibleWrites hasCompleteWriteAtPath:path]) { + // At this point we can probably guarantee that we're in case 2, meaning no events + // May need to check visibility while doing the findRootMostValueAndPath call + return nil; + } else { + // This could be more efficient if the serverNode + updates doesn't change the eventSnap + // However this is tricky to find out, since user updates don't necessary change the server + // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server + // adds nodes, but doesn't change any existing writes. It is therefore not enough to + // only check if the updates change the serverNode. + // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? + FCompoundWrite *childMerge = [self.visibleWrites childCompoundWriteAtPath:path]; + if (childMerge.isEmpty) { + // We're not shadowing at all. Case 1 + return [existingServerSnap getChild:childPath]; + } else { + return [childMerge applyToNode:[existingServerSnap getChild:childPath]]; + } + } +} + +/** +* Returns a complete child for a given server snap after applying all user writes or nil if there is no complete child +* for this child key. +*/ +- (id) calculateCompleteChildAtPath:(FPath *)treePath childKey:(NSString *)childKey cache:(FCacheNode *)existingServerCache { + FPath *path = [treePath childFromString:childKey]; + id shadowingNode = [self.visibleWrites completeNodeAtPath:path]; + if (shadowingNode != nil) { + return shadowingNode; + } else { + if ([existingServerCache isCompleteForChild:childKey]) { + FCompoundWrite *childMerge = [self.visibleWrites childCompoundWriteAtPath:path]; + return [childMerge applyToNode:[existingServerCache.node getImmediateChild:childKey]]; + } else { + return nil; + } + } +} + +/** +* Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at +* a higher path, this will return the child of that write relative to the write and this path. +* Returns null if there is no write at this path. +*/ +- (id) shadowingWriteAtPath:(FPath *)path { + return [self.visibleWrites completeNodeAtPath:path]; +} + +/** +* This method is used when processing child remove events on a query. If we can, we pull in children that were outside +* the window, but may now be in the window. +*/ +- (FNamedNode *)calculateNextNodeAfterPost:(FNamedNode *)post + atPath:(FPath *)treePath + completeServerData:(id)completeServerData + reverse:(BOOL)reverse + index:(id)index +{ + __block id toIterate; + FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath]; + id shadowingNode = [merge completeNodeAtPath:[FPath empty]]; + if (shadowingNode != nil) { + toIterate = shadowingNode; + } else if (completeServerData != nil) { + toIterate = [merge applyToNode:completeServerData]; + } else { + return nil; + } + + __block NSString *currentNextKey = nil; + __block id currentNextNode = nil; + [toIterate enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + if ([index compareKey:key andNode:node toOtherKey:post.name andNode:post.node reverse:reverse] > NSOrderedSame && + (!currentNextKey || [index compareKey:key andNode:node toOtherKey:currentNextKey andNode:currentNextNode reverse:reverse] < NSOrderedSame)) { + currentNextKey = key; + currentNextNode = node; + } + }]; + + if (currentNextKey != nil) { + return [FNamedNode nodeWithName:currentNextKey node:currentNextNode]; + } else { + return nil; + } +} + +#pragma mark - +#pragma mark Private Methods + +- (BOOL) record:(FWriteRecord *)record containsPath:(FPath *)path { + if ([record isOverwrite]) { + return [record.path contains:path]; + } else { + __block BOOL contains = NO; + [record.merge enumerateWrites:^(FPath *childPath, id node, BOOL *stop) { + contains = [[record.path child:childPath] contains:path]; + *stop = contains; + }]; + return contains; + } +} + +/** +* Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots +*/ +- (void) resetTree { + self.visibleWrites = [FWriteTree layerTreeFromWrites:self.allWrites filter:[FWriteTree defaultFilter] treeRoot:[FPath empty]]; + if ([self.allWrites count] > 0) { + FWriteRecord *lastRecord = self.allWrites[[self.allWrites count] - 1]; + self.lastWriteId = lastRecord.writeId; + } else { + self.lastWriteId = -1; + } +} + +/** +* The default filter used when constructing the tree. Keep everything that's visible. +*/ ++ (BOOL (^)(FWriteRecord *record)) defaultFilter { + static BOOL (^filter)(FWriteRecord *); + static dispatch_once_t filterToken; + dispatch_once(&filterToken, ^{ + filter = ^(FWriteRecord *record) { + return YES; + }; + }); + return filter; +} + +/** +* Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct a merge +* at that path +* @return An FImmutableTree of ids. +*/ ++ (FCompoundWrite *) layerTreeFromWrites:(NSArray *)writes filter:(BOOL (^)(FWriteRecord *record))filter treeRoot:(FPath *)treeRoot { + __block FCompoundWrite *compoundWrite = [FCompoundWrite emptyWrite]; + [writes enumerateObjectsUsingBlock:^(FWriteRecord *record, NSUInteger idx, BOOL *stop) { + // Theory, a later set will either: + // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction + // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction + if (filter(record)) { + FPath *writePath = record.path; + if ([record isOverwrite]) { + if ([treeRoot contains:writePath]) { + FPath *relativePath = [FPath relativePathFrom:treeRoot to:writePath]; + compoundWrite = [compoundWrite addWrite:record.overwrite atPath:relativePath]; + } else if ([writePath contains:treeRoot]) { + id child = [record.overwrite getChild:[FPath relativePathFrom:writePath to:treeRoot]]; + compoundWrite = [compoundWrite addWrite:child atPath:[FPath empty]]; + } else { + // There is no overlap between root path and write path, ignore write + } + } else { + if ([treeRoot contains:writePath]) { + FPath *relativePath = [FPath relativePathFrom:treeRoot to:writePath]; + compoundWrite = [compoundWrite addCompoundWrite:record.merge atPath:relativePath]; + } else if ([writePath contains:treeRoot]) { + FPath *relativePath = [FPath relativePathFrom:writePath to:treeRoot]; + if (relativePath.isEmpty) { + compoundWrite = [compoundWrite addCompoundWrite:record.merge atPath:[FPath empty]]; + } else { + id child = [record.merge completeNodeAtPath:relativePath]; + if (child != nil) { + // There exists a child in this node that matches the root path + id deepNode = [child getChild:[relativePath popFront]]; + compoundWrite = [compoundWrite addWrite:deepNode atPath:[FPath empty]]; + } + } + } else { + // There is no overlap between root path and write path, ignore write + } + } + } + }]; + return compoundWrite; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.h new file mode 100644 index 0000000..791dd26 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.h @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@class FChildrenNode; +@class FPath; +@class FNamedNode; +@class FWriteRecord; +@class FWriteTree; +@protocol FIndex; +@class FCacheNode; + +@interface FWriteTreeRef : NSObject + +- (id) initWithPath:(FPath *)aPath writeTree:(FWriteTree *)tree; + +- (id ) calculateCompleteEventCacheWithCompleteServerCache:(id )completeServerCache; + +- (FChildrenNode *) calculateCompleteEventChildrenWithCompleteServerChildren:(FChildrenNode *)completeServerChildren; + +- (id) calculateEventCacheAfterServerOverwriteWithChildPath:(FPath *)childPath + existingEventSnap:(id)existingEventSnap + existingServerSnap:(id)existingServerSnap; + +- (id) shadowingWriteAtPath:(FPath *)path; + +- (FNamedNode *) calculateNextNodeAfterPost:(FNamedNode *)post + completeServerData:(id)completeServerData + reverse:(BOOL)reverse + index:(id)index; + +- (id) calculateCompleteChild:(NSString *)childKey cache:(FCacheNode *)existingServerCache; + +- (FWriteTreeRef *) childWriteTreeRef:(NSString *)childKey; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.m new file mode 100644 index 0000000..392369b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/FWriteTreeRef.m @@ -0,0 +1,133 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FWriteTreeRef.h" +#import "FPath.h" +#import "FNode.h" +#import "FWriteTree.h" +#import "FChildrenNode.h" +#import "FNamedNode.h" +#import "FWriteRecord.h" +#import "FIndex.h" +#import "FCacheNode.h" + +@interface FWriteTreeRef () +/** +* The path to this particular FWriteTreeRef. Used for calling methods on writeTree while exposing a simpler interface +* to callers. +*/ +@property (nonatomic, strong) FPath *path; +/** +* A reference to the actual tree of the write data. All methods are pass-through to the tree, but with the appropriate +* path prefixed. +* +* This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of +* the data. +*/ +@property (nonatomic, strong) FWriteTree *writeTree; +@end + +/** +* A FWriteTreeRef wraps a FWriteTree and a FPath, for convenient access to a particular subtree. All the methods just +* proxy to the underlying FWriteTree. +*/ +@implementation FWriteTreeRef +- (id) initWithPath:(FPath *)aPath writeTree:(FWriteTree *)tree { + self = [super init]; + if (self) { + self.path = aPath; + self.writeTree = tree; + } + return self; +} + +/** +* @return If possible, returns a complete event cache, using the underlying server data if possible. In addition, can +* be used to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned +* node can lead to a more expensive calculation. +*/ +- (id ) calculateCompleteEventCacheWithCompleteServerCache:(id)completeServerCache { + return [self.writeTree calculateCompleteEventCacheAtPath:self.path completeServerCache:completeServerCache excludeWriteIds:nil includeHiddenWrites:NO]; +} + +/** +* @return If possible, returns a children node containing all of the complete children we have data for. The returned +* data is a mix of the given server data and write data. +*/ +- (FChildrenNode *) calculateCompleteEventChildrenWithCompleteServerChildren:(id)completeServerChildren { + return [self.writeTree calculateCompleteEventChildrenAtPath:self.path completeServerChildren:completeServerChildren]; +} + +/** +* Given that either the underlying server data has updated or the outstanding writes have been updating, determine what, +* if anything, needs to be applied to the event cache. +* +* Possibilities: +* +* 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data. +* +* 2. Some writes are completly shadowing. No events to be raised. +* +* 3. Is partially shadowed. Events should be raised. +* +* Either existingEventSnap or existingServerSnap must exist, this is validated via an assert. +*/ +- (id) calculateEventCacheAfterServerOverwriteWithChildPath:(FPath *)childPath existingEventSnap:(id )existingEventSnap existingServerSnap:(id )existingServerSnap { + return [self.writeTree calculateEventCacheAfterServerOverwriteAtPath:self.path childPath:childPath existingEventSnap:existingEventSnap existingServerSnap:existingServerSnap]; +} + +/** +* Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at a higher +* path, this will return the child of that write relative to the write and this path. +* Returns nil if there is no write at this path. +*/ +- (id) shadowingWriteAtPath:(FPath *)path { + return [self.writeTree shadowingWriteAtPath:[self.path child:path]]; +} + +/** +* This method is used when processing child remove events on a query. If we can, we pull in children that are outside +* the window, but may now be in the window. +*/ +- (FNamedNode *)calculateNextNodeAfterPost:(FNamedNode *)post + completeServerData:(id)completeServerData + reverse:(BOOL)reverse + index:(id)index +{ + return [self.writeTree calculateNextNodeAfterPost:post + atPath:self.path + completeServerData:completeServerData + reverse:reverse + index:index]; +} + +/** +* Returns a complete child for a given server snap after applying all user writes or nil if there is no complete child +* for this child key. +*/ +- (id) calculateCompleteChild:(NSString *)childKey cache:(FCacheNode *)existingServerCache { + return [self.writeTree calculateCompleteChildAtPath:self.path childKey:childKey cache:existingServerCache]; +} + +/** +* @return a WriteTreeref for a child. +*/ +- (FWriteTreeRef *) childWriteTreeRef:(NSString *)childKey { + return [[FWriteTreeRef alloc] initWithPath:[self.path childFromString:childKey] writeTree:self.writeTree]; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.h new file mode 100644 index 0000000..a337996 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FOperation.h" + +@class FPath; +@class FOperationSource; +@class FImmutableTree; + + +@interface FAckUserWrite : NSObject + +- initWithPath:(FPath *)operationPath affectedTree:(FImmutableTree *)affectedTree revert:(BOOL)shouldRevert; + +@property (nonatomic, strong, readonly) FOperationSource *source; +@property (nonatomic, readonly) FOperationType type; +@property (nonatomic, strong, readonly) FPath *path; +// A FImmutableTree, containing @YES for each affected path. Affected paths can't overlap. +@property (nonatomic, strong, readonly) FImmutableTree *affectedTree; +@property (nonatomic, readonly) BOOL revert; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.m new file mode 100644 index 0000000..f81e7f5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FAckUserWrite.m @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FAckUserWrite.h" +#import "FPath.h" +#import "FOperationSource.h" +#import "FImmutableTree.h" + + +@implementation FAckUserWrite + +- (id) initWithPath:(FPath *)operationPath affectedTree:(FImmutableTree *)tree revert:(BOOL)shouldRevert { + self = [super init]; + if (self) { + self->_source = [FOperationSource userInstance]; + self->_type = FOperationTypeAckUserWrite; + self->_path = operationPath; + self->_affectedTree = tree; + self->_revert = shouldRevert; + } + return self; +} + +- (FAckUserWrite *) operationForChild:(NSString *)childKey { + if (![self.path isEmpty]) { + NSAssert([self.path.getFront isEqualToString:childKey], @"operationForChild called for unrelated child."); + return [[FAckUserWrite alloc] initWithPath:[self.path popFront] affectedTree:self.affectedTree revert:self.revert]; + } else if (self.affectedTree.value != nil) { + NSAssert(self.affectedTree.children.isEmpty, @"affectedTree should not have overlapping affected paths."); + // All child locations are affected as well; just return same operation. + return self; + } else { + FImmutableTree *childTree = [self.affectedTree subtreeAtPath:[[FPath alloc] initWith:childKey]]; + return [[FAckUserWrite alloc] initWithPath:[FPath empty] affectedTree:childTree revert:self.revert]; + } +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FAckUserWrite { path=%@, revert=%d, affectedTree=%@ }", self.path, self.revert, self.affectedTree]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.h new file mode 100644 index 0000000..4cab613 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FOperation.h" + +@class FCompoundWrite; + +@interface FMerge : NSObject + +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath children:(FCompoundWrite *)children; + +@property (nonatomic, strong, readonly) FOperationSource *source; +@property (nonatomic, readonly) FOperationType type; +@property (nonatomic, strong, readonly) FPath *path; +@property (nonatomic, strong, readonly) FCompoundWrite *children; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.m new file mode 100644 index 0000000..8e6d924 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FMerge.m @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FMerge.h" +#import "FOperationSource.h" +#import "FPath.h" +#import "FNode.h" +#import "FOverwrite.h" +#import "FCompoundWrite.h" + +@interface FMerge () +@property (nonatomic, strong, readwrite) FOperationSource *source; +@property (nonatomic, readwrite) FOperationType type; +@property (nonatomic, strong, readwrite) FPath *path; +@property (nonatomic, strong) FCompoundWrite *children; +@end + +@implementation FMerge + +@synthesize source; +@synthesize type; +@synthesize path; +@synthesize children; + +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath children:(FCompoundWrite *)someChildren { + self = [super init]; + if (self) { + self.source = aSource; + self.type = FOperationTypeMerge; + self.path = aPath; + self.children = someChildren; + } + return self; +} + +- (id) operationForChild:(NSString *)childKey { + if ([self.path isEmpty]) { + FCompoundWrite *childTree = [self.children childCompoundWriteAtPath:[[FPath alloc] initWith:childKey]]; + if (childTree.isEmpty) { + return nil; + } else if (childTree.rootWrite != nil) { + // We have a snapshot for the child in question. This becomes an overwrite of the child. + return [[FOverwrite alloc] initWithSource:self.source path:[FPath empty] snap:childTree.rootWrite]; + } else { + // This is a merge at a deeper level + return [[FMerge alloc] initWithSource:self.source path:[FPath empty] children:childTree]; + } + } else { + NSAssert([self.path.getFront isEqualToString:childKey], @"Can't get a merge for a child not on the path of the operation"); + return [[FMerge alloc] initWithSource:self.source path:[self.path popFront] children:self.children]; + } +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FMerge { path=%@, soruce=%@ children=%@}", self.path, self.source, self.children]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperation.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperation.h new file mode 100644 index 0000000..2bbbbd2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperation.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FOperationSource; +@class FPath; + +typedef NS_ENUM(NSInteger, FOperationType) { + FOperationTypeOverwrite = 0, + FOperationTypeMerge = 1, + FOperationTypeAckUserWrite = 2, + FOperationTypeListenComplete = 3 +}; + +@protocol FOperation +@property (nonatomic, strong, readonly) FOperationSource *source; +@property (nonatomic, readonly) FOperationType type; +@property (nonatomic, strong, readonly) FPath *path; +- (id) operationForChild:(NSString *)childKey; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.h new file mode 100644 index 0000000..a069c2f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FQueryParams; + +@interface FOperationSource : NSObject + +@property (nonatomic, readonly) BOOL fromUser; +@property (nonatomic, readonly) BOOL fromServer; +@property (nonatomic, readonly) BOOL isTagged; +@property (nonatomic, strong, readonly) FQueryParams *queryParams; + +- initWithFromUser:(BOOL)isFromUser fromServer:(BOOL)isFromServer queryParams:(FQueryParams *)params tagged:(BOOL)isTagged; + ++ (FOperationSource *) userInstance; ++ (FOperationSource *) serverInstance; ++ (FOperationSource *) forServerTaggedQuery:(FQueryParams *)params; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.m new file mode 100644 index 0000000..9a34a2e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOperationSource.m @@ -0,0 +1,73 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FOperationSource.h" +#import "FPath.h" +#import "FQueryParams.h" + +@interface FOperationSource () +@property (nonatomic, readwrite) BOOL fromUser; +@property (nonatomic, readwrite) BOOL fromServer; +@property (nonatomic, readwrite) BOOL isTagged; +@property (nonatomic, strong, readwrite) FQueryParams *queryParams; +@end + +@implementation FOperationSource + +@synthesize fromUser; +@synthesize fromServer; +@synthesize queryParams; + +- (id) initWithFromUser:(BOOL)isFromUser fromServer:(BOOL)isFromServer queryParams:(FQueryParams *)params tagged:(BOOL)tagged { + self = [super init]; + if (self) { + self.fromUser = isFromUser; + self.fromServer = isFromServer; + self.queryParams = params; + self.isTagged = tagged; + } + return self; +} + ++ (FOperationSource *) userInstance { + static FOperationSource *user = nil; + static dispatch_once_t userToken; + dispatch_once(&userToken, ^{ + user = [[FOperationSource alloc] initWithFromUser:YES fromServer:NO queryParams:nil tagged:NO]; + }); + return user; +} + ++ (FOperationSource *) serverInstance { + static FOperationSource *server = nil; + static dispatch_once_t serverToken; + dispatch_once(&serverToken, ^{ + server = [[FOperationSource alloc] initWithFromUser:NO fromServer:YES queryParams:nil tagged:NO]; + }); + return server; +} + ++ (FOperationSource *) forServerTaggedQuery:(FQueryParams *)params { + return [[FOperationSource alloc] initWithFromUser:NO fromServer:YES queryParams:params tagged:YES]; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FOperationSource { fromUser=%d, fromServer=%d, queryId=%@, tagged=%d }", + self.fromUser, self.fromServer, self.queryParams, self.isTagged]; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.h new file mode 100644 index 0000000..e950bed --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FOperation.h" + +@protocol FNode; + +@interface FOverwrite : NSObject + +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath snap:(id)aSnap; + +@property (nonatomic, strong, readonly) FOperationSource *source; +@property (nonatomic, readonly) FOperationType type; +@property (nonatomic, strong, readonly) FPath *path; +@property (nonatomic, strong, readonly) id snap; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.m new file mode 100644 index 0000000..b72d31a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Operation/FOverwrite.m @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FOverwrite.h" +#import "FNode.h" +#import "FOperationSource.h" + +@interface FOverwrite () +@property (nonatomic, strong, readwrite) FOperationSource *source; +@property (nonatomic, readwrite) FOperationType type; +@property (nonatomic, strong, readwrite) FPath *path; +@property (nonatomic, strong) id snap; +@end + +@implementation FOverwrite + +@synthesize source; +@synthesize type; +@synthesize path; +@synthesize snap; + +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath snap:(id )aSnap { + self = [super init]; + if (self) { + self.source = aSource; + self.type = FOperationTypeOverwrite; + self.path = aPath; + self.snap = aSnap; + } + return self; +} + +- (FOverwrite *) operationForChild:(NSString *)childKey { + if ([self.path isEmpty]) { + return [[FOverwrite alloc] initWithSource:self.source + path:[FPath empty] + snap:[self.snap getImmediateChild:childKey]]; + } else { + return [[FOverwrite alloc] initWithSource:self.source + path:[self.path popFront] + snap:self.snap]; + } +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FOverwrite { path=%@, source=%@, snapshot=%@ }", self.path, self.source, self.snap]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.h new file mode 100644 index 0000000..f83aad9 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FIRRetryHelper : NSObject + +- (instancetype) initWithDispatchQueue:(dispatch_queue_t)dispatchQueue + minRetryDelayAfterFailure:(NSTimeInterval)minRetryDelayAfterFailure + maxRetryDelay:(NSTimeInterval)maxRetryDelay + retryExponent:(double)retryExponent + jitterFactor:(double)jitterFactor; + +- (void) retry:(void (^)(void))block; + +- (void) cancel; + +- (void) signalSuccess; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.m new file mode 100644 index 0000000..fca02f5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FIRRetryHelper.m @@ -0,0 +1,140 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRRetryHelper.h" +#import "FUtilities.h" + +@interface FIRRetryHelperTask : NSObject + +@property (nonatomic, strong) void (^block)(void); + +@end + +@implementation FIRRetryHelperTask + +- (instancetype) initWithBlock:(void (^)(void))block { + self = [super init]; + if (self != nil) { + self->_block = [block copy]; + } + return self; +} + +- (BOOL) isCanceled { + return self.block == nil; +} + +- (void) cancel { + self.block = nil; +} + +- (void) execute { + if (self.block) { + self.block(); + } +} + +@end + + + +@interface FIRRetryHelper () + +@property (nonatomic, strong) dispatch_queue_t dispatchQueue; +@property (nonatomic) NSTimeInterval minRetryDelayAfterFailure; +@property (nonatomic) NSTimeInterval maxRetryDelay; +@property (nonatomic) double retryExponent; +@property (nonatomic) double jitterFactor; + +@property (nonatomic) BOOL lastWasSuccess; +@property (nonatomic) NSTimeInterval currentRetryDelay; + +@property (nonatomic, strong) FIRRetryHelperTask *scheduledRetry; + +@end + +@implementation FIRRetryHelper + +- (instancetype) initWithDispatchQueue:(dispatch_queue_t)dispatchQueue + minRetryDelayAfterFailure:(NSTimeInterval)minRetryDelayAfterFailure + maxRetryDelay:(NSTimeInterval)maxRetryDelay + retryExponent:(double)retryExponent + jitterFactor:(double)jitterFactor { + self = [super init]; + if (self != nil) { + self->_dispatchQueue = dispatchQueue; + self->_minRetryDelayAfterFailure = minRetryDelayAfterFailure; + self->_maxRetryDelay = maxRetryDelay; + self->_retryExponent = retryExponent; + self->_jitterFactor = jitterFactor; + self->_lastWasSuccess = YES; + } + return self; +} + +- (void) retry:(void (^)(void))block { + if (self.scheduledRetry != nil) { + FFLog(@"I-RDB054001", @"Canceling existing retry attempt"); + [self.scheduledRetry cancel]; + self.scheduledRetry = nil; + } + + NSTimeInterval delay; + if (self.lastWasSuccess) { + delay = 0; + } else { + if (self.currentRetryDelay == 0) { + self.currentRetryDelay = self.minRetryDelayAfterFailure; + } else { + NSTimeInterval newDelay = (self.currentRetryDelay * self.retryExponent); + self.currentRetryDelay = MIN(newDelay, self.maxRetryDelay); + } + + delay = ((1 - self.jitterFactor) * self.currentRetryDelay) + + (self.jitterFactor * self.currentRetryDelay * [FUtilities randomDouble]); + FFLog(@"I-RDB054002", @"Scheduling retry in %fs", delay); + + } + self.lastWasSuccess = NO; + FIRRetryHelperTask *task = [[FIRRetryHelperTask alloc] initWithBlock:block]; + self.scheduledRetry = task; + dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (long long)(delay * NSEC_PER_SEC)); + dispatch_after(popTime, self.dispatchQueue, ^{ + if (![task isCanceled]) { + self.scheduledRetry = nil; + [task execute]; + } + }); +} + +- (void) signalSuccess { + self.lastWasSuccess = YES; + self.currentRetryDelay = 0; +} + +- (void) cancel { + if (self.scheduledRetry != nil) { + FFLog(@"I-RDB054003", @"Canceling existing retry attempt"); + [self.scheduledRetry cancel]; + self.scheduledRetry = nil; + } else { + FFLog(@"I-RDB054004", @"No existing retry attempt to cancel"); + } + self.currentRetryDelay = 0; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.h new file mode 100644 index 0000000..005a9f2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.h @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FImmutableSortedDictionary.h" +#import "FPath.h" +#import "FTuplePathValue.h" + +@interface FImmutableTree : NSObject + +- (id) initWithValue:(id)aValue; +- (id) initWithValue:(id)aValue children:(FImmutableSortedDictionary *)childrenMap; + ++ (FImmutableTree *) empty; +- (BOOL) isEmpty; + +- (FTuplePathValue *) findRootMostMatchingPath:(FPath *)relativePath predicate:(BOOL (^)(id))predicate; +- (FTuplePathValue *) findRootMostValueAndPath:(FPath *)relativePath; +- (FImmutableTree *) subtreeAtPath:(FPath *)relativePath; +- (FImmutableTree *) setValue:(id)newValue atPath:(FPath *)relativePath; +- (FImmutableTree *) removeValueAtPath:(FPath *)relativePath; +- (id) valueAtPath:(FPath *)relativePath; +- (id) rootMostValueOnPath:(FPath *)path; +- (id) rootMostValueOnPath:(FPath *)path matching:(BOOL (^)(id))predicate; +- (id) leafMostValueOnPath:(FPath *)path; +- (id) leafMostValueOnPath:(FPath *)relativePath matching:(BOOL (^)(id))predicate; +- (BOOL) containsValueMatching:(BOOL (^)(id))predicate; +- (FImmutableTree *) setTree:(FImmutableTree *)newTree atPath:(FPath *)relativePath; +- (id) foldWithBlock:(id (^)(FPath *path, id value, NSDictionary *foldedChildren))block; +- (id) findOnPath:(FPath *)path andApplyBlock:(id (^)(FPath *path, id value))block; +- (FPath *) forEachOnPath:(FPath *)path whileBlock:(BOOL (^)(FPath *path, id value))block; +- (FImmutableTree *) forEachOnPath:(FPath *)path performBlock:(void (^)(FPath *path, id value))block; +- (void) forEach:(void (^)(FPath *path, id value))block; +- (void) forEachChild:(void (^)(NSString *childKey, id childValue))block; + +@property (nonatomic, strong, readonly) id value; +@property (nonatomic, strong, readonly) FImmutableSortedDictionary *children; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.m new file mode 100644 index 0000000..57bf74d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FImmutableTree.m @@ -0,0 +1,421 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FImmutableTree.h" +#import "FImmutableSortedDictionary.h" +#import "FPath.h" +#import "FUtilities.h" + +@interface FImmutableTree () +@property (nonatomic, strong, readwrite) id value; +/** +* Maps NSString -> FImmutableTree, where is type of value. +*/ +@property (nonatomic, strong, readwrite) FImmutableSortedDictionary *children; +@end + +@implementation FImmutableTree +@synthesize value; +@synthesize children; + +- (id) initWithValue:(id)aValue { + self = [super init]; + if (self) { + self.value = aValue; + self.children = [FImmutableTree emptyChildren]; + } + return self; +} + +- (id) initWithValue:(id)aValue children:(FImmutableSortedDictionary *)childrenMap { + self = [super init]; + if (self) { + self.value = aValue; + self.children = childrenMap; + } + return self; +} + ++ (FImmutableSortedDictionary *) emptyChildren { + static dispatch_once_t emptyChildrenToken; + static FImmutableSortedDictionary *emptyChildren; + dispatch_once(&emptyChildrenToken, ^{ + emptyChildren = [FImmutableSortedDictionary dictionaryWithComparator:[FUtilities stringComparator]]; + }); + return emptyChildren; +} + ++ (FImmutableTree *) empty { + static dispatch_once_t emptyImmutableTreeToken; + static FImmutableTree *emptyTree = nil; + dispatch_once(&emptyImmutableTreeToken, ^{ + emptyTree = [[FImmutableTree alloc] initWithValue:nil]; + }); + return emptyTree; +} + +- (BOOL) isEmpty { + return self.value == nil && [self.children isEmpty]; +} + +/** +* Given a path and a predicate, return the first node and the path to that node where the predicate returns true +* // TODO Do a perf test. If we're creating a bunch of FTuplePathValue objects on the way back out, it may be better to pass down a pathSoFar FPath +*/ +- (FTuplePathValue *) findRootMostMatchingPath:(FPath *)relativePath predicate:(BOOL (^)(id value))predicate { + if (self.value != nil && predicate(self.value)) { + return [[FTuplePathValue alloc] initWithPath:[FPath empty] value:self.value]; + } else { + if ([relativePath isEmpty]) { + return nil; + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *child = [self.children get:front]; + if (child != nil) { + FTuplePathValue *childExistingPathAndValue = [child findRootMostMatchingPath:[relativePath popFront] predicate:predicate]; + if (childExistingPathAndValue != nil) { + FPath *fullPath = [[[FPath alloc] initWith:front] child:childExistingPathAndValue.path]; + return [[FTuplePathValue alloc] initWithPath:fullPath value:childExistingPathAndValue.value]; + } else { + return nil; + } + } else { + // No child matching path + return nil; + } + } + } +} + +/** +* Find, if it exists, the shortest subpath of the given path that points a defined value in the tree +*/ +- (FTuplePathValue *) findRootMostValueAndPath:(FPath *)relativePath { + return [self findRootMostMatchingPath:relativePath predicate:^BOOL(__unsafe_unretained id value){ + return YES; + }]; +} + +- (id) rootMostValueOnPath:(FPath *)path { + return [self rootMostValueOnPath:path matching:^BOOL(id value) { + return YES; + }]; +} + +- (id) rootMostValueOnPath:(FPath *)path matching:(BOOL (^)(id))predicate { + if (self.value != nil && predicate(self.value)) { + return self.value; + } else if (path.isEmpty) { + return nil; + } else { + return [[self.children get:path.getFront] rootMostValueOnPath:[path popFront] matching:predicate]; + } +} + +- (id) leafMostValueOnPath:(FPath *)path { + return [self leafMostValueOnPath:path matching:^BOOL(id value) { + return YES; + }]; +} + +- (id) leafMostValueOnPath:(FPath *)relativePath matching:(BOOL (^)(id))predicate { + __block id currentValue = self.value; + __block FImmutableTree *currentTree = self; + [relativePath enumerateComponentsUsingBlock:^(NSString *key, BOOL *stop) { + currentTree = [currentTree.children get:key]; + if (currentTree == nil) { + *stop = YES; + } else { + id treeValue = currentTree.value; + if (treeValue != nil && predicate(treeValue)) { + currentValue = treeValue; + } + } + }]; + return currentValue; +} + +- (BOOL) containsValueMatching:(BOOL (^)(id))predicate { + if (self.value != nil && predicate(self.value)) { + return YES; + } else { + __block BOOL found = NO; + [self.children enumerateKeysAndObjectsUsingBlock:^(NSString *key, FImmutableTree *subtree, BOOL *stop) { + found = [subtree containsValueMatching:predicate]; + if (found) *stop = YES; + }]; + return found; + } +} + +- (FImmutableTree *) subtreeAtPath:(FPath *)relativePath { + if ([relativePath isEmpty]) { + return self; + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *childTree = [self.children get:front]; + if (childTree != nil) { + return [childTree subtreeAtPath:[relativePath popFront]]; + } else { + return [FImmutableTree empty]; + } + } +} + +/** +* Sets a value at the specified path +*/ +- (FImmutableTree *) setValue:(id)newValue atPath:(FPath *)relativePath { + if ([relativePath isEmpty]) { + return [[FImmutableTree alloc] initWithValue:newValue children:self.children]; + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *child = [self.children get:front]; + if (child == nil) { + child = [FImmutableTree empty]; + } + FImmutableTree *newChild = [child setValue:newValue atPath:[relativePath popFront]]; + FImmutableSortedDictionary *newChildren = [self.children insertKey:front withValue:newChild]; + return [[FImmutableTree alloc] initWithValue:self.value children:newChildren]; + } +} + +/** +* Remove the value at the specified path +*/ +- (FImmutableTree *) removeValueAtPath:(FPath *)relativePath { + if ([relativePath isEmpty]) { + if ([self.children isEmpty]) { + return [FImmutableTree empty]; + } else { + return [[FImmutableTree alloc] initWithValue:nil children:self.children]; + } + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *child = [self.children get:front]; + if (child) { + FImmutableTree *newChild = [child removeValueAtPath:[relativePath popFront]]; + FImmutableSortedDictionary *newChildren; + if ([newChild isEmpty]) { + newChildren = [self.children removeKey:front]; + } else { + newChildren = [self.children insertKey:front withValue:newChild]; + } + if (self.value == nil && [newChildren isEmpty]) { + return [FImmutableTree empty]; + } else { + return [[FImmutableTree alloc] initWithValue:self.value children:newChildren]; + } + } else { + return self; + } + } +} + +/** +* Gets a value from the tree +*/ +- (id) valueAtPath:(FPath *)relativePath { + if ([relativePath isEmpty]) { + return self.value; + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *child = [self.children get:front]; + if (child) { + return [child valueAtPath:[relativePath popFront]]; + } else { + return nil; + } + } +} + +/** +* Replaces the subtree at the specified path with the given new tree +*/ +- (FImmutableTree *) setTree:(FImmutableTree *)newTree atPath:(FPath *)relativePath { + if ([relativePath isEmpty]) { + return newTree; + } else { + NSString *front = [relativePath getFront]; + FImmutableTree *child = [self.children get:front]; + if (child == nil) { + child = [FImmutableTree empty]; + } + FImmutableTree *newChild = [child setTree:newTree atPath:[relativePath popFront]]; + FImmutableSortedDictionary *newChildren; + if ([newChild isEmpty]) { + newChildren = [self.children removeKey:front]; + } else { + newChildren = [self.children insertKey:front withValue:newChild]; + } + return [[FImmutableTree alloc] initWithValue:self.value children:newChildren]; + } +} + +/** +* Performs a depth first fold on this tree. Transforms a tree into a single value, given a function that operates on +* the path to a node, an optional current value, and a map of the child names to folded subtrees +*/ +- (id) foldWithBlock:(id (^)(FPath *path, id value, NSDictionary *foldedChildren))block { + return [self foldWithPathSoFar:[FPath empty] withBlock:block]; +} + +/** +* Recursive helper for public facing foldWithBlock: method +*/ +- (id) foldWithPathSoFar:(FPath *)pathSoFar withBlock:(id (^)(FPath *path, id value, NSDictionary *foldedChildren))block { + __block NSMutableDictionary *accum = [[NSMutableDictionary alloc] init]; + [self.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + accum[childKey] = [childTree foldWithPathSoFar:[pathSoFar childFromString:childKey] withBlock:block]; + }]; + return block(pathSoFar, self.value, accum); +} + +/** +* Find the first matching value on the given path. Return the result of applying block to it. +*/ +- (id) findOnPath:(FPath *)path andApplyBlock:(id (^)(FPath *path, id value))block { + return [self findOnPath:path pathSoFar:[FPath empty] andApplyBlock:block]; +} + +- (id) findOnPath:(FPath *)pathToFollow pathSoFar:(FPath *)pathSoFar andApplyBlock:(id (^)(FPath *path, id value))block { + id result = self.value ? block(pathSoFar, self.value) : nil; + if (result != nil) { + return result; + } else { + if ([pathToFollow isEmpty]) { + return nil; + } else { + NSString *front = [pathToFollow getFront]; + FImmutableTree *nextChild = [self.children get:front]; + if (nextChild != nil) { + return [nextChild findOnPath:[pathToFollow popFront] pathSoFar:[pathSoFar childFromString:front] andApplyBlock:block]; + } else { + return nil; + } + } + } +} +/** +* Call the block on each value along the path for as long as that function returns true +* @return The path to the deepest location inspected +*/ +- (FPath *) forEachOnPath:(FPath *)path whileBlock:(BOOL (^)(FPath *, id))block { + return [self forEachOnPath:path pathSoFar:[FPath empty] whileBlock:block]; +} + +- (FPath *) forEachOnPath:(FPath *)pathToFollow pathSoFar:(FPath *)pathSoFar whileBlock:(BOOL (^)(FPath *, id))block { + if ([pathToFollow isEmpty]) { + if (self.value) { + block(pathSoFar, self.value); + } + return pathSoFar; + } else { + BOOL shouldContinue = YES; + if (self.value) { + shouldContinue = block(pathSoFar, self.value); + } + if (shouldContinue) { + NSString *front = [pathToFollow getFront]; + FImmutableTree *nextChild = [self.children get:front]; + if (nextChild) { + return [nextChild forEachOnPath:[pathToFollow popFront] pathSoFar:[pathSoFar childFromString:front] whileBlock:block]; + } else { + return pathSoFar; + } + } else { + return pathSoFar; + } + } +} + +- (FImmutableTree *) forEachOnPath:(FPath *)path performBlock:(void (^)(FPath *path, id value))block { + return [self forEachOnPath:path pathSoFar:[FPath empty] performBlock:block]; +} + +- (FImmutableTree *) forEachOnPath:(FPath *)pathToFollow pathSoFar:(FPath *)pathSoFar performBlock:(void (^)(FPath *path, id value))block { + if ([pathToFollow isEmpty]) { + return self; + } else { + if (self.value) { + block(pathSoFar, self.value); + } + NSString *front = [pathToFollow getFront]; + FImmutableTree *nextChild = [self.children get:front]; + if (nextChild) { + return [nextChild forEachOnPath:[pathToFollow popFront] pathSoFar:[pathSoFar childFromString:front] performBlock:block]; + } else { + return [FImmutableTree empty]; + } + } +} +/** +* Calls the given block for each node in the tree that has a value. Called in depth-first order +*/ +- (void) forEach:(void (^)(FPath *path, id value))block { + [self forEachPathSoFar:[FPath empty] withBlock:block]; +} + +- (void) forEachPathSoFar:(FPath *)pathSoFar withBlock:(void (^)(FPath *path, id value))block { + [self.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + [childTree forEachPathSoFar:[pathSoFar childFromString:childKey] withBlock:block]; + }]; + if (self.value) { + block(pathSoFar, self.value); + } +} + +- (void) forEachChild:(void (^)(NSString *childKey, id childValue))block { + [self.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + if (childTree.value) { + block(childKey, childTree.value); + } + }]; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[FImmutableTree class]]) { + return NO; + } + FImmutableTree *other = (FImmutableTree *)object; + return (self.value == other.value || [self.value isEqual:other.value]) && [self.children isEqual:other.children]; +} + +- (NSUInteger)hash { + return self.children.hash * 31 + [self.value hash]; +} + +- (NSString *) description { + NSMutableString *string = [[NSMutableString alloc] init]; + [string appendString:@"FImmutableTree { value="]; + [string appendString:(self.value ? [self.value description] : @"")]; + [string appendString:@", children={"]; + [self.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + [string appendString:@" "]; + [string appendString:childKey]; + [string appendString:@"="]; + [string appendString:[childTree.value description]]; + }]; + [string appendString:@" } }"]; + return [NSString stringWithString:string]; +} + +- (NSString *) debugDescription { + return [self description]; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.h new file mode 100644 index 0000000..71a7167 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FPath : NSObject + ++ (FPath *) relativePathFrom:(FPath *)outer to:(FPath *)inner; ++ (FPath *) empty; ++ (FPath *) pathWithString:(NSString *)string; + +- (id)initWith:(NSString *)path; +- (id)initWithPieces:(NSArray *)somePieces andPieceNum:(NSInteger)aPieceNum; + +- (id)copyWithZone:(NSZone *)zone; + +- (void)enumerateComponentsUsingBlock:(void (^)(NSString *key, BOOL *stop))block; +- (NSString *) getFront; +- (NSUInteger) length; +- (FPath *) popFront; +- (NSString *) getBack; +- (NSString *) toString; +- (NSString *) toStringWithTrailingSlash; +- (NSString *) wireFormat; +- (FPath *) parent; +- (FPath *) child:(FPath *)childPathObj; +- (FPath *) childFromString:(NSString *)childPath; +- (BOOL) isEmpty; +- (BOOL) contains:(FPath *)other; +- (NSComparisonResult) compare:(FPath *)other; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.m new file mode 100644 index 0000000..5215596 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FPath.m @@ -0,0 +1,298 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FPath.h" + +#import "FUtilities.h" + +@interface FPath() + +@property (nonatomic, readwrite, assign) NSInteger pieceNum; +@property (nonatomic, strong) NSArray * pieces; + +@end + +@implementation FPath + +#pragma mark - +#pragma mark Initializers + ++ (FPath *) relativePathFrom:(FPath *)outer to:(FPath *)inner { + NSString* outerFront = [outer getFront]; + NSString* innerFront = [inner getFront]; + if (outerFront == nil) { + return inner; + } else if ([outerFront isEqualToString:innerFront]) { + return [self relativePathFrom:[outer popFront] to:[inner popFront]]; + } else { + @throw [[NSException alloc] initWithName:@"FirebaseDatabaseInternalError" reason:[NSString stringWithFormat:@"innerPath (%@) is not within outerPath (%@)", inner, outer] userInfo:nil]; + } +} + ++ (FPath *)pathWithString:(NSString *)string +{ + return [[FPath alloc] initWith:string]; +} + +- (id)initWith:(NSString *)path +{ + self = [super init]; + if (self) { + NSArray *pathPieces = [path componentsSeparatedByString:@"/"]; + NSMutableArray *newPieces = [[NSMutableArray alloc] init]; + for (NSInteger i = 0; i < pathPieces.count; i++) { + NSString *piece = [pathPieces objectAtIndex:i]; + if (piece.length > 0) { + [newPieces addObject:piece]; + } + } + + self.pieces = newPieces; + self.pieceNum = 0; + } + return self; +} + +- (id)initWithPieces:(NSArray *)somePieces andPieceNum:(NSInteger)aPieceNum { + self = [super init]; + if (self) { + self.pieceNum = aPieceNum; + self.pieces = somePieces; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone +{ + // Immutable, so it's safe to return self + return self; +} + +- (NSString *)description { + return [self toString]; +} + +#pragma mark - +#pragma mark Public methods + +- (NSString *) getFront { + if(self.pieceNum >= self.pieces.count) { + return nil; + } + return [self.pieces objectAtIndex:self.pieceNum]; +} + +/** +* @return The number of segments in this path +*/ +- (NSUInteger) length { + return self.pieces.count - self.pieceNum; +} + +- (FPath *) popFront { + NSInteger newPieceNum = self.pieceNum; + if (newPieceNum < self.pieces.count) { + newPieceNum++; + } + return [[FPath alloc] initWithPieces:self.pieces andPieceNum:newPieceNum]; +} + +- (NSString *) getBack { + if(self.pieceNum < self.pieces.count) { + return [self.pieces lastObject]; + } + else { + return nil; + } +} + +- (NSString *) toString { + return [self toStringWithTrailingSlash:NO]; +} + +- (NSString *) toStringWithTrailingSlash { + return [self toStringWithTrailingSlash:YES]; +} + +- (NSString *) toStringWithTrailingSlash:(BOOL)trailingSlash { + NSMutableString* pathString = [[NSMutableString alloc] init]; + for(NSInteger i = self.pieceNum; i < self.pieces.count; i++) { + [pathString appendString:@"/"]; + [pathString appendString:[self.pieces objectAtIndex:i]]; + } + if ([pathString length] == 0) { + return @"/"; + } else { + if (trailingSlash) { + [pathString appendString:@"/"]; + } + return pathString; + } +} + +- (NSString *)wireFormat { + if ([self isEmpty]) { + return @"/"; + } else { + NSMutableString* pathString = [[NSMutableString alloc] init]; + for (NSInteger i = self.pieceNum; i < self.pieces.count; i++) { + if (i > self.pieceNum) { + [pathString appendString:@"/"]; + } + [pathString appendString:[self.pieces objectAtIndex:i]]; + } + return pathString; + } +} + +- (FPath *) parent { + if(self.pieceNum >= self.pieces.count) { + return nil; + } else { + NSMutableArray* newPieces = [[NSMutableArray alloc] init]; + for (NSInteger i = self.pieceNum; i < self.pieces.count - 1; i++) { + [newPieces addObject:[self.pieces objectAtIndex:i]]; + } + return [[FPath alloc] initWithPieces:newPieces andPieceNum:0]; + } +} + +- (FPath *) child:(FPath *)childPathObj { + NSMutableArray* newPieces = [[NSMutableArray alloc] init]; + for (NSInteger i = self.pieceNum; i < self.pieces.count; i++) { + [newPieces addObject:[self.pieces objectAtIndex:i]]; + } + + for (NSInteger i = childPathObj.pieceNum; i < childPathObj.pieces.count; i++) { + [newPieces addObject:[childPathObj.pieces objectAtIndex:i]]; + } + + return [[FPath alloc] initWithPieces:newPieces andPieceNum:0]; +} + +- (FPath *)childFromString:(NSString *)childPath { + NSMutableArray* newPieces = [[NSMutableArray alloc] init]; + for (NSInteger i = self.pieceNum; i < self.pieces.count; i++) { + [newPieces addObject:[self.pieces objectAtIndex:i]]; + } + + NSArray *pathPieces = [childPath componentsSeparatedByString:@"/"]; + for (unsigned int i = 0; i < pathPieces.count; i++) { + NSString *piece = [pathPieces objectAtIndex:i]; + if (piece.length > 0) { + [newPieces addObject:piece]; + } + } + + return [[FPath alloc] initWithPieces:newPieces andPieceNum:0]; +} + +/** +* @return True if there are no segments in this path +*/ +- (BOOL) isEmpty { + return self.pieceNum >= self.pieces.count; +} + +/** +* @return Singleton to represent an empty path +*/ ++ (FPath *) empty { + static dispatch_once_t oneEmptyPath; + static FPath *emptyPath; + dispatch_once(&oneEmptyPath, ^{ + emptyPath = [[FPath alloc] initWith:@""]; + }); + return emptyPath; +} + +- (BOOL) contains:(FPath *)other { + if (self.length > other.length) { + return NO; + } + + NSInteger i = self.pieceNum; + NSInteger j = other.pieceNum; + while (i < self.pieces.count) { + NSString* thisSeg = [self.pieces objectAtIndex:i]; + NSString* otherSeg = [other.pieces objectAtIndex:j]; + if (![thisSeg isEqualToString:otherSeg]) { + return NO; + } + ++i; + ++j; + } + return YES; +} + +- (void) enumerateComponentsUsingBlock:(void (^)(NSString *, BOOL *))block { + BOOL stop = NO; + for (NSInteger i = self.pieceNum; !stop && i < self.pieces.count; i++) { + block(self.pieces[i], &stop); + } +} + +- (NSComparisonResult) compare:(FPath *)other { + NSInteger myCount = self.pieces.count; + NSInteger otherCount = other.pieces.count; + for (NSInteger i = self.pieceNum, j = other.pieceNum; i < myCount && j < otherCount; i++, j++) { + NSComparisonResult comparison = [FUtilities compareKey:self.pieces[i] toKey:other.pieces[j]]; + if (comparison != NSOrderedSame) { + return comparison; + } + } + if (self.length < other.length) { + return NSOrderedAscending; + } else if (other.length < self.length) { + return NSOrderedDescending; + } else { + NSAssert(self.length == other.length, @"Paths must be the same lengths"); + return NSOrderedSame; + } +} + +/** +* @return YES if paths are the same +*/ +- (BOOL)isEqual:(id)other +{ + if (other == self) { + return YES; + } + if (!other || ![other isKindOfClass:[self class]]) { + return NO; + } + FPath *otherPath = (FPath *)other; + if (self.length != otherPath.length) { + return NO; + } + for (NSUInteger i = self.pieceNum, j = otherPath.pieceNum; i < self.pieces.count; i++, j++) { + if (![self.pieces[i] isEqualToString:otherPath.pieces[j]]) { + return NO; + } + } + return YES; +} + +- (NSUInteger) hash { + NSUInteger hashCode = 0; + for (NSInteger i = self.pieceNum; i < self.pieces.count; i++) { + hashCode = hashCode * 37 + [self.pieces[i] hash]; + } + return hashCode; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.h new file mode 100644 index 0000000..8528526 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.h @@ -0,0 +1,48 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTreeNode.h" +#import "FPath.h" + +@interface FTree : NSObject + +- (id)init; +- (id)initWithName:(NSString*)aName withParent:(FTree *)aParent withNode:(FTreeNode *)aNode; + +- (FTree *) subTree:(FPath*)path; +- (id)getValue; +- (void)setValue:(id)value; +- (void) clear; +- (BOOL) hasChildren; +- (BOOL) isEmpty; +- (void) forEachChildMutationSafe:(void (^)(FTree *))action; +- (void) forEachChild:(void (^)(FTree *))action; +- (void) forEachDescendant:(void (^)(FTree *))action; +- (void) forEachDescendant:(void (^)(FTree *))action includeSelf:(BOOL)incSelf childrenFirst:(BOOL)childFirst; +- (BOOL) forEachAncestor:(BOOL (^)(FTree *))action; +- (BOOL) forEachAncestor:(BOOL (^)(FTree *))action includeSelf:(BOOL)incSelf; +- (void) forEachImmediateDescendantWithValue:(void (^)(FTree *))action; +- (BOOL) valueExistsAtOrAbove:(FPath *)path; +- (FPath *)path; +- (void) updateParents; +- (void) updateChild:(NSString*)childName withNode:(FTree *)child; + +@property (nonatomic, strong) NSString* name; +@property (nonatomic, strong) FTree* parent; +@property (nonatomic, strong) FTreeNode* node; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.m new file mode 100644 index 0000000..8e7a334 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTree.m @@ -0,0 +1,183 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTree.h" +#import "FTreeNode.h" +#import "FPath.h" +#import "FUtilities.h" + +@implementation FTree + +@synthesize name; +@synthesize parent; +@synthesize node; + +- (id)init +{ + self = [super init]; + if (self) { + self.name = @""; + self.parent = nil; + self.node = [[FTreeNode alloc] init]; + } + return self; +} + + +- (id)initWithName:(NSString*)aName withParent:(FTree *)aParent withNode:(FTreeNode *)aNode +{ + self = [super init]; + if (self) { + self.name = aName != nil ? aName : @""; + self.parent = aParent != nil ? aParent : nil; + self.node = aNode != nil ? aNode : [[FTreeNode alloc] init]; + } + return self; +} + +- (FTree *) subTree:(FPath*)path { + FTree* child = self; + NSString* next = [path getFront]; + while(next != nil) { + FTreeNode* childNode = child.node.children[next]; + if (childNode == nil) { + childNode = [[FTreeNode alloc] init]; + } + child = [[FTree alloc] initWithName:next withParent:child withNode:childNode]; + path = [path popFront]; + next = [path getFront]; + } + return child; +} + +- (id)getValue { + return self.node.value; +} + +- (void)setValue:(id)value { + self.node.value = value; + [self updateParents]; +} + +- (void) clear { + self.node.value = nil; + [self.node.children removeAllObjects]; + self.node.childCount = 0; + [self updateParents]; +} + +- (BOOL) hasChildren { + return self.node.childCount > 0; +} + +- (BOOL) isEmpty { + return [self getValue] == nil && ![self hasChildren]; +} + +- (void) forEachChild:(void (^)(FTree *))action { + for(NSString* key in self.node.children) { + action([[FTree alloc] initWithName:key withParent:self withNode:[self.node.children objectForKey:key]]); + } +} + +- (void) forEachChildMutationSafe:(void (^)(FTree *))action { + for(NSString* key in [self.node.children copy]) { + action([[FTree alloc] initWithName:key withParent:self withNode:[self.node.children objectForKey:key]]); + } +} + +- (void) forEachDescendant:(void (^)(FTree *))action { + [self forEachDescendant:action includeSelf:NO childrenFirst:NO]; +} + +- (void) forEachDescendant:(void (^)(FTree *))action includeSelf:(BOOL)incSelf childrenFirst:(BOOL)childFirst { + if(incSelf && !childFirst) { + action(self); + } + + [self forEachChild:^(FTree* child) { + [child forEachDescendant:action includeSelf:YES childrenFirst:childFirst]; + }]; + + if(incSelf && childFirst) { + action(self); + } +} + +- (BOOL) forEachAncestor:(BOOL (^)(FTree *))action { + return [self forEachAncestor:action includeSelf:NO]; +} + +- (BOOL) forEachAncestor:(BOOL (^)(FTree *))action includeSelf:(BOOL)incSelf { + FTree* aNode = (incSelf) ? self : self.parent; + while(aNode != nil) { + if(action(aNode)) { + return YES; + } + aNode = aNode.parent; + } + return NO; +} + +- (void) forEachImmediateDescendantWithValue:(void (^)(FTree *))action { + [self forEachChild:^(FTree * child) { + if([child getValue] != nil) { + action(child); + } + else { + [child forEachImmediateDescendantWithValue:action]; + } + }]; +} + +- (BOOL) valueExistsAtOrAbove:(FPath *)path { + FTreeNode* aNode = self.node; + while(aNode != nil) { + if(aNode.value != nil) { + return YES; + } + aNode = [aNode.children objectForKey:path.getFront]; + path = [path popFront]; + } + // XXX Check with Michael if this is correct; deviates from JS. + return NO; +} + +- (FPath *)path { + return [[FPath alloc] initWith:(self.parent == nil) ? self.name : + [NSString stringWithFormat:@"%@/%@", [self.parent path], self.name ]]; +} + +- (void) updateParents { + [self.parent updateChild:self.name withNode:self]; +} + +- (void) updateChild:(NSString*)childName withNode:(FTree *)child { + BOOL childEmpty = [child isEmpty]; + BOOL childExists = self.node.children[childName] != nil; + if(childEmpty && childExists) { + [self.node.children removeObjectForKey:childName]; + self.node.childCount = self.node.childCount - 1; + [self updateParents]; + } + else if(!childEmpty && !childExists) { + [self.node.children setObject:child.node forKey:childName]; + self.node.childCount = self.node.childCount + 1; + [self updateParents]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.h new file mode 100644 index 0000000..7e3497e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FTreeNode : NSObject + +@property (nonatomic, strong) NSMutableDictionary* children; +@property (nonatomic, readwrite, assign) int childCount; +@property (nonatomic, strong) id value; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.m new file mode 100644 index 0000000..9cba9c5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/Utilities/FTreeNode.m @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTreeNode.h" + +@implementation FTreeNode + +@synthesize children; +@synthesize childCount; +@synthesize value; + +- (id)init +{ + self = [super init]; + if (self) { + self.children = [[NSMutableDictionary alloc] init]; + self.childCount = 0; + self.value = nil; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.h new file mode 100644 index 0000000..b23869c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.h @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@class FIndexedNode; +@class FPath; + +/** +* A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully +* initialized in the sense that we know at one point in time, this represented a valid state of the world, e.g. +* initialized with data from the server, or a complete overwrite by the client. It is not necessarily complete because +* it may have been from a tagged query. The filtered flag also tracks whether a node potentially had children removed +* due to a filter. +*/ +@interface FCacheNode : NSObject + +- (id) initWithIndexedNode:(FIndexedNode *)indexedNode + isFullyInitialized:(BOOL)fullyInitialized + isFiltered:(BOOL)filtered; + +- (BOOL) isCompleteForPath:(FPath *)path; +- (BOOL) isCompleteForChild:(NSString *)childKey; + +@property (nonatomic, readonly) BOOL isFullyInitialized; +@property (nonatomic, readonly) BOOL isFiltered; +@property (nonatomic, strong, readonly) FIndexedNode *indexedNode; +@property (nonatomic, strong, readonly) id node; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.m new file mode 100644 index 0000000..4767a25 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCacheNode.m @@ -0,0 +1,60 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FCacheNode.h" +#import "FNode.h" +#import "FPath.h" +#import "FEmptyNode.h" +#import "FIndexedNode.h" + +@interface FCacheNode () +@property (nonatomic, readwrite) BOOL isFullyInitialized; +@property (nonatomic, readwrite) BOOL isFiltered; +@property (nonatomic, strong, readwrite) FIndexedNode *indexedNode; +@end + +@implementation FCacheNode +- (id) initWithIndexedNode:(FIndexedNode *)indexedNode + isFullyInitialized:(BOOL)fullyInitialized + isFiltered:(BOOL)filtered +{ + self = [super init]; + if (self) { + self.indexedNode = indexedNode; + self.isFullyInitialized = fullyInitialized; + self.isFiltered = filtered; + } + return self; +} + +- (BOOL)isCompleteForPath:(FPath *)path { + if (path.isEmpty) { + return self.isFullyInitialized && !self.isFiltered; + } else { + NSString *childKey = [path getFront]; + return [self isCompleteForChild:childKey]; + } +} + +- (BOOL)isCompleteForChild:(NSString *)childKey { + return (self.isFullyInitialized && !self.isFiltered) || [self.node hasChild:childKey]; +} + +- (id)node { + return self.indexedNode.node; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.h new file mode 100644 index 0000000..38277f7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FEvent.h" + +@protocol FEventRegistration; + + +@interface FCancelEvent : NSObject + +- initWithEventRegistration:(id)eventRegistration error:(NSError *)error path:(FPath *)path; + +@property (nonatomic, strong, readonly) NSError *error; +@property (nonatomic, strong, readonly) FPath *path; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.m new file mode 100644 index 0000000..fb73f17 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FCancelEvent.m @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FCancelEvent.h" +#import "FPath.h" +#import "FEventRegistration.h" + +@interface FCancelEvent () +@property (nonatomic, strong) id eventRegistration; +@property (nonatomic, strong, readwrite) NSError *error; +@property (nonatomic, strong, readwrite) FPath *path; +@end + +@implementation FCancelEvent + +@synthesize eventRegistration; +@synthesize error; +@synthesize path; + +- (id)initWithEventRegistration:(id )registration error:(NSError *)anError path:(FPath *)aPath { + self = [super init]; + if (self) { + self.eventRegistration = registration; + self.error = anError; + self.path = aPath; + } + return self; +} + +- (void) fireEventOnQueue:(dispatch_queue_t)queue { + [self.eventRegistration fireEvent:self queue:queue]; +} + +- (BOOL) isCancelEvent { + return YES; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"%@: cancel", self.path]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.h new file mode 100644 index 0000000..d728fe0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDatabaseReference.h" +#import "FNode.h" +#import "FIndexedNode.h" + +@interface FChange : NSObject + +@property (nonatomic, readonly) FIRDataEventType type; +@property (nonatomic, strong, readonly) FIndexedNode *indexedNode; +@property (nonatomic, strong, readonly) NSString *childKey; +@property (nonatomic, strong, readonly) NSString *prevKey; +@property (nonatomic, strong, readonly) FIndexedNode *oldIndexedNode; + +- (id)initWithType:(FIRDataEventType)type indexedNode:(FIndexedNode *)indexedNode; +- (id)initWithType:(FIRDataEventType)type indexedNode:(FIndexedNode *)indexedNode childKey:(NSString *)childKey; +- (id)initWithType:(FIRDataEventType)type + indexedNode:(FIndexedNode *)indexedNode + childKey:(NSString *)childKey + oldIndexedNode:(FIndexedNode *)oldIndexedNode; + +- (FChange *) changeWithPrevKey:(NSString *)prevKey; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.m new file mode 100644 index 0000000..893fce4 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChange.m @@ -0,0 +1,65 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FChange.h" + +@interface FChange () + +@property (nonatomic, strong, readwrite) NSString *prevKey; + +@end + +@implementation FChange + +- (id)initWithType:(FIRDataEventType)type indexedNode:(FIndexedNode *)indexedNode +{ + return [self initWithType:type indexedNode:indexedNode childKey:nil oldIndexedNode:nil]; +} + +- (id)initWithType:(FIRDataEventType)type indexedNode:(FIndexedNode *)indexedNode childKey:(NSString *)childKey +{ + return [self initWithType:type indexedNode:indexedNode childKey:childKey oldIndexedNode:nil]; +} + +- (id)initWithType:(FIRDataEventType)type + indexedNode:(FIndexedNode *)indexedNode + childKey:(NSString *)childKey + oldIndexedNode:(FIndexedNode *)oldIndexedNode +{ + self = [super init]; + if (self != nil) { + self->_type = type; + self->_indexedNode = indexedNode; + self->_childKey = childKey; + self->_oldIndexedNode = oldIndexedNode; + } + return self; +} + +- (FChange *) changeWithPrevKey:(NSString *)prevKey { + FChange *newChange = [[FChange alloc] initWithType:self.type + indexedNode:self.indexedNode + childKey:self.childKey + oldIndexedNode:self.oldIndexedNode]; + newChange.prevKey = prevKey; + return newChange; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"event: %d, data: %@", (int)self.type, [self.indexedNode.node val]]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.h new file mode 100644 index 0000000..8da0b8f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.h @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FEventRegistration.h" +#import "FTypedefs.h" + +@class FRepo; + +@interface FChildEventRegistration : NSObject + +- (id) initWithRepo:(FRepo *)repo + handle:(FIRDatabaseHandle)fHandle + callbacks:(NSDictionary *)callbackBlocks + cancelCallback:(fbt_void_nserror)cancelCallbackBlock; + +/** +* Maps FIRDataEventType (as NSNumber) to fbt_void_datasnapshot_nsstring +*/ +@property (nonatomic, copy, readonly) NSDictionary *callbacks; +@property (nonatomic, copy, readonly) fbt_void_nserror cancelCallback; +@property (nonatomic, readonly) FIRDatabaseHandle handle; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.m new file mode 100644 index 0000000..a98ea47 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FChildEventRegistration.m @@ -0,0 +1,93 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FChildEventRegistration.h" +#import "FIRDatabaseQuery_Private.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FIRDataSnapshot_Private.h" +#import "FDataEvent.h" +#import "FCancelEvent.h" + +@interface FChildEventRegistration () +@property (nonatomic, strong) FRepo *repo; +@property (nonatomic, copy, readwrite) NSDictionary *callbacks; +@property (nonatomic, copy, readwrite) fbt_void_nserror cancelCallback; +@property (nonatomic, readwrite) FIRDatabaseHandle handle; +@end + +@implementation FChildEventRegistration + +- (id)initWithRepo:(id)repo handle:(FIRDatabaseHandle)fHandle callbacks:(NSDictionary *)callbackBlocks cancelCallback:(fbt_void_nserror)cancelCallbackBlock { + self = [super init]; + if (self) { + self.repo = repo; + self.handle = fHandle; + self.callbacks = callbackBlocks; + self.cancelCallback = cancelCallbackBlock; + } + return self; +} + +- (BOOL) responseTo:(FIRDataEventType)eventType { + return self.callbacks != nil && [self.callbacks objectForKey:[NSNumber numberWithInteger:eventType]] != nil; +} + +- (FDataEvent *) createEventFrom:(FChange *)change query:(FQuerySpec *)query { + FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self.repo path:[query.path childFromString:change.childKey]]; + FIRDataSnapshot *snapshot = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:change.indexedNode]; + + FDataEvent *eventData = [[FDataEvent alloc] initWithEventType:change.type eventRegistration:self + dataSnapshot:snapshot prevName:change.prevKey]; + return eventData; +} + +- (void) fireEvent:(id )event queue:(dispatch_queue_t)queue { + if ([event isCancelEvent]) { + FCancelEvent *cancelEvent = event; + FFLog(@"I-RDB061001", @"Raising cancel value event on %@", event.path); + NSAssert(self.cancelCallback != nil, @"Raising a cancel event on a listener with no cancel callback"); + dispatch_async(queue, ^{ + self.cancelCallback(cancelEvent.error); + }); + } else if (self.callbacks != nil) { + FDataEvent *dataEvent = event; + FFLog(@"I-RDB061002", @"Raising event callback (%ld) on %@", (long)dataEvent.eventType, dataEvent.path); + fbt_void_datasnapshot_nsstring callback = [self.callbacks objectForKey:[NSNumber numberWithInteger:dataEvent.eventType]]; + + if (callback != nil) { + dispatch_async(queue, ^{ + callback(dataEvent.snapshot, dataEvent.prevName); + }); + } + } +} + +- (FCancelEvent *) createCancelEventFromError:(NSError *)error path:(FPath *)path { + if (self.cancelCallback != nil) { + return [[FCancelEvent alloc] initWithEventRegistration:self error:error path:path]; + } else { + return nil; + } +} + +- (BOOL) matches:(id)other { + return self.handle == NSNotFound || other.handle == NSNotFound || self.handle == other.handle; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.h new file mode 100644 index 0000000..da90b03 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDataSnapshot.h" +#import "FIRDatabaseReference.h" +#import "FTupleUserCallback.h" +#import "FEvent.h" + +@protocol FEventRegistration; +@protocol FIndex; + +@interface FDataEvent : NSObject + +- initWithEventType:(FIRDataEventType)type eventRegistration:(id)eventRegistration + dataSnapshot:(FIRDataSnapshot *)dataSnapshot; +- initWithEventType:(FIRDataEventType)type eventRegistration:(id)eventRegistration + dataSnapshot:(FIRDataSnapshot *)snapshot prevName:(NSString *)prevName; + + +@property (nonatomic, strong, readonly) id eventRegistration; +@property (nonatomic, strong, readonly) FIRDataSnapshot * snapshot; +@property (nonatomic, strong, readonly) NSString* prevName; +@property (nonatomic, readonly) FIRDataEventType eventType; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.m new file mode 100644 index 0000000..6c97faf --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FDataEvent.m @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FDataEvent.h" +#import "FEventRegistration.h" +#import "FIndex.h" +#import "FIRDatabaseQuery_Private.h" + +@interface FDataEvent () +@property (nonatomic, strong, readwrite) id eventRegistration; +@property (nonatomic, strong, readwrite) FIRDataSnapshot *snapshot; +@property (nonatomic, strong, readwrite) NSString *prevName; +@property (nonatomic, readwrite) FIRDataEventType eventType; +@end + +@implementation FDataEvent + +@synthesize eventRegistration; +@synthesize snapshot; +@synthesize prevName; +@synthesize eventType; + +- (id)initWithEventType:(FIRDataEventType)type eventRegistration:(id )registration dataSnapshot:(FIRDataSnapshot *)dataSnapshot { + return [self initWithEventType:type eventRegistration:registration dataSnapshot:dataSnapshot prevName:nil]; +} + +- (id)initWithEventType:(FIRDataEventType)type eventRegistration:(id )registration dataSnapshot:(FIRDataSnapshot *)dataSnapshot prevName:(NSString *)previousName { + self = [super init]; + if (self) { + self.eventRegistration = registration; + self.snapshot = dataSnapshot; + self.prevName = previousName; + self.eventType = type; + } + return self; +} + +- (FPath *) path { + // Used for logging, so delay calculation + FIRDatabaseReference *ref = self.snapshot.ref; + if (self.eventType == FIRDataEventTypeValue) { + return ref.path; + } else { + return ref.parent.path; + } +} + +- (void) fireEventOnQueue:(dispatch_queue_t)queue { + [self.eventRegistration fireEvent:self queue:queue]; +} + +- (BOOL) isCancelEvent { + return NO; +} + + +- (NSString *) description { + return [NSString stringWithFormat:@"event %d, data: %@", (int) eventType, [snapshot value]]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEvent.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEvent.h new file mode 100644 index 0000000..6b9e31a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEvent.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDataEventType.h" + +@class FPath; + +@protocol FEvent +- (FPath *) path; +- (void) fireEventOnQueue:(dispatch_queue_t)queue; +- (BOOL) isCancelEvent; +- (NSString *) description; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.h new file mode 100644 index 0000000..01a0130 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTypedefs.h" + +@class FPath; +@class FRepo; +@class FIRDatabaseConfig; + +/** +* Left as instance methods rather than class methods so that we could potentially callback on different queues for different repos. +* This is semi-parallel to JS's FEventQueue +*/ +@interface FEventRaiser : NSObject + +- (id)initWithQueue:(dispatch_queue_t)queue; + +- (void) raiseEvents:(NSArray *)eventDataList; +- (void) raiseCallback:(fbt_void_void)callback; +- (void) raiseCallbacks:(NSArray *)callbackList; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.m new file mode 100644 index 0000000..94a0907 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRaiser.m @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FEventRaiser.h" +#import "FDataEvent.h" +#import "FTypedefs.h" +#import "FUtilities.h" +#import "FTupleUserCallback.h" +#import "FRepo.h" +#import "FRepoManager.h" + +@interface FEventRaiser () + +@property (nonatomic, strong) dispatch_queue_t queue; + +@end + +/** +* This class exists for symmetry with other clients, but since events are async, we don't need to do the complicated +* stuff the JS client does to preserve event order. +*/ +@implementation FEventRaiser + +- (id)init { + [NSException raise:NSInternalInconsistencyException format:@"Can't use default constructor"]; + return nil; +} + +- (id)initWithQueue:(dispatch_queue_t)queue { + self = [super init]; + if (self != nil) { + self->_queue = queue; + } + return self; +} + +- (void) raiseEvents:(NSArray *)eventDataList { + for (id event in eventDataList) { + [event fireEventOnQueue:self.queue]; + } +} + +- (void) raiseCallback:(fbt_void_void)callback { + dispatch_async(self.queue, callback); +} + +- (void) raiseCallbacks:(NSArray *)callbackList { + for (fbt_void_void callback in callbackList) { + dispatch_async(self.queue, callback); + } +} + ++ (void) raiseCallbacks:(NSArray *)callbackList queue:(dispatch_queue_t)queue { + for (fbt_void_void callback in callbackList) { + dispatch_async(queue, callback); + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRegistration.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRegistration.h new file mode 100644 index 0000000..5b845ac --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FEventRegistration.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FChange.h" +#import "FIRDataEventType.h" + +@protocol FEvent; +@class FDataEvent; +@class FCancelEvent; +@class FQuerySpec; + +@protocol FEventRegistration +- (BOOL) responseTo:(FIRDataEventType)eventType; +- (FDataEvent *) createEventFrom:(FChange *)change query:(FQuerySpec *)query; +- (void) fireEvent:(id)event queue:(dispatch_queue_t)queue; +- (FCancelEvent *) createCancelEventFromError:(NSError *)error path:(FPath *)path; +/** +* Used to figure out what event registration match the event registration that needs to be removed. +*/ +- (BOOL) matches:(id)other; +@property (nonatomic, readonly) FIRDatabaseHandle handle; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.h new file mode 100644 index 0000000..669e012 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FEventRegistration.h" + +/** + * A singleton event registration to mark a query as keep synced + */ +@interface FKeepSyncedEventRegistration : NSObject + ++ (FKeepSyncedEventRegistration *)instance; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.m new file mode 100644 index 0000000..806d54f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FKeepSyncedEventRegistration.m @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FKeepSyncedEventRegistration.h" + +@interface FKeepSyncedEventRegistration () + +@end + +@implementation FKeepSyncedEventRegistration + ++ (FKeepSyncedEventRegistration *)instance { + static dispatch_once_t onceToken; + static FKeepSyncedEventRegistration *keepSynced; + dispatch_once(&onceToken, ^{ + keepSynced = [[FKeepSyncedEventRegistration alloc] init]; + }); + return keepSynced; +} + +- (BOOL) responseTo:(FIRDataEventType)eventType { + return NO; +} + +- (FDataEvent *) createEventFrom:(FChange *)change query:(FQuerySpec *)query { + [NSException raise:NSInternalInconsistencyException format:@"Should never create event for FKeepSyncedEventRegistration"]; + return nil; +} + +- (void) fireEvent:(id)event queue:(dispatch_queue_t)queue { + [NSException raise:NSInternalInconsistencyException format:@"Should never raise event for FKeepSyncedEventRegistration"]; +} + +- (FCancelEvent *) createCancelEventFromError:(NSError *)error path:(FPath *)path { + // Don't create cancel events.... + return nil; +} + +- (FIRDatabaseHandle) handle { + // TODO[offline]: returning arbitray, can't return NSNotFound since that is used to match other event registrations + // We should really redo this to match on different kind of events (single observer, all observers, cancelled) + // rather than on a NSNotFound handle... + return NSNotFound - 1; +} + +- (BOOL) matches:(id)other { + // Only matches singleton instance + return self == other; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.h new file mode 100644 index 0000000..1220c60 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FEventRegistration.h" +#import "FTypedefs.h" + +@class FRepo; + +@interface FValueEventRegistration : NSObject + +- (id) initWithRepo:(FRepo *)repo + handle:(FIRDatabaseHandle)fHandle + callback:(fbt_void_datasnapshot)callbackBlock + cancelCallback:(fbt_void_nserror)cancelCallbackBlock; + +@property (nonatomic, copy, readonly) fbt_void_datasnapshot callback; +@property (nonatomic, copy, readonly) fbt_void_nserror cancelCallback; +@property (nonatomic, readonly) FIRDatabaseHandle handle; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.m new file mode 100644 index 0000000..6a98629 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FValueEventRegistration.m @@ -0,0 +1,90 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FValueEventRegistration.h" +#import "FIRDatabaseQuery_Private.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FIRDataSnapshot_Private.h" +#import "FCancelEvent.h" +#import "FDataEvent.h" + +@interface FValueEventRegistration () +@property (nonatomic, strong) FRepo* repo; +@property (nonatomic, copy, readwrite) fbt_void_datasnapshot callback; +@property (nonatomic, copy, readwrite) fbt_void_nserror cancelCallback; +@property (nonatomic, readwrite) FIRDatabaseHandle handle; +@end + +@implementation FValueEventRegistration + +- (id) initWithRepo:(FRepo *)repo + handle:(FIRDatabaseHandle)fHandle + callback:(fbt_void_datasnapshot)callbackBlock + cancelCallback:(fbt_void_nserror)cancelCallbackBlock { + self = [super init]; + if (self) { + self.repo = repo; + self.handle = fHandle; + self.callback = callbackBlock; + self.cancelCallback = cancelCallbackBlock; + } + return self; +} + +- (BOOL) responseTo:(FIRDataEventType)eventType { + return eventType == FIRDataEventTypeValue; +} + +- (FDataEvent *) createEventFrom:(FChange *)change query:(FQuerySpec *)query { + FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self.repo path:query.path]; + FIRDataSnapshot *snapshot = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:change.indexedNode]; + FDataEvent *eventData = [[FDataEvent alloc] initWithEventType:FIRDataEventTypeValue eventRegistration:self + dataSnapshot:snapshot]; + return eventData; +} + +- (void) fireEvent:(id )event queue:(dispatch_queue_t)queue { + if ([event isCancelEvent]) { + FCancelEvent *cancelEvent = event; + FFLog(@"I-RDB065001", @"Raising cancel value event on %@", event.path); + NSAssert(self.cancelCallback != nil, @"Raising a cancel event on a listener with no cancel callback"); + dispatch_async(queue, ^{ + self.cancelCallback(cancelEvent.error); + }); + } else if (self.callback != nil) { + FDataEvent *dataEvent = event; + FFLog(@"I-RDB065002", @"Raising value event on %@", dataEvent.snapshot.key); + dispatch_async(queue, ^{ + self.callback(dataEvent.snapshot); + }); + } +} + +- (FCancelEvent *) createCancelEventFromError:(NSError *)error path:(FPath *)path { + if (self.cancelCallback != nil) { + return [[FCancelEvent alloc] initWithEventRegistration:self error:error path:path]; + } else { + return nil; + } +} + +- (BOOL) matches:(id)other { + return self.handle == NSNotFound || other.handle == NSNotFound || self.handle == other.handle; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.h new file mode 100644 index 0000000..2d0761a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@protocol FOperation; +@protocol FEventRegistration; +@class FWriteTreeRef; +@class FQuerySpec; +@class FChange; +@class FPath; +@class FViewCache; + +@interface FViewOperationResult : NSObject + +@property (nonatomic, strong, readonly) NSArray* changes; +@property (nonatomic, strong, readonly) NSArray* events; + +@end + + +@interface FView : NSObject + +@property (nonatomic, strong, readonly) FQuerySpec *query; + +- (id) initWithQuery:(FQuerySpec *)query initialViewCache:(FViewCache *)initialViewCache; + +- (id) eventCache; +- (id) serverCache; +- (id) completeServerCacheFor:(FPath*)path; +- (BOOL) isEmpty; + +- (void) addEventRegistration:(id)eventRegistration; +- (NSArray *) removeEventRegistration:(id)eventRegistration cancelError:(NSError *)cancelError; + +- (FViewOperationResult *) applyOperation:(id )operation writesCache:(FWriteTreeRef *)writesCache serverCache:(id )optCompleteServerCache; +- (NSArray *) initialEvents:(id)registration; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.m new file mode 100644 index 0000000..1aea4d7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FView.m @@ -0,0 +1,223 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FView.h" +#import "FNode.h" +#import "FWriteTreeRef.h" +#import "FOperation.h" +#import "FIRDatabaseQuery.h" +#import "FIRDatabaseQuery_Private.h" +#import "FEventRegistration.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FViewCache.h" +#import "FPath.h" +#import "FEventGenerator.h" +#import "FOperationSource.h" +#import "FCancelEvent.h" +#import "FIndexedFilter.h" +#import "FCacheNode.h" +#import "FEmptyNode.h" +#import "FViewProcessor.h" +#import "FViewProcessorResult.h" +#import "FIndexedNode.h" + +@interface FViewOperationResult () + +@property (nonatomic, strong, readwrite) NSArray *changes; +@property (nonatomic, strong, readwrite) NSArray *events; + +@end + +@implementation FViewOperationResult + +- (id)initWithChanges:(NSArray *)changes events:(NSArray *)events { + self = [super init]; + if (self != nil) { + self->_changes = changes; + self->_events = events; + } + return self; +} + +@end + +/** +* A view represents a specific location and query that has 1 or more event registrations. +* +* It does several things: +* - Maintains the list of event registration for this location/query. +* - Maintains a cache of the data visible for this location/query. +* - Applies new operations (via applyOperation), updates the cache, and based on the event +* registrations returns the set of events to be raised. +*/ +@interface FView () + +@property (nonatomic, strong, readwrite) FQuerySpec *query; +@property (nonatomic, strong) FViewProcessor *processor; +@property (nonatomic, strong) FViewCache *viewCache; +@property (nonatomic, strong) NSMutableArray *eventRegistrations; +@property (nonatomic, strong) FEventGenerator *eventGenerator; + +@end + +@implementation FView +- (id) initWithQuery:(FQuerySpec *)query initialViewCache:(FViewCache *)initialViewCache { + self = [super init]; + if (self) { + self.query = query; + + FIndexedFilter *indexFilter = [[FIndexedFilter alloc] initWithIndex:query.index]; + id filter = query.params.nodeFilter; + self.processor = [[FViewProcessor alloc] initWithFilter:filter]; + FCacheNode *initialServerCache = initialViewCache.cachedServerSnap; + FCacheNode *initialEventCache = initialViewCache.cachedEventSnap; + + // Don't filter server node with other filter than index, wait for tagged listen + FIndexedNode *emptyIndexedNode = [FIndexedNode indexedNodeWithNode:[FEmptyNode emptyNode] index:query.index]; + FIndexedNode *serverSnap = [indexFilter updateFullNode:emptyIndexedNode + withNewNode:initialServerCache.indexedNode + accumulator:nil]; + FIndexedNode *eventSnap = [filter updateFullNode:emptyIndexedNode + withNewNode:initialEventCache.indexedNode + accumulator:nil]; + FCacheNode *newServerCache = [[FCacheNode alloc] initWithIndexedNode:serverSnap + isFullyInitialized:initialServerCache.isFullyInitialized + isFiltered:indexFilter.filtersNodes]; + FCacheNode *newEventCache = [[FCacheNode alloc] initWithIndexedNode:eventSnap + isFullyInitialized:initialEventCache.isFullyInitialized + isFiltered:filter.filtersNodes]; + + self.viewCache = [[FViewCache alloc] initWithEventCache:newEventCache serverCache:newServerCache]; + + self.eventRegistrations = [[NSMutableArray alloc] init]; + + self.eventGenerator = [[FEventGenerator alloc] initWithQuery:query]; + } + + return self; +} + +- (id ) serverCache { + return self.viewCache.cachedServerSnap.node; +} + +- (id ) eventCache { + return self.viewCache.cachedEventSnap.node; +} + +- (id ) completeServerCacheFor:(FPath*)path { + id cache = self.viewCache.completeServerSnap; + if (cache) { + // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and + // we need to see if it contains the child we're interested in. + if ([self.query loadsAllData] || + (!path.isEmpty && ![cache getImmediateChild:path.getFront].isEmpty)) { + return [cache getChild:path]; + } + } + return nil; +} + +- (BOOL) isEmpty { + return self.eventRegistrations.count == 0; +} + +- (void) addEventRegistration:(id )eventRegistration { + [self.eventRegistrations addObject:eventRegistration]; +} + +/** +* @param eventRegistration If null, remove all callbacks. +* @param cancelError If a cancelError is provided, appropriate cancel events will be returned. +* @return Cancel events, if cancelError was provided. +*/ +- (NSArray *) removeEventRegistration:(id )eventRegistration cancelError:(NSError *)cancelError { + NSMutableArray *cancelEvents = [[NSMutableArray alloc] init]; + if (cancelError != nil) { + NSAssert(eventRegistration == nil, @"A cancel should cancel all event registrations."); + FPath *path = self.query.path; + for (id registration in self.eventRegistrations) { + FCancelEvent *maybeEvent = [registration createCancelEventFromError:cancelError path:path]; + if (maybeEvent) { + [cancelEvents addObject:maybeEvent]; + } + } + } + + if (eventRegistration) { + NSUInteger i = 0; + while (i < self.eventRegistrations.count) { + id existing = self.eventRegistrations[i]; + if ([existing matches:eventRegistration]) { + [self.eventRegistrations removeObjectAtIndex:i]; + } else { + i++; + } + } + } else { + [self.eventRegistrations removeAllObjects]; + } + return cancelEvents; +} + +/** + * Applies the given Operation, updates our cache, and returns the appropriate events and changes + */ +- (FViewOperationResult *) applyOperation:(id )operation writesCache:(FWriteTreeRef *)writesCache serverCache:(id )optCompleteServerCache { + if (operation.type == FOperationTypeMerge && operation.source.queryParams != nil) { + NSAssert(self.viewCache.completeServerSnap != nil, @"We should always have a full cache before handling merges"); + NSAssert(self.viewCache.completeEventSnap != nil, @"Missing event cache, even though we have a server cache"); + } + FViewCache *oldViewCache = self.viewCache; + FViewProcessorResult *result = [self.processor applyOperationOn:oldViewCache operation:operation writesCache:writesCache completeCache:optCompleteServerCache]; + + NSAssert(result.viewCache.cachedServerSnap.isFullyInitialized || !oldViewCache.cachedServerSnap.isFullyInitialized, @"Once a server snap is complete, it should never go back."); + + self.viewCache = result.viewCache; + NSArray *events = [self generateEventsForChanges:result.changes eventCache:result.viewCache.cachedEventSnap.indexedNode registration:nil]; + return [[FViewOperationResult alloc] initWithChanges:result.changes events:events]; +} + +- (NSArray *) initialEvents:(id)registration { + FCacheNode *eventSnap = self.viewCache.cachedEventSnap; + NSMutableArray *initialChanges = [[NSMutableArray alloc] init]; + [eventSnap.indexedNode.node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:node]; + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded indexedNode:indexed childKey:key]; + [initialChanges addObject:change]; + }]; + if (eventSnap.isFullyInitialized) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeValue indexedNode:eventSnap.indexedNode]; + [initialChanges addObject:change]; + } + return [self generateEventsForChanges:initialChanges eventCache:eventSnap.indexedNode registration:registration]; +} + +- (NSArray *) generateEventsForChanges:(NSArray *)changes eventCache:(FIndexedNode *)eventCache registration:(id)registration { + NSArray *registrations; + if (registration == nil) { + registrations = [[NSArray alloc] initWithArray:self.eventRegistrations]; + } else { + registrations = [[NSArray alloc] initWithObjects:registration, nil]; + } + return [self.eventGenerator generateEventsForChanges:changes eventCache:eventCache eventRegistrations:registrations]; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FView (%@)", self.query]; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.h new file mode 100644 index 0000000..4d01877 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.h @@ -0,0 +1,35 @@ +#/* +* Copyright 2017 Google +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#import + +@protocol FNode; +@class FCacheNode; +@class FIndexedNode; + +@interface FViewCache : NSObject + +- (id) initWithEventCache:(FCacheNode *)eventCache serverCache:(FCacheNode *)serverCache; + +- (FViewCache *) updateEventSnap:(FIndexedNode *)eventSnap isComplete:(BOOL)complete isFiltered:(BOOL)filtered; +- (FViewCache *) updateServerSnap:(FIndexedNode *)serverSnap isComplete:(BOOL)complete isFiltered:(BOOL)filtered; + +@property (nonatomic, strong, readonly) FCacheNode *cachedEventSnap; +@property (nonatomic, strong, readonly) id completeEventSnap; +@property (nonatomic, strong, readonly) FCacheNode *cachedServerSnap; +@property (nonatomic, strong, readonly) id completeServerSnap; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.m new file mode 100644 index 0000000..c6ec8b1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/FViewCache.m @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FViewCache.h" +#import "FCacheNode.h" +#import "FNode.h" +#import "FEmptyNode.h" + +@interface FViewCache () +@property (nonatomic, strong, readwrite) FCacheNode *cachedEventSnap; +@property (nonatomic, strong, readwrite) FCacheNode *cachedServerSnap; +@end + +@implementation FViewCache + +- (id) initWithEventCache:(FCacheNode *)eventCache serverCache:(FCacheNode *)serverCache { + self = [super init]; + if (self) { + self.cachedEventSnap = eventCache; + self.cachedServerSnap = serverCache; + } + return self; +} + +- (FViewCache *) updateEventSnap:(FIndexedNode *)eventSnap isComplete:(BOOL)complete isFiltered:(BOOL)filtered { + FCacheNode *updatedEventCache = [[FCacheNode alloc] initWithIndexedNode:eventSnap + isFullyInitialized:complete + isFiltered:filtered]; + return [[FViewCache alloc] initWithEventCache:updatedEventCache serverCache:self.cachedServerSnap]; +} + +- (FViewCache *) updateServerSnap:(FIndexedNode *)serverSnap isComplete:(BOOL)complete isFiltered:(BOOL)filtered { + FCacheNode *updatedServerCache = [[FCacheNode alloc] initWithIndexedNode:serverSnap + isFullyInitialized:complete + isFiltered:filtered]; + return [[FViewCache alloc] initWithEventCache:self.cachedEventSnap serverCache:updatedServerCache]; +} + +- (id) completeEventSnap { + return (self.cachedEventSnap.isFullyInitialized) ? self.cachedEventSnap.node : nil; +} + +- (id) completeServerSnap { + return (self.cachedServerSnap.isFullyInitialized) ? self.cachedServerSnap.node : nil; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.h new file mode 100644 index 0000000..59b0a85 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FChange; + + +@interface FChildChangeAccumulator : NSObject + +- (id) init; +- (void) trackChildChange:(FChange *)change; +- (NSArray *) changes; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.m new file mode 100644 index 0000000..e43fd7c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FChildChangeAccumulator.m @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FChildChangeAccumulator.h" +#import "FChange.h" +#import "FIndex.h" + +@interface FChildChangeAccumulator () +@property (nonatomic, strong) NSMutableDictionary *changeMap; +@end + +@implementation FChildChangeAccumulator + +- (id) init { + self = [super init]; + if (self) { + self.changeMap = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void) trackChildChange:(FChange *)change { + FIRDataEventType type = change.type; + NSString *childKey = change.childKey; + NSAssert(type == FIRDataEventTypeChildAdded || type == FIRDataEventTypeChildChanged || type == FIRDataEventTypeChildRemoved, @"Only child changes supported for tracking."); + NSAssert(![change.childKey isEqualToString:@".priority"], @"Changes not tracked on priority"); + if (self.changeMap[childKey] != nil) { + FChange *oldChange = [self.changeMap objectForKey:childKey]; + FIRDataEventType oldType = oldChange.type; + if (type == FIRDataEventTypeChildAdded && oldType == FIRDataEventTypeChildRemoved) { + FChange *newChange = [[FChange alloc] initWithType:FIRDataEventTypeChildChanged + indexedNode:change.indexedNode + childKey:childKey + oldIndexedNode:oldChange.indexedNode]; + [self.changeMap setObject:newChange forKey:childKey]; + } else if (type == FIRDataEventTypeChildRemoved && oldType == FIRDataEventTypeChildAdded) { + [self.changeMap removeObjectForKey:childKey]; + } else if (type == FIRDataEventTypeChildRemoved && oldType == FIRDataEventTypeChildChanged) { + FChange *newChange = [[FChange alloc] initWithType:FIRDataEventTypeChildRemoved + indexedNode:oldChange.oldIndexedNode + childKey:childKey]; + [self.changeMap setObject:newChange forKey:childKey]; + } else if (type == FIRDataEventTypeChildChanged && oldType == FIRDataEventTypeChildAdded) { + FChange *newChange = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded + indexedNode:change.indexedNode + childKey:childKey]; + [self.changeMap setObject:newChange forKey:childKey]; + } else if (type == FIRDataEventTypeChildChanged && oldType == FIRDataEventTypeChildChanged) { + FChange *newChange = [[FChange alloc] initWithType:FIRDataEventTypeChildChanged + indexedNode:change.indexedNode + childKey:childKey + oldIndexedNode:oldChange.oldIndexedNode]; + [self.changeMap setObject:newChange forKey:childKey]; + } else { + NSString *reason = [NSString stringWithFormat:@"Illegal combination of changes: %@ occurred after %@", change, oldChange]; + @throw [[NSException alloc] initWithName:@"FirebaseDatabaseInternalError" reason:reason userInfo:nil]; + } + } else { + [self.changeMap setObject:change forKey:childKey]; + } +} + +- (NSArray *) changes { + return [self.changeMap allValues]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FCompleteChildSource.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FCompleteChildSource.h new file mode 100644 index 0000000..4e99045 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FCompleteChildSource.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@class FNamedNode; +@protocol FIndex; + +@protocol FCompleteChildSource + +- (id) completeChild:(NSString *)childKey; +- (FNamedNode *) childByIndex:(id)index afterChild:(FNamedNode *)child isReverse:(BOOL)reverse; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.h new file mode 100644 index 0000000..5081a77 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNodeFilter.h" + +@protocol FIndex; + + +@interface FIndexedFilter : NSObject + +- (id) initWithIndex:(id)theIndex; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.m new file mode 100644 index 0000000..44c411c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FIndexedFilter.m @@ -0,0 +1,147 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FNode.h" +#import "FIndexedFilter.h" +#import "FChildChangeAccumulator.h" +#import "FIndex.h" +#import "FChange.h" +#import "FChildrenNode.h" +#import "FKeyIndex.h" +#import "FEmptyNode.h" +#import "FIndexedNode.h" + +@interface FIndexedFilter () +@property (nonatomic, strong, readwrite) id index; +@end + +@implementation FIndexedFilter +- (id) initWithIndex:(id)theIndex { + self = [super init]; + if (self) { + self.index = theIndex; + } + return self; +} + +- (FIndexedNode *)updateChildIn:(FIndexedNode *)indexedNode + forChildKey:(NSString *)childKey + newChild:(id)newChildSnap + affectedPath:(FPath *)affectedPath + fromSource:(id)source + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + NSAssert([indexedNode hasIndex:self.index], @"The index in FIndexedNode must match the index of the filter"); + id node = indexedNode.node; + id oldChildSnap = [node getImmediateChild:childKey]; + + // Check if anything actually changed. + if ([[oldChildSnap getChild:affectedPath] isEqual:[newChildSnap getChild:affectedPath]]) { + // There's an edge case where a child can enter or leave the view because affectedPath was set to null. + // In this case, affectedPath will appear null in both the old and new snapshots. So we need + // to avoid treating these cases as "nothing changed." + if (oldChildSnap.isEmpty == newChildSnap.isEmpty) { + // Nothing changed. + #ifdef DEBUG + NSAssert([oldChildSnap isEqual:newChildSnap], @"Old and new snapshots should be equal."); + #endif + + return indexedNode; + } + } + if (optChangeAccumulator) { + if (newChildSnap.isEmpty) { + if ([node hasChild:childKey]) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildRemoved + indexedNode:[FIndexedNode indexedNodeWithNode:oldChildSnap] + childKey:childKey]; + [optChangeAccumulator trackChildChange:change]; + } else { + NSAssert(node.isLeafNode, @"A child remove without an old child only makes sense on a leaf node."); + } + } else if (oldChildSnap.isEmpty) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded + indexedNode:[FIndexedNode indexedNodeWithNode:newChildSnap] + childKey:childKey]; + [optChangeAccumulator trackChildChange:change]; + } else { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildChanged + indexedNode:[FIndexedNode indexedNodeWithNode:newChildSnap] + childKey:childKey + oldIndexedNode:[FIndexedNode indexedNodeWithNode:oldChildSnap]]; + [optChangeAccumulator trackChildChange:change]; + } + } + if (node.isLeafNode && newChildSnap.isEmpty) { + return indexedNode; + } else { + return [indexedNode updateChild:childKey withNewChild:newChildSnap]; + } +} + +- (FIndexedNode *)updateFullNode:(FIndexedNode *)oldSnap + withNewNode:(FIndexedNode *)newSnap + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + if (optChangeAccumulator) { + [oldSnap.node enumerateChildrenUsingBlock:^(NSString *childKey, id childNode, BOOL *stop) { + if (![newSnap.node hasChild:childKey]) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildRemoved + indexedNode:[FIndexedNode indexedNodeWithNode:childNode] + childKey:childKey]; + [optChangeAccumulator trackChildChange:change]; + } + }]; + + [newSnap.node enumerateChildrenUsingBlock:^(NSString *childKey, id childNode, BOOL *stop) { + if ([oldSnap.node hasChild:childKey]) { + id oldChildSnap = [oldSnap.node getImmediateChild:childKey]; + if (![oldChildSnap isEqual:childNode]) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildChanged + indexedNode:[FIndexedNode indexedNodeWithNode:childNode] + childKey:childKey + oldIndexedNode:[FIndexedNode indexedNodeWithNode:oldChildSnap]]; + [optChangeAccumulator trackChildChange:change]; + } + } else { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded + indexedNode:[FIndexedNode indexedNodeWithNode:childNode] + childKey:childKey]; + [optChangeAccumulator trackChildChange:change]; + } + }]; + } + return newSnap; +} + +- (FIndexedNode *)updatePriority:(id)priority forNode:(FIndexedNode *)oldSnap +{ + if ([oldSnap.node isEmpty]) { + return oldSnap; + } else { + return [oldSnap updatePriority:priority]; + } +} + +- (BOOL) filtersNodes { + return NO; +} + +- (id) indexedFilter { + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.h new file mode 100644 index 0000000..1690980 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNodeFilter.h" + +@class FQueryParams; + + +@interface FLimitedFilter : NSObject + +- (id) initWithQueryParams:(FQueryParams *)params; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.m new file mode 100644 index 0000000..8bc6e87 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FLimitedFilter.m @@ -0,0 +1,243 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FLimitedFilter.h" +#import "FChildChangeAccumulator.h" +#import "FIndex.h" +#import "FRangedFilter.h" +#import "FQueryParams.h" +#import "FQueryParams.h" +#import "FNamedNode.h" +#import "FEmptyNode.h" +#import "FChildrenNode.h" +#import "FCompleteChildSource.h" +#import "FChange.h" +#import "FTreeSortedDictionary.h" + +@interface FLimitedFilter () +@property (nonatomic, strong) FRangedFilter *rangedFilter; +@property (nonatomic, strong, readwrite) id index; +@property (nonatomic) NSInteger limit; +@property (nonatomic) BOOL reverse; + +@end + +@implementation FLimitedFilter +- (id) initWithQueryParams:(FQueryParams *)params { + self = [super init]; + if (self) { + self.rangedFilter = [[FRangedFilter alloc] initWithQueryParams:params]; + self.index = params.index; + self.limit = params.limit; + self.reverse = !params.isViewFromLeft; + } + return self; +} + + +- (FIndexedNode *)updateChildIn:(FIndexedNode *)oldSnap + forChildKey:(NSString *)childKey + newChild:(id)newChildSnap + affectedPath:(FPath *)affectedPath + fromSource:(id)source + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + if (![self.rangedFilter matchesKey:childKey andNode:newChildSnap]) { + newChildSnap = [FEmptyNode emptyNode]; + } + if ([[oldSnap.node getImmediateChild:childKey] isEqual:newChildSnap]) { + // No change + return oldSnap; + } else if (oldSnap.node.numChildren < self.limit) { + return [[self.rangedFilter indexedFilter] updateChildIn:oldSnap + forChildKey:childKey + newChild:newChildSnap + affectedPath:affectedPath + fromSource:source + accumulator:optChangeAccumulator]; + } else { + return [self fullLimitUpdateNode:oldSnap + forChildKey:childKey + newChild:newChildSnap + fromSource:source + accumulator:optChangeAccumulator]; + } +} + +- (FIndexedNode *)fullLimitUpdateNode:(FIndexedNode *)oldIndexed + forChildKey:(NSString *)childKey + newChild:(id)newChildSnap + fromSource:(id)source + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + NSAssert(oldIndexed.node.numChildren == self.limit, @"Should have number of children equal to limit."); + + FNamedNode *windowBoundary = self.reverse ? oldIndexed.firstChild : oldIndexed.lastChild; + + BOOL inRange = [self.rangedFilter matchesKey:childKey andNode:newChildSnap]; + if ([oldIndexed.node hasChild:childKey]) { + // `childKey` was already in `oldSnap`. Figure out if it remains in the window or needs to be replaced. + id oldChildSnap = [oldIndexed.node getImmediateChild:childKey]; + + // In case the `newChildSnap` falls outside the window, get the `nextChild` that might replace it. + FNamedNode *nextChild = [source childByIndex:self.index afterChild:windowBoundary isReverse:(BOOL)self.reverse]; + if (nextChild != nil && ([nextChild.name isEqualToString:childKey] || + [oldIndexed.node hasChild:nextChild.name])) { + // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't + // been applied to the limited filter yet. Ignore this next child which will be updated later in + // the limited filter... + nextChild = [source childByIndex:self.index afterChild:nextChild isReverse:self.reverse]; + } + + + + // Figure out if `newChildSnap` is in range and ordered before `nextChild` + BOOL remainsInWindow = inRange && !newChildSnap.isEmpty; + remainsInWindow = remainsInWindow && (!nextChild || [self.index compareKey:nextChild.name + andNode:nextChild.node + toOtherKey:childKey + andNode:newChildSnap + reverse:self.reverse] >= NSOrderedSame); + if (remainsInWindow) { + // `newChildSnap` is ordered before `nextChild`, so it's a child changed event + if (optChangeAccumulator != nil) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildChanged + indexedNode:[FIndexedNode indexedNodeWithNode:newChildSnap] + childKey:childKey + oldIndexedNode:[FIndexedNode indexedNodeWithNode:oldChildSnap]]; + [optChangeAccumulator trackChildChange:change]; + } + return [oldIndexed updateChild:childKey withNewChild:newChildSnap]; + } else { + // `newChildSnap` is ordered after `nextChild`, so it's a child removed event + if (optChangeAccumulator != nil) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildRemoved + indexedNode:[FIndexedNode indexedNodeWithNode:oldChildSnap] + childKey:childKey]; + [optChangeAccumulator trackChildChange:change]; + } + FIndexedNode *newIndexed = [oldIndexed updateChild:childKey withNewChild:[FEmptyNode emptyNode]]; + + // We need to check if the `nextChild` is actually in range before adding it + BOOL nextChildInRange = (nextChild != nil) && [self.rangedFilter matchesKey:nextChild.name + andNode:nextChild.node]; + if (nextChildInRange) { + if (optChangeAccumulator != nil) { + FChange *change = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded + indexedNode:[FIndexedNode indexedNodeWithNode:nextChild.node] + childKey:nextChild.name]; + [optChangeAccumulator trackChildChange:change]; + } + return [newIndexed updateChild:nextChild.name withNewChild:nextChild.node]; + } else { + return newIndexed; + } + } + } else if (newChildSnap.isEmpty) { + // We're deleting a node, but it was not in the window, so ignore it. + return oldIndexed; + } else if (inRange) { + // `newChildSnap` is in range, but was ordered after `windowBoundary`. If this has changed, we bump out the + // `windowBoundary` and add the `newChildSnap` + if ([self.index compareKey:windowBoundary.name + andNode:windowBoundary.node + toOtherKey:childKey + andNode:newChildSnap + reverse:self.reverse] >= NSOrderedSame) { + if (optChangeAccumulator != nil) { + FChange *removedChange = [[FChange alloc] initWithType:FIRDataEventTypeChildRemoved + indexedNode:[FIndexedNode indexedNodeWithNode:windowBoundary.node] + childKey:windowBoundary.name]; + FChange *addedChange = [[FChange alloc] initWithType:FIRDataEventTypeChildAdded + indexedNode:[FIndexedNode indexedNodeWithNode:newChildSnap] + childKey:childKey]; + [optChangeAccumulator trackChildChange:removedChange]; + [optChangeAccumulator trackChildChange:addedChange]; + } + return [[oldIndexed updateChild:childKey withNewChild:newChildSnap] updateChild:windowBoundary.name + withNewChild:[FEmptyNode emptyNode]]; + } else { + return oldIndexed; + } + } else { + // `newChildSnap` was not in range and remains not in range, so ignore it. + return oldIndexed; + } +} + +- (FIndexedNode *)updateFullNode:(FIndexedNode *)oldSnap + withNewNode:(FIndexedNode *)newSnap + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + __block FIndexedNode *filtered; + if (newSnap.node.isLeafNode || newSnap.node.isEmpty) { + // Make sure we have a children node with the correct index, not a leaf node + filtered = [FIndexedNode indexedNodeWithNode:[FEmptyNode emptyNode] index:self.index]; + } else { + filtered = newSnap; + // Don't support priorities on queries. + filtered = [filtered updatePriority:[FEmptyNode emptyNode]]; + FNamedNode *startPost = nil; + FNamedNode *endPost = nil; + if (self.reverse) { + startPost = self.rangedFilter.endPost; + endPost = self.rangedFilter.startPost; + } else { + startPost = self.rangedFilter.startPost; + endPost = self.rangedFilter.endPost; + } + __block BOOL foundStartPost = NO; + __block NSUInteger count = 0; + [newSnap enumerateChildrenReverse:self.reverse usingBlock:^(NSString *childKey, id childNode, BOOL *stop) { + if (!foundStartPost && [self.index compareKey:startPost.name + andNode:startPost.node + toOtherKey:childKey + andNode:childNode + reverse:self.reverse] <= NSOrderedSame) { + // Start adding + foundStartPost = YES; + } + BOOL inRange = foundStartPost && count < self.limit; + inRange = inRange && [self.index compareKey:childKey + andNode:childNode + toOtherKey:endPost.name + andNode:endPost.node + reverse:self.reverse] <= NSOrderedSame; + if (inRange) { + count++; + } else { + filtered = [filtered updateChild:childKey withNewChild:[FEmptyNode emptyNode]]; + } + }]; + } + return [self.indexedFilter updateFullNode:oldSnap withNewNode:filtered accumulator:optChangeAccumulator]; +} + +- (FIndexedNode *)updatePriority:(id)priority forNode:(FIndexedNode *)oldSnap +{ + // Don't support priorities on queries. + return oldSnap; +} + +- (BOOL) filtersNodes { + return YES; +} + +- (id) indexedFilter { + return self.rangedFilter.indexedFilter; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FNodeFilter.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FNodeFilter.h new file mode 100644 index 0000000..f29a85a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Core/View/Filter/FNodeFilter.h @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@class FIndexedNode; +@protocol FCompleteChildSource; +@class FChildChangeAccumulator; +@protocol FIndex; +@class FPath; + +/** +* FNodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping +* track of any child changes. This class does not track value changes as value changes depend on more than just the +* node itself. Different kind of queries require different kind of implementations of this interface. +*/ +@protocol FNodeFilter + +/** +* Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. +* The method expects an indexed snap. +*/ +- (FIndexedNode *) updateChildIn:(FIndexedNode *)oldSnap + forChildKey:(NSString *)childKey + newChild:(id)newChildSnap + affectedPath:(FPath *)affectedPath + fromSource:(id)source + accumulator:(FChildChangeAccumulator *)optChangeAccumulator; + +/** +* Update a node in full and output any resulting change from this complete update. +*/ +- (FIndexedNode *) updateFullNode:(FIndexedNode *)oldSnap + withNewNode:(FIndexedNode *)newSnap + accumulator:(FChildChangeAccumulator *)optChangeAccumulator; + +/** +* Update the priority of the root node +*/ +- (FIndexedNode *) updatePriority:(id)priority forNode:(FIndexedNode *)oldSnap; + +/** +* Returns true if children might be filtered due to query critiera +*/ +- (BOOL) filtersNodes; + +/** +* Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. +*/ +@property (nonatomic, strong, readonly) id indexedFilter; + +/** +* Returns the index that this filter uses +*/ +@property (nonatomic, strong, readonly) id index; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.h new file mode 100644 index 0000000..1924ad4 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FClock + +- (NSTimeInterval)currentTime; + +@end + +@interface FSystemClock : NSObject + ++ (FSystemClock *)clock; + +@end + +@interface FOffsetClock : NSObject + +- (id)initWithClock:(id)clock offset:(NSTimeInterval)offset; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.m new file mode 100644 index 0000000..2464056 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FClock.m @@ -0,0 +1,58 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FClock.h" + +@implementation FSystemClock + +- (NSTimeInterval)currentTime { + return [[NSDate date] timeIntervalSince1970]; +} + ++ (FSystemClock *)clock { + static dispatch_once_t onceToken; + static FSystemClock *clock; + dispatch_once(&onceToken, ^{ + clock = [[FSystemClock alloc] init]; + }); + return clock; +} + +@end + +@interface FOffsetClock () + +@property (nonatomic, strong) id clock; +@property (nonatomic) NSTimeInterval offset; + +@end + +@implementation FOffsetClock + +- (NSTimeInterval)currentTime { + return [self.clock currentTime] + self.offset; +} + +- (id)initWithClock:(id)clock offset:(NSTimeInterval)offset { + self = [super init]; + if (self != nil) { + self->_clock = clock; + self->_offset = offset; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.h new file mode 100644 index 0000000..1bc011b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FQuerySpec; +@class FIndexedNode; +@protocol FNode; + +@interface FEventGenerator : NSObject +- (id) initWithQuery:(FQuerySpec *)query; +- (NSArray*) generateEventsForChanges:(NSArray*)changes eventCache:(FIndexedNode *)eventCache + eventRegistrations:(NSArray*)registrations; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.m new file mode 100644 index 0000000..f6e8f47 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FEventGenerator.m @@ -0,0 +1,141 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FEventGenerator.h" +#import "FNode.h" +#import "FIRDatabaseQuery_Private.h" +#import "FQueryParams.h" +#import "FQuerySpec.h" +#import "FChange.h" +#import "FNamedNode.h" +#import "FEventRegistration.h" +#import "FEvent.h" +#import "FDataEvent.h" + +@interface FEventGenerator () +@property (nonatomic, strong) FQuerySpec *query; +@end + +/** +* An EventGenerator is used to convert "raw" changes (fb.core.view.Change) as computed by the +* CacheDiffer into actual events (fb.core.view.Event) that can be raised. See generateEventsForChanges() +* for details. +*/ +@implementation FEventGenerator + +- (id)initWithQuery:(FQuerySpec *)query { + self = [super init]; + if (self) { + self.query = query; + } + return self; +} + +/** +* Given a set of raw changes (no moved events, and prevName not specified yet), and a set of EventRegistrations that +* should be notified of these changes, generate the actual events to be raised. +* +* Notes: +* - child_moved events will be synthesized at this time for any child_changed events that affect our index +* - prevName will be calculated based on the index ordering +* +* @param changes NSArray of FChange, not necessarily in order. +* @param registrations is NSArray of FEventRegistration. +* @return NSArray of FEvent. +*/ +- (NSArray *) generateEventsForChanges:(NSArray *)changes + eventCache:(FIndexedNode *)eventCache + eventRegistrations:(NSArray *)registrations +{ + NSMutableArray *events = [[NSMutableArray alloc] init]; + + // child_moved is index-specific, so check all our child_changed events to see if we need to materialize + // child_moved events with this view's index + NSMutableArray *moves = [[NSMutableArray alloc] init]; + for (FChange *change in changes) { + if (change.type == FIRDataEventTypeChildChanged && [self.query.index indexedValueChangedBetween:change.oldIndexedNode.node + and:change.indexedNode.node]) { + FChange *moveChange = [[FChange alloc] initWithType:FIRDataEventTypeChildMoved + indexedNode:change.indexedNode + childKey:change.childKey + oldIndexedNode:nil]; + [moves addObject:moveChange]; + } + } + + [self generateEvents:events forType:FIRDataEventTypeChildRemoved changes:changes eventCache:eventCache eventRegistrations:registrations]; + [self generateEvents:events forType:FIRDataEventTypeChildAdded changes:changes eventCache:eventCache eventRegistrations:registrations]; + [self generateEvents:events forType:FIRDataEventTypeChildMoved changes:moves eventCache:eventCache eventRegistrations:registrations]; + [self generateEvents:events forType:FIRDataEventTypeChildChanged changes:changes eventCache:eventCache eventRegistrations:registrations]; + [self generateEvents:events forType:FIRDataEventTypeValue changes:changes eventCache:eventCache eventRegistrations:registrations]; + + return events; +} + +- (void) generateEvents:(NSMutableArray *)events + forType:(FIRDataEventType)eventType + changes:(NSArray *)changes + eventCache:(FIndexedNode *)eventCache + eventRegistrations:(NSArray *)registrations +{ + NSMutableArray *filteredChanges = [[NSMutableArray alloc] init]; + for (FChange *change in changes) { + if (change.type == eventType) { + [filteredChanges addObject:change]; + } + } + + id index = self.query.index; + + [filteredChanges sortUsingComparator:^NSComparisonResult(FChange *one, FChange *two) { + if (one.childKey == nil || two.childKey == nil) { + @throw [[NSException alloc] initWithName:@"InternalInconsistencyError" + reason:@"Should only compare child_ events" + userInfo:nil]; + } + return [index compareKey:one.childKey + andNode:one.indexedNode.node + toOtherKey:two.childKey + andNode:two.indexedNode.node]; + }]; + + for (FChange *change in filteredChanges) { + for (id registration in registrations) { + if ([registration responseTo:eventType]) { + id event = [self generateEventForChange:change registration:registration eventCache:eventCache]; + [events addObject:event]; + } + } + } +} + +- (id) generateEventForChange:(FChange *)change + registration:(id)registration + eventCache:(FIndexedNode *)eventCache +{ + FChange *materializedChange; + if (change.type == FIRDataEventTypeValue || change.type == FIRDataEventTypeChildRemoved) { + materializedChange = change; + } else { + NSString *prevChildKey = [eventCache predecessorForChildKey:change.childKey + childNode:change.indexedNode.node + index:self.query.index]; + materializedChange = [change changeWithPrevKey:prevChildKey]; + } + return [registration createEventFrom:materializedChange query:self.query]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseConfig_Private.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseConfig_Private.h new file mode 100644 index 0000000..ac37f2e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseConfig_Private.h @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseConfig.h" +#import "FAuthTokenProvider.h" + +@protocol FStorageEngine; + +@interface FIRDatabaseConfig () + +@property (nonatomic, readonly) BOOL isFrozen; +@property (nonatomic, strong, readonly) NSString *sessionIdentifier; +@property (nonatomic, strong) id authTokenProvider; +@property (nonatomic, strong) id forceStorageEngine; + +- (void)freeze; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseReference.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseReference.m new file mode 100644 index 0000000..3ea5992 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIRDatabaseReference.m @@ -0,0 +1,400 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDatabaseReference.h" +#import +#import "FUtilities.h" +#import "FNextPushId.h" +#import "FIRDatabaseQuery_Private.h" +#import "FValidation.h" +#import "FIRDatabaseReference_Private.h" +#import "FStringUtilities.h" +#import "FSnapshotUtilities.h" +#import "FIRDatabaseConfig.h" +#import "FIRDatabaseConfig_Private.h" +#import "FQueryParams.h" +#import "FIRDatabase.h" + +@implementation FIRDatabaseReference + +#pragma mark - +#pragma mark Constructors + +- (id) initWithConfig:(FIRDatabaseConfig *)config { + FParsedUrl* parsedUrl = [FUtilities parseUrl:[[FIRApp defaultApp] options].databaseURL]; + [FValidation validateFrom:@"initWithUrl:" validURL:parsedUrl]; + return [self initWithRepo:[FRepoManager getRepo:parsedUrl.repoInfo config:config] path:parsedUrl.path]; +} + +- (id) initWithRepo:(FRepo *)repo path:(FPath *)path { + return [super initWithRepo:repo + path:path + params:[FQueryParams defaultInstance] + orderByCalled:NO + priorityMethodCalled:NO]; +} + + +#pragma mark - +#pragma mark Ancillary methods + +- (nullable NSString *) key { + if([self.path isEmpty]) { + return nil; + } + else { + return [self.path getBack]; + } +} + +- (FIRDatabase *) database { + return self.repo.database; +} + +- (FIRDatabaseReference *) parent { + FPath* parentPath = [self.path parent]; + FIRDatabaseReference * parent = nil; + if (parentPath != nil ) { + parent = [[FIRDatabaseReference alloc] initWithRepo:self.repo path:parentPath]; + } + return parent; +} + +- (NSString *) URL { + FIRDatabaseReference * parent = [self parent]; + return parent == nil ? [self.repo description] : [NSString stringWithFormat:@"%@/%@", [parent description], [FStringUtilities urlEncoded:self.key]]; +} + +- (NSString *) description { + return [self URL]; +} + +- (FIRDatabaseReference *) root { + return [[FIRDatabaseReference alloc] initWithRepo:self.repo path:[[FPath alloc] initWith:@""]]; +} + +#pragma mark - +#pragma mark Child methods + +- (FIRDatabaseReference *)childByAppendingPath:(NSString *)pathString { + return [self child:pathString]; +} + +- (FIRDatabaseReference *)child:(NSString *)pathString { + if ([self.path getFront] == nil) { + // we're at the root + [FValidation validateFrom:@"child:" validRootPathString:pathString]; + } else { + [FValidation validateFrom:@"child:" validPathString:pathString]; + } + FPath* path = [self.path childFromString:pathString]; + FIRDatabaseReference * firebaseRef = [[FIRDatabaseReference alloc] initWithRepo:self.repo path:path]; + return firebaseRef; +} + +- (FIRDatabaseReference *) childByAutoId { + [FValidation validateFrom:@"childByAutoId:" writablePath:self.path]; + + NSString* name = [FNextPushId get:self.repo.serverTime]; + return [self child:name]; +} + +#pragma mark - +#pragma mark Basic write methods + +- (void) setValue:(id)value { + [self setValueInternal:value andPriority:nil withCompletionBlock:nil from:@"setValue:"]; +} + +- (void) setValue:(id)value withCompletionBlock:(fbt_void_nserror_ref)block { + [self setValueInternal:value andPriority:nil withCompletionBlock:block from:@"setValue:withCompletionBlock:"]; +} + +- (void) setValue:(id)value andPriority:(id)priority { + [self setValueInternal:value andPriority:priority withCompletionBlock:nil from:@"setValue:andPriority:"]; +} + +- (void) setValue:(id)value andPriority:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block { + [self setValueInternal:value andPriority:priority withCompletionBlock:block from:@"setValue:andPriority:withCompletionBlock:"]; +} + +- (void) setValueInternal:(id)value andPriority:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block from:(NSString*)fn { + [FValidation validateFrom:fn writablePath:self.path]; + + fbt_void_nserror_ref userCallback = [block copy]; + id newNode = [FSnapshotUtilities nodeFrom:value priority:priority withValidationFrom:fn]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo set:self.path withNode:newNode withCallback:userCallback]; + }); +} + + +- (void) removeValue { + [self setValueInternal:nil andPriority:nil withCompletionBlock:nil from:@"removeValue:"]; +} + +- (void) removeValueWithCompletionBlock:(fbt_void_nserror_ref)block { + [self setValueInternal:nil andPriority:nil withCompletionBlock:block from:@"removeValueWithCompletionBlock:"]; +} + + +- (void) setPriority:(id)priority { + [self setPriorityInternal:priority withCompletionBlock:nil from:@"setPriority:"]; +} + +- (void) setPriority:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block { + + [self setPriorityInternal:priority withCompletionBlock:block from:@"setPriority:withCompletionBlock:"]; +} + +- (void) setPriorityInternal:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block from:(NSString*)fn { + [FValidation validateFrom:fn writablePath:self.path]; + + fbt_void_nserror_ref userCallback = [block copy]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo set:[self.path childFromString:@".priority"] withNode:[FSnapshotUtilities nodeFrom:priority] withCallback:userCallback]; + }); +} + + +- (void) updateChildValues:(NSDictionary *)values { + [self updateChildValuesInternal:values withCompletionBlock:nil from:@"updateChildValues:"]; +} + +- (void) updateChildValues:(NSDictionary *)values withCompletionBlock:(fbt_void_nserror_ref)block { + [self updateChildValuesInternal:values withCompletionBlock:block from:@"updateChildValues:withCompletionBlock:"]; +} + +- (void) updateChildValuesInternal:(NSDictionary *)values withCompletionBlock:(fbt_void_nserror_ref)block from:(NSString*)fn { + [FValidation validateFrom:fn writablePath:self.path]; + + FCompoundWrite *merge = [FSnapshotUtilities compoundWriteFromDictionary:values withValidationFrom:fn]; + + fbt_void_nserror_ref userCallback = [block copy]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo update:self.path withNodes:merge withCallback:userCallback]; + }); +} + +#pragma mark - +#pragma mark Disconnect Operations + +- (void) onDisconnectSetValue:(id)value { + [self onDisconnectSetValueInternal:value andPriority:nil withCompletionBlock:nil from:@"onDisconnectSetValue:"]; +} + +- (void) onDisconnectSetValue:(id)value withCompletionBlock:(fbt_void_nserror_ref)block { + [self onDisconnectSetValueInternal:value andPriority:nil withCompletionBlock:block from:@"onDisconnectSetValue:withCompletionBlock:"]; +} + +- (void) onDisconnectSetValue:(id)value andPriority:(id)priority { + [self onDisconnectSetValueInternal:value andPriority:priority withCompletionBlock:nil from:@"onDisconnectSetValue:andPriority:"]; +} + +- (void) onDisconnectSetValue:(id)value andPriority:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block { + [self onDisconnectSetValueInternal:value andPriority:priority withCompletionBlock:block from:@"onDisconnectSetValue:andPriority:withCompletionBlock:"]; +} + +- (void) onDisconnectSetValueInternal:(id)value andPriority:(id)priority withCompletionBlock:(fbt_void_nserror_ref)block from:(NSString*)fn { + [FValidation validateFrom:fn writablePath:self.path]; + + id newNodeUnresolved = [FSnapshotUtilities nodeFrom:value priority:priority withValidationFrom:fn]; + + fbt_void_nserror_ref userCallback = [block copy]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo onDisconnectSet:self.path withNode:newNodeUnresolved withCallback:userCallback]; + }); +} + + +- (void) onDisconnectRemoveValue { + [self onDisconnectSetValueInternal:nil andPriority:nil withCompletionBlock:nil from:@"onDisconnectRemoveValue:"]; +} + +- (void) onDisconnectRemoveValueWithCompletionBlock:(fbt_void_nserror_ref)block { + [self onDisconnectSetValueInternal:nil andPriority:nil withCompletionBlock:block from:@"onDisconnectRemoveValueWithCompletionBlock:"]; +} + + +- (void) onDisconnectUpdateChildValues:(NSDictionary *)values { + [self onDisconnectUpdateChildValuesInternal:values withCompletionBlock:nil from:@"onDisconnectUpdateChildValues:"]; +} + +- (void) onDisconnectUpdateChildValues:(NSDictionary *)values withCompletionBlock:(fbt_void_nserror_ref)block { + [self onDisconnectUpdateChildValuesInternal:values withCompletionBlock:block from:@"onDisconnectUpdateChildValues:withCompletionBlock:"]; +} + +- (void) onDisconnectUpdateChildValuesInternal:(NSDictionary *)values withCompletionBlock:(fbt_void_nserror_ref)block from:(NSString*)fn { + [FValidation validateFrom:fn writablePath:self.path]; + + FCompoundWrite *merge = [FSnapshotUtilities compoundWriteFromDictionary:values withValidationFrom:fn]; + + fbt_void_nserror_ref userCallback = [block copy]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo onDisconnectUpdate:self.path withNodes:merge withCallback:userCallback]; + }); +} + + +- (void) cancelDisconnectOperations { + [self cancelDisconnectOperationsWithCompletionBlock:nil]; +} + +- (void) cancelDisconnectOperationsWithCompletionBlock:(fbt_void_nserror_ref)block { + fbt_void_nserror_ref callback = nil; + if (block != nil) { + callback = [block copy]; + } + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo onDisconnectCancel:self.path withCallback:callback]; + }); +} + +#pragma mark - +#pragma mark Connection management methods + ++ (void) goOffline { + [FRepoManager interruptAll]; +} + ++ (void) goOnline { + [FRepoManager resumeAll]; +} + + +#pragma mark - +#pragma mark Data reading methods deferred to FQuery + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block { + return [self observeEventType:eventType withBlock:block withCancelBlock:nil]; +} + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block { + return [self observeEventType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:nil]; +} + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block withCancelBlock:(fbt_void_nserror)cancelBlock { + return [super observeEventType:eventType withBlock:block withCancelBlock:cancelBlock]; +} + +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block withCancelBlock:(fbt_void_nserror)cancelBlock { + return [super observeEventType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:cancelBlock]; +} + + +- (void) removeObserverWithHandle:(FIRDatabaseHandle)handle { + [super removeObserverWithHandle:handle]; +} + + +- (void) removeAllObservers { + [super removeAllObservers]; +} + +- (void) keepSynced:(BOOL)keepSynced { + [super keepSynced:keepSynced]; +} + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block { + [self observeSingleEventOfType:eventType withBlock:block withCancelBlock:nil]; +} + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block { + [self observeSingleEventOfType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:nil]; +} + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(fbt_void_datasnapshot)block withCancelBlock:(fbt_void_nserror)cancelBlock { + [super observeSingleEventOfType:eventType withBlock:block withCancelBlock:cancelBlock]; +} + +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(fbt_void_datasnapshot_nsstring)block withCancelBlock:(fbt_void_nserror)cancelBlock { + [super observeSingleEventOfType:eventType andPreviousSiblingKeyWithBlock:block withCancelBlock:cancelBlock]; +} + +#pragma mark - +#pragma mark Query methods +// These methods suppress warnings from having method definitions in FIRDatabaseReference.h for docs generation. + +- (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit { + return [super queryLimitedToFirst:limit]; +} + +- (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit { + return [super queryLimitedToLast:limit]; +} + +- (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key { + return [super queryOrderedByChild:key]; +} + +- (FIRDatabaseQuery *) queryOrderedByKey { + return [super queryOrderedByKey]; +} + +- (FIRDatabaseQuery *) queryOrderedByPriority { + return [super queryOrderedByPriority]; +} + +- (FIRDatabaseQuery *)queryStartingAtValue:(id)startValue { + return [super queryStartingAtValue:startValue]; +} + +- (FIRDatabaseQuery *)queryStartingAtValue:(id)startValue childKey:(NSString *)childKey { + return [super queryStartingAtValue:startValue childKey:childKey]; +} + +- (FIRDatabaseQuery *)queryEndingAtValue:(id)endValue { + return [super queryEndingAtValue:endValue]; +} + +- (FIRDatabaseQuery *)queryEndingAtValue:(id)endValue childKey:(NSString *)childKey { + return [super queryEndingAtValue:endValue childKey:childKey]; +} + +- (FIRDatabaseQuery *)queryEqualToValue:(id)value { + return [super queryEqualToValue:value]; +} + +- (FIRDatabaseQuery *)queryEqualToValue:(id)value childKey:(NSString *)childKey { + return [super queryEqualToValue:value childKey:childKey]; +} + + +#pragma mark - +#pragma mark Transaction methods + +- (void) runTransactionBlock:(fbt_transactionresult_mutabledata)block { + [FValidation validateFrom:@"runTransactionBlock:" writablePath:self.path]; + [self runTransactionBlock:block andCompletionBlock:nil withLocalEvents:YES]; +} + +- (void) runTransactionBlock:(fbt_transactionresult_mutabledata)update andCompletionBlock:(fbt_void_nserror_bool_datasnapshot)completionBlock { + [FValidation validateFrom:@"runTransactionBlock:andCompletionBlock:" writablePath:self.path]; + [self runTransactionBlock:update andCompletionBlock:completionBlock withLocalEvents:YES]; +} + +- (void) runTransactionBlock:(fbt_transactionresult_mutabledata)block andCompletionBlock:(fbt_void_nserror_bool_datasnapshot)completionBlock withLocalEvents:(BOOL)localEvents { + [FValidation validateFrom:@"runTransactionBlock:andCompletionBlock:withLocalEvents:" writablePath:self.path]; + fbt_transactionresult_mutabledata updateCopy = [block copy]; + fbt_void_nserror_bool_datasnapshot onCompleteCopy = [completionBlock copy]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self.repo startTransactionOnPath:self.path update:updateCopy onComplete:onCompleteCopy withLocalEvents:localEvents]; + }); +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.h new file mode 100644 index 0000000..8ab08c8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.h @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FImmutableSortedDictionary; +@class FNamedNode; +@protocol FNode; + +@protocol FIndex +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2; + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 + reverse:(BOOL)reverse; + +- (NSComparisonResult) compareNamedNode:(FNamedNode *)namedNode1 toNamedNode:(FNamedNode *)namedNode2; + +- (BOOL) isDefinedOn:(id)node; +- (BOOL) indexedValueChangedBetween:(id)oldNode and:(id)newNode; +- (FNamedNode*) minPost; +- (FNamedNode*) maxPost; +- (FNamedNode*) makePost:(id)indexValue name:(NSString*)name; +- (NSString*) queryDefinition; + +@end + +@interface FIndex : NSObject + ++ (id)indexFromQueryDefinition:(NSString *)string; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.m new file mode 100644 index 0000000..61980c7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FIndex.m @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIndex.h" + +#import "FKeyIndex.h" +#import "FValueIndex.h" +#import "FPathIndex.h" +#import "FPriorityIndex.h" + +@implementation FIndex + ++ (id)indexFromQueryDefinition:(NSString *)string { + if ([string isEqualToString:@".key"]) { + return [FKeyIndex keyIndex]; + } else if ([string isEqualToString:@".value"]) { + return [FValueIndex valueIndex]; + } else if ([string isEqualToString:@".priority"]) { + return [FPriorityIndex priorityIndex]; + } else { + return [[FPathIndex alloc] initWithPath:[[FPath alloc] initWith:string]]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.h new file mode 100644 index 0000000..a6bf787 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIndex.h" + + +@interface FKeyIndex : NSObject ++ (id) keyIndex; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.m new file mode 100644 index 0000000..68ad461 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FKeyIndex.m @@ -0,0 +1,115 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FKeyIndex.h" +#import "FNamedNode.h" +#import "FSnapshotUtilities.h" +#import "FUtilities.h" +#import "FEmptyNode.h" + +@interface FKeyIndex () + +@property (nonatomic, strong) FNamedNode *maxPost; + +@end + +@implementation FKeyIndex + +- (id)init { + self = [super init]; + if (self) { + self.maxPost = [[FNamedNode alloc] initWithName:[FUtilities maxName] andNode:[FEmptyNode emptyNode]]; + } + return self; + +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 +{ + return [FUtilities compareKey:key1 toKey:key2]; +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 + reverse:(BOOL)reverse +{ + if (reverse) { + return [self compareKey:key2 andNode:node2 toOtherKey:key1 andNode:node1]; + } else { + return [self compareKey:key1 andNode:node1 toOtherKey:key2 andNode:node2]; + } +} + +- (NSComparisonResult) compareNamedNode:(FNamedNode *)namedNode1 toNamedNode:(FNamedNode *)namedNode2 +{ + return [self compareKey:namedNode1.name andNode:namedNode1.node toOtherKey:namedNode2.name andNode:namedNode2.node]; +} + +- (BOOL)isDefinedOn:(id )node { + return YES; +} + +- (BOOL)indexedValueChangedBetween:(id )oldNode and:(id )newNode { + return NO; // The key for a node never changes. +} + +- (FNamedNode *)minPost { + return [FNamedNode min]; +} + +- (FNamedNode *)makePost:(id)indexValue name:(NSString*)name { + NSString *key = indexValue.val; + NSAssert([key isKindOfClass:[NSString class]], @"KeyIndex indexValue must always be a string."); + // We just use empty node, but it'll never be compared, since our comparator only looks at name. + return [[FNamedNode alloc] initWithName:key andNode:[FEmptyNode emptyNode]]; +} + +- (NSString *) queryDefinition { + return @".key"; +} + +- (NSString *) description { + return @"FKeyIndex"; +} + +- (id)copyWithZone:(NSZone *)zone { + return self; +} + +- (BOOL) isEqual:(id)other { + // since we're a singleton. + return (other == self); +} + +- (NSUInteger) hash { + return [@".key" hash]; +} + + ++ (id) keyIndex { + static id keyIndex; + static dispatch_once_t once; + dispatch_once(&once, ^{ + keyIndex = [[FKeyIndex alloc] init]; + }); + return keyIndex; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.h new file mode 100644 index 0000000..914a3e4 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.h @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FOperation.h" + + +@interface FListenComplete : NSObject + +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath; + +@property (nonatomic, strong, readonly) FOperationSource *source; +@property (nonatomic, strong, readonly) FPath *path; +@property (nonatomic, readonly) FOperationType type; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.m new file mode 100644 index 0000000..8573075 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FListenComplete.m @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FListenComplete.h" +#import "FOperationSource.h" +#import "FPath.h" + +@interface FListenComplete () +@property (nonatomic, strong, readwrite) FOperationSource *source; +@property (nonatomic, strong, readwrite) FPath *path; +@property (nonatomic, readwrite) FOperationType type; +@end + +@implementation FListenComplete +- (id) initWithSource:(FOperationSource *)aSource path:(FPath *)aPath { + NSAssert(!aSource.fromUser, @"Can't have a listen complete from a user source"); + self = [super init]; + if (self) { + self.source = aSource; + self.path = aPath; + self.type = FOperationTypeListenComplete; + } + return self; +} + +- (id ) operationForChild:(NSString *)childKey { + if ([self.path isEmpty]) { + return [[FListenComplete alloc] initWithSource:self.source path:[FPath empty]]; + } else { + return [[FListenComplete alloc] initWithSource:self.source path:[self.path popFront]]; + } +} + +- (NSString *) description { + return [NSString stringWithFormat:@"FListenComplete { path=%@, source=%@ }", self.path, self.source]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.h new file mode 100644 index 0000000..6aff8c6 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FChildrenNode.h" + + +@interface FMaxNode : FChildrenNode + + (id) maxNode; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.m new file mode 100644 index 0000000..3c93684 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FMaxNode.m @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FMaxNode.h" +#import "FUtilities.h" +#import "FEmptyNode.h" + + +@implementation FMaxNode { + +} +- (id) init { + self = [super init]; + if (self) { + + } + return self; +} + ++ (id) maxNode { + static FMaxNode *maxNode = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + maxNode = [[FMaxNode alloc] init]; + }); + return maxNode; +} + +- (NSComparisonResult) compare:(id)other { + if (other == self) { + return NSOrderedSame; + } else { + return NSOrderedDescending; + } +} + +- (BOOL)isEqual:(id)other { + return other == self; +} + +- (id) getImmediateChild:(NSString *) childName { + return [FEmptyNode emptyNode]; +} + +- (BOOL) isEmpty { + return NO; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.h new file mode 100644 index 0000000..ac9baa6 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.h @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@interface FNamedNode : NSObject + +@property (nonatomic, strong, readonly) NSString* name; +@property (nonatomic, strong, readonly) id node; + + +-(id)initWithName:(NSString*)name andNode:(id)node; + ++ (FNamedNode *)nodeWithName:(NSString *)name node:(id)node; + ++ (FNamedNode*) min; ++ (FNamedNode*) max; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.m new file mode 100644 index 0000000..d11787b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FNamedNode.m @@ -0,0 +1,94 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FNamedNode.h" +#import "FUtilities.h" +#import "FEmptyNode.h" +#import "FMaxNode.h" +#import "FIndex.h" + +@interface FNamedNode () +@property (nonatomic, strong, readwrite) NSString* name; +@property (nonatomic, strong, readwrite) id node; +@end + +@implementation FNamedNode + ++ (FNamedNode *)nodeWithName:(NSString *)name node:(id)node +{ + return [[FNamedNode alloc] initWithName:name andNode:node]; +} + +- (id)initWithName:(NSString *)name andNode:(id )node { + self = [super init]; + if (self) { + self.name = name; + self.node = node; + } + return self; +} + +- (id)copy +{ + return self; +} + +- (id)copyWithZone:(NSZone *)zone +{ + return self; +} + ++ (FNamedNode *)min { + static FNamedNode *min = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + min = [[FNamedNode alloc] initWithName:[FUtilities minName] andNode:[FEmptyNode emptyNode]]; + }); + return min; +} + ++ (FNamedNode *)max { + static FNamedNode *max = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + max = [[FNamedNode alloc] initWithName:[FUtilities maxName] andNode:[FMaxNode maxNode]]; + }); + return max; +} + +- (NSString *) description { + return [NSString stringWithFormat:@"NamedNode[%@] %@", self.name, self.node]; +} + +- (BOOL) isEqual:(id)object { + if (self == object) { return YES; } + if (object == nil || ![object isKindOfClass:[FNamedNode class]]) { return NO; } + + FNamedNode *namedNode = object; + if (![self.name isEqualToString:namedNode.name]) { return NO; } + if (![self.node isEqual:namedNode.node]) { return NO; } + + return YES; +} + +- (NSUInteger) hash { + NSUInteger nameHash = [self.name hash]; + NSUInteger nodeHash = [self.node hash]; + NSUInteger result = 31 * nameHash + nodeHash; + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.h new file mode 100644 index 0000000..cf92ad1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIndex.h" +#import "FPath.h" + +@interface FPathIndex : NSObject +- (id) initWithPath:(FPath *)path; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.m new file mode 100644 index 0000000..39913aa --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPathIndex.m @@ -0,0 +1,125 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FPathIndex.h" +#import "FUtilities.h" +#import "FMaxNode.h" +#import "FEmptyNode.h" +#import "FSnapshotUtilities.h" +#import "FNamedNode.h" +#import "FPath.h" + +@interface FPathIndex () + @property (nonatomic, strong) FPath *path; +@end + +@implementation FPathIndex + +- (id) initWithPath:(FPath *)path { + self = [super init]; + if (self) { + if (path.isEmpty || [path.getFront isEqualToString:@".priority"]) { + [NSException raise:NSInvalidArgumentException format:@"Invalid path for PathIndex: %@", path]; + } + _path = path; + } + return self; +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 +{ + id child1 = [node1 getChild:self.path]; + id child2 = [node2 getChild:self.path]; + NSComparisonResult indexCmp = [child1 compare:child2]; + if (indexCmp == NSOrderedSame) { + return [FUtilities compareKey:key1 toKey:key2]; + } else { + return indexCmp; + } +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 + reverse:(BOOL)reverse +{ + if (reverse) { + return [self compareKey:key2 andNode:node2 toOtherKey:key1 andNode:node1]; + } else { + return [self compareKey:key1 andNode:node1 toOtherKey:key2 andNode:node2]; + } +} + +- (NSComparisonResult) compareNamedNode:(FNamedNode *)namedNode1 toNamedNode:(FNamedNode *)namedNode2 +{ + return [self compareKey:namedNode1.name andNode:namedNode1.node toOtherKey:namedNode2.name andNode:namedNode2.node]; +} + +- (BOOL)isDefinedOn:(id )node { + return ![node getChild:self.path].isEmpty; +} + +- (BOOL)indexedValueChangedBetween:(id )oldNode and:(id )newNode { + id oldValue = [oldNode getChild:self.path]; + id newValue = [newNode getChild:self.path]; + return [oldValue compare:newValue] != NSOrderedSame; +} + +- (FNamedNode *)minPost { + return FNamedNode.min; +} + +- (FNamedNode *)maxPost { + id maxNode = [[FEmptyNode emptyNode] updateChild:self.path + withNewChild:[FMaxNode maxNode]]; + + return [[FNamedNode alloc] initWithName:[FUtilities maxName] andNode:maxNode]; +} + +- (FNamedNode*)makePost:(id)indexValue name:(NSString*)name { + id node = [[FEmptyNode emptyNode] updateChild:self.path withNewChild:indexValue]; + return [[FNamedNode alloc] initWithName:name andNode:node]; +} + +- (NSString *)queryDefinition { + return [self.path wireFormat]; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"FPathIndex(%@)", self.path]; +} + +- (id)copyWithZone:(NSZone *)zone { + // Safe since we're immutable. + return self; +} + +- (BOOL) isEqual:(id)other { + if (![other isKindOfClass:[FPathIndex class]]) { + return NO; + } + return ([self.path isEqual:((FPathIndex*)other).path]); +} + +- (NSUInteger) hash { + return [self.path hash]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.h new file mode 100644 index 0000000..8b5904d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIndex.h" + +@interface FPriorityIndex : NSObject ++ (id) priorityIndex; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.m new file mode 100644 index 0000000..2d06ffa --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FPriorityIndex.m @@ -0,0 +1,118 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FPriorityIndex.h" + +#import "FNode.h" +#import "FUtilities.h" +#import "FNamedNode.h" +#import "FEmptyNode.h" +#import "FLeafNode.h" +#import "FMaxNode.h" + +// TODO: Abstract into some common base class? + +@implementation FPriorityIndex + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 +{ + id child1 = [node1 getPriority]; + id child2 = [node2 getPriority]; + NSComparisonResult indexCmp = [child1 compare:child2]; + if (indexCmp == NSOrderedSame) { + return [FUtilities compareKey:key1 toKey:key2]; + } else { + return indexCmp; + } +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 + reverse:(BOOL)reverse +{ + if (reverse) { + return [self compareKey:key2 andNode:node2 toOtherKey:key1 andNode:node1]; + } else { + return [self compareKey:key1 andNode:node1 toOtherKey:key2 andNode:node2]; + } +} + +- (NSComparisonResult) compareNamedNode:(FNamedNode *)namedNode1 toNamedNode:(FNamedNode *)namedNode2 +{ + return [self compareKey:namedNode1.name andNode:namedNode1.node toOtherKey:namedNode2.name andNode:namedNode2.node]; +} + +- (BOOL)isDefinedOn:(id )node { + return !node.getPriority.isEmpty; +} + +- (BOOL)indexedValueChangedBetween:(id )oldNode and:(id )newNode { + id oldValue = [oldNode getPriority]; + id newValue = [newNode getPriority]; + return ![oldValue isEqual:newValue]; +} + +- (FNamedNode *)minPost { + return FNamedNode.min; +} + +- (FNamedNode *)maxPost { + return [self makePost:[FMaxNode maxNode] name:[FUtilities maxName]]; +} + +- (FNamedNode*)makePost:(id)indexValue name:(NSString*)name { + id node = [[FLeafNode alloc] initWithValue:@"[PRIORITY-POST]" withPriority:indexValue]; + return [[FNamedNode alloc] initWithName:name andNode:node]; +} + +- (NSString *)queryDefinition { + return @".priority"; +} + +- (NSString *)description { + return @"FPriorityIndex"; +} + +- (id)copyWithZone:(NSZone *)zone { + // Safe since we're immutable. + return self; +} + +- (BOOL) isEqual:(id)other { + return [other isKindOfClass:[FPriorityIndex class]]; +} + +- (NSUInteger) hash { + // chosen by a fair dice roll. Guaranteed to be random + return 3155577; +} + ++ (id) priorityIndex { + static id index; + static dispatch_once_t once; + dispatch_once(&once, ^{ + index = [[FPriorityIndex alloc] init]; + }); + + return index; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.h new file mode 100644 index 0000000..1457778 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.h @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNodeFilter.h" + +@class FQueryParams; +@class FNamedNode; + +@interface FRangedFilter : NSObject + +- (id) initWithQueryParams:(FQueryParams *)params; +- (BOOL) matchesKey:(NSString *)key andNode:(id)node; + + +@property (nonatomic, strong, readonly) FNamedNode *startPost; +@property (nonatomic, strong, readonly) FNamedNode *endPost; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.m new file mode 100644 index 0000000..5c4bbeb --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FRangedFilter.m @@ -0,0 +1,118 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRangedFilter.h" +#import "FChildChangeAccumulator.h" +#import "FNamedNode.h" +#import "FQueryParams.h" +#import "FIndexedFilter.h" +#import "FQueryParams.h" +#import "FEmptyNode.h" +#import "FChildrenNode.h" +#import "FIndexedNode.h" + +@interface FRangedFilter () +@property (nonatomic, strong, readwrite) id indexedFilter; +@property (nonatomic, strong, readwrite) id index; +@property (nonatomic, strong, readwrite) FNamedNode *startPost; +@property (nonatomic, strong, readwrite) FNamedNode *endPost; +@end + +@implementation FRangedFilter +- (id) initWithQueryParams:(FQueryParams *)params { + self = [super init]; + if (self) { + self.indexedFilter = [[FIndexedFilter alloc] initWithIndex:params.index]; + self.index = params.index; + self.startPost = [FRangedFilter startPostFromQueryParams:params]; + self.endPost = [FRangedFilter endPostFromQueryParams:params]; + } + return self; +} + + ++ (FNamedNode *) startPostFromQueryParams:(FQueryParams *)params { + if ([params hasStart]) { + NSString *startKey = params.indexStartKey; + return [params.index makePost:params.indexStartValue name:startKey]; + } else { + return params.index.minPost; + } +} + ++ (FNamedNode *) endPostFromQueryParams:(FQueryParams *)params { + if ([params hasEnd]) { + NSString *endKey = params.indexEndKey; + return [params.index makePost:params.indexEndValue name:endKey]; + } else { + return params.index.maxPost; + } +} + +- (BOOL) matchesKey:(NSString *)key andNode:(id)node { + return ([self.index compareKey:self.startPost.name andNode:self.startPost.node toOtherKey:key andNode:node] <= NSOrderedSame && + [self.index compareKey:key andNode:node toOtherKey:self.endPost.name andNode:self.endPost.node] <= NSOrderedSame); +} + +- (FIndexedNode *)updateChildIn:(FIndexedNode *)oldSnap + forChildKey:(NSString *)childKey + newChild:(id)newChildSnap + affectedPath:(FPath *)affectedPath + fromSource:(id)source + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + if (![self matchesKey:childKey andNode:newChildSnap]) { + newChildSnap = [FEmptyNode emptyNode]; + } + return [self.indexedFilter updateChildIn:oldSnap + forChildKey:childKey + newChild:newChildSnap + affectedPath:affectedPath + fromSource:source + accumulator:optChangeAccumulator]; +} + +- (FIndexedNode *) updateFullNode:(FIndexedNode *)oldSnap + withNewNode:(FIndexedNode *)newSnap + accumulator:(FChildChangeAccumulator *)optChangeAccumulator +{ + __block FIndexedNode *filtered; + if (newSnap.node.isLeafNode) { + // Make sure we have a children node with the correct index, not a leaf node + filtered = [FIndexedNode indexedNodeWithNode:[FEmptyNode emptyNode] index:self.index]; + } else { + // Dont' support priorities on queries + filtered = [newSnap updatePriority:[FEmptyNode emptyNode]]; + [newSnap.node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + if (![self matchesKey:key andNode:node]) { + filtered = [filtered updateChild:key withNewChild:[FEmptyNode emptyNode]]; + } + }]; + } + return [self.indexedFilter updateFullNode:oldSnap withNewNode:filtered accumulator:optChangeAccumulator]; +} + +- (FIndexedNode *) updatePriority:(id)priority forNode:(FIndexedNode *)oldSnap +{ + // Don't support priorities on queries + return oldSnap; +} + +- (BOOL) filtersNodes { + return YES; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.h new file mode 100644 index 0000000..75391a8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.h @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + + +@interface FTransformedEnumerator : NSEnumerator +- (id)initWithEnumerator:(NSEnumerator*) enumerator andTransform:(id (^)(id))transform; +- (id)nextObject; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.m new file mode 100644 index 0000000..bb36e94 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FTransformedEnumerator.m @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTransformedEnumerator.h" + +@interface FTransformedEnumerator () +@property (nonatomic, strong) NSEnumerator *enumerator; +@property (nonatomic, copy) id (^transform)(id); +@end + +@implementation FTransformedEnumerator +- (id)initWithEnumerator:(NSEnumerator *)enumerator andTransform:(id (^)(id))transform { + self = [super init]; + if (self) { + self.enumerator = enumerator; + self.transform = transform; + } + return self; +} + +- (id)nextObject { + id next = self.enumerator.nextObject; + if (next != nil) { + return self.transform(next); + } else { + return nil; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.h new file mode 100644 index 0000000..0f1c7f7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIndex.h" + + +@interface FValueIndex : NSObject ++ (id) valueIndex; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.m new file mode 100644 index 0000000..7ef9bff --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FValueIndex.m @@ -0,0 +1,106 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FValueIndex.h" +#import "FNamedNode.h" +#import "FSnapshotUtilities.h" +#import "FUtilities.h" +#import "FMaxNode.h" + +@implementation FValueIndex + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 +{ + NSComparisonResult indexCmp = [node1 compare:node2]; + if (indexCmp == NSOrderedSame) { + return [FUtilities compareKey:key1 toKey:key2]; + } else { + return indexCmp; + } +} + +- (NSComparisonResult) compareKey:(NSString *)key1 + andNode:(id)node1 + toOtherKey:(NSString *)key2 + andNode:(id)node2 + reverse:(BOOL)reverse +{ + if (reverse) { + return [self compareKey:key2 andNode:node2 toOtherKey:key1 andNode:node1]; + } else { + return [self compareKey:key1 andNode:node1 toOtherKey:key2 andNode:node2]; + } +} + +- (NSComparisonResult) compareNamedNode:(FNamedNode *)namedNode1 toNamedNode:(FNamedNode *)namedNode2 +{ + return [self compareKey:namedNode1.name andNode:namedNode1.node toOtherKey:namedNode2.name andNode:namedNode2.node]; +} + +- (BOOL)isDefinedOn:(id)node { + return YES; +} + +- (BOOL)indexedValueChangedBetween:(id)oldNode and:(id)newNode { + return ![oldNode isEqual:newNode]; +} + +- (FNamedNode *)minPost { + return FNamedNode.min; +} + +- (FNamedNode *)maxPost { + return FNamedNode.max; +} + +- (FNamedNode *)makePost:(id)indexValue name:(NSString*)name { + return [[FNamedNode alloc] initWithName:name andNode:indexValue]; +} + +- (NSString *)queryDefinition { + return @".value"; +} + +- (NSString *) description { + return @"FValueIndex"; +} + +- (id)copyWithZone:(NSZone *)zone { + return self; +} + +- (BOOL) isEqual:(id)other { + // since we're a singleton. + return (other == self); +} + +- (NSUInteger) hash { + return [@".value" hash]; +} + + ++ (id) valueIndex { + static id valueIndex; + static dispatch_once_t once; + dispatch_once(&once, ^{ + valueIndex = [[FValueIndex alloc] init]; + }); + return valueIndex; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.h new file mode 100644 index 0000000..59bfd2d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FViewCache; +@class FViewProcessorResult; +@class FChildChangeAccumulator; +@protocol FNode; +@class FWriteTreeRef; +@class FPath; +@protocol FOperation; +@protocol FNodeFilter; + + +@interface FViewProcessor : NSObject + +- (id)initWithFilter:(id)nodeFilter; + +- (FViewProcessorResult *)applyOperationOn:(FViewCache *)oldViewCache operation:(id)operation writesCache:(FWriteTreeRef *)writesCache completeCache:(id )optCompleteCache; +- (FViewCache *) revertUserWriteOn:(FViewCache *)viewCache + path:(FPath *)path + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id)optCompleteCache + accumulator:(FChildChangeAccumulator *)accumulator; + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.m new file mode 100644 index 0000000..50a3594 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessor.m @@ -0,0 +1,655 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FViewProcessor.h" +#import "FCompleteChildSource.h" +#import "FWriteTreeRef.h" +#import "FViewCache.h" +#import "FCacheNode.h" +#import "FNode.h" +#import "FOperation.h" +#import "FOperationSource.h" +#import "FChildChangeAccumulator.h" +#import "FNodeFilter.h" +#import "FOverwrite.h" +#import "FMerge.h" +#import "FAckUserWrite.h" +#import "FViewProcessorResult.h" +#import "FIRDataEventType.h" +#import "FChange.h" +#import "FEmptyNode.h" +#import "FChildrenNode.h" +#import "FPath.h" +#import "FKeyIndex.h" +#import "FCompoundWrite.h" +#import "FImmutableTree.h" + +/** +* An implementation of FCompleteChildSource that never returns any additional children +*/ +@interface FNoCompleteChildSource: NSObject +@end + +@implementation FNoCompleteChildSource ++ (FNoCompleteChildSource *) instance { + static FNoCompleteChildSource *source = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + source = [[FNoCompleteChildSource alloc] init]; + }); + return source; +} + +- (id) completeChild:(NSString *)childKey { + return nil; +} + +- (FNamedNode *) childByIndex:(id)index afterChild:(FNamedNode *)child isReverse:(BOOL)reverse { + return nil; +} +@end + +/** +* An implementation of FCompleteChildSource that uses a FWriteTree in addition to any other server data or +* old event caches available to calculate complete children. +*/ +@interface FWriteTreeCompleteChildSource: NSObject +@property (nonatomic, strong) FWriteTreeRef *writes; +@property (nonatomic, strong) FViewCache *viewCache; +@property (nonatomic, strong) id optCompleteServerCache; +@end + +@implementation FWriteTreeCompleteChildSource +- (id) initWithWrites:(FWriteTreeRef *)writes viewCache:(FViewCache *)viewCache serverCache:(id)optCompleteServerCache { + self = [super init]; + if (self) { + self.writes = writes; + self.viewCache = viewCache; + self.optCompleteServerCache = optCompleteServerCache; + } + return self; +} + +- (id) completeChild:(NSString *)childKey { + FCacheNode *node = self.viewCache.cachedEventSnap; + if ([node isCompleteForChild:childKey]) { + return [node.node getImmediateChild:childKey]; + } else { + FCacheNode *serverNode; + if (self.optCompleteServerCache) { + // Since we're only ever getting child nodes, we can use the key index here + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:self.optCompleteServerCache index:[FKeyIndex keyIndex]]; + serverNode = [[FCacheNode alloc] initWithIndexedNode:indexed isFullyInitialized:YES isFiltered:NO]; + } else { + serverNode = self.viewCache.cachedServerSnap; + } + return [self.writes calculateCompleteChild:childKey cache:serverNode]; + } +} + +- (FNamedNode *) childByIndex:(id)index afterChild:(FNamedNode *)child isReverse:(BOOL)reverse { + id completeServerData = self.optCompleteServerCache != nil + ? self.optCompleteServerCache + : self.viewCache.completeServerSnap; + return [self.writes calculateNextNodeAfterPost:child + completeServerData:completeServerData + reverse:reverse + index:index]; +} + +@end + +@interface FViewProcessor () +@property (nonatomic, strong) id filter; +@end + +@implementation FViewProcessor + +- (id)initWithFilter:(id)nodeFilter { + self = [super init]; + if (self) { + self.filter = nodeFilter; + } + return self; +} + +- (FViewProcessorResult *)applyOperationOn:(FViewCache *)oldViewCache operation:(id)operation writesCache:(FWriteTreeRef *)writesCache completeCache:(id )optCompleteCache { + FChildChangeAccumulator *accumulator = [[FChildChangeAccumulator alloc] init]; + FViewCache *newViewCache; + + if (operation.type == FOperationTypeOverwrite) { + FOverwrite *overwrite = (FOverwrite *) operation; + if (operation.source.fromUser) { + newViewCache = [self applyUserOverwriteTo:oldViewCache + changePath:overwrite.path + changedSnap:overwrite.snap + writesCache:writesCache + completeCache:optCompleteCache + accumulator:accumulator]; + } else { + NSAssert(operation.source.fromServer, @"Unknown source for overwrite."); + // We filter the node if it's a tagged update or the node has been previously filtered and the update is + // not at the root in which case it is ok (and necessary) to mark the node unfiltered again + BOOL filterServerNode = overwrite.source.isTagged || (oldViewCache.cachedServerSnap.isFiltered && + !overwrite.path.isEmpty); + newViewCache = [self applyServerOverwriteTo:oldViewCache + changePath:overwrite.path + snap:overwrite.snap + writesCache:writesCache + completeCache:optCompleteCache + filterServerNode:filterServerNode + accumulator:accumulator]; + } + } else if (operation.type == FOperationTypeMerge) { + FMerge *merge = (FMerge*)operation; + if (operation.source.fromUser) { + newViewCache = [self applyUserMergeTo:oldViewCache + path:merge.path + changedChildren:merge.children + writesCache:writesCache + completeCache:optCompleteCache + accumulator:accumulator]; + } else { + NSAssert(operation.source.fromServer, @"Unknown source for merge."); + // We filter the node if it's a tagged update or the node has been previously filtered + BOOL filterServerNode = merge.source.isTagged || oldViewCache.cachedServerSnap.isFiltered; + newViewCache = [self applyServerMergeTo:oldViewCache + path:merge.path + changedChildren:merge.children + writesCache:writesCache + completeCache:optCompleteCache + filterServerNode:filterServerNode + accumulator:accumulator]; + } + } else if (operation.type == FOperationTypeAckUserWrite) { + FAckUserWrite *ackWrite = (FAckUserWrite *) operation; + if (!ackWrite.revert) { + newViewCache = [self ackUserWriteOn:oldViewCache + ackPath:ackWrite.path + affectedTree:ackWrite.affectedTree + writesCache:writesCache + completeCache:optCompleteCache + accumulator:accumulator]; + } else { + newViewCache = [self revertUserWriteOn:oldViewCache + path:ackWrite.path + writesCache:writesCache + completeCache:optCompleteCache + accumulator:accumulator]; + } + } else if (operation.type == FOperationTypeListenComplete) { + newViewCache = [self listenCompleteOldCache:oldViewCache + path:operation.path + writesCache:writesCache + serverCache:optCompleteCache + accumulator:accumulator]; + } else { + [NSException raise:NSInternalInconsistencyException + format:@"Unknown operation encountered %ld.", (long)operation.type]; + return nil; + } + + NSArray *changes = [self maybeAddValueFromOldViewCache:oldViewCache newViewCache:newViewCache changes:accumulator.changes]; + FViewProcessorResult *results = [[FViewProcessorResult alloc] initWithViewCache:newViewCache changes:changes]; + return results; +} + +- (NSArray *) maybeAddValueFromOldViewCache:(FViewCache *)oldViewCache newViewCache:(FViewCache *)newViewCache changes:(NSArray *)changes { + NSArray *newChanges = changes; + FCacheNode *eventSnap = newViewCache.cachedEventSnap; + if (eventSnap.isFullyInitialized) { + BOOL isLeafOrEmpty = eventSnap.node.isLeafNode || eventSnap.node.isEmpty; + if ([changes count] > 0 || + !oldViewCache.cachedEventSnap.isFullyInitialized || + (isLeafOrEmpty && ![eventSnap.node isEqual:oldViewCache.completeEventSnap]) || + ![eventSnap.node.getPriority isEqual:oldViewCache.completeEventSnap.getPriority]) { + FChange *valueChange = [[FChange alloc] initWithType:FIRDataEventTypeValue indexedNode:eventSnap.indexedNode]; + NSMutableArray *mutableChanges = [changes mutableCopy]; + [mutableChanges addObject:valueChange]; + newChanges = mutableChanges; + } + } + return newChanges; +} + +- (FViewCache *) generateEventCacheAfterServerEvent:(FViewCache *)viewCache + path:(FPath *)changePath + writesCache:(FWriteTreeRef *)writesCache + source:(id)source + accumulator:(FChildChangeAccumulator *)accumulator { + FCacheNode *oldEventSnap = viewCache.cachedEventSnap; + if ([writesCache shadowingWriteAtPath:changePath] != nil) { + // we have a shadowing write, ignore changes. + return viewCache; + } else { + FIndexedNode *newEventCache; + if (changePath.isEmpty) { + // TODO: figure out how this plays with "sliding ack windows" + NSAssert(viewCache.cachedServerSnap.isFullyInitialized, @"If change path is empty, we must have complete server data"); + id nodeWithLocalWrites; + if (viewCache.cachedServerSnap.isFiltered) { + // We need to special case this, because we need to only apply writes to complete children, or + // we might end up raising events for incomplete children. If the server data is filtered deep + // writes cannot be guaranteed to be complete + id serverCache = viewCache.completeServerSnap; + FChildrenNode *completeChildren = ([serverCache isKindOfClass:[FChildrenNode class]]) ? serverCache : [FEmptyNode emptyNode]; + nodeWithLocalWrites = [writesCache calculateCompleteEventChildrenWithCompleteServerChildren:completeChildren]; + } else { + nodeWithLocalWrites = [writesCache calculateCompleteEventCacheWithCompleteServerCache:viewCache.completeServerSnap]; + } + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:nodeWithLocalWrites index:self.filter.index]; + newEventCache = [self.filter updateFullNode:viewCache.cachedEventSnap.indexedNode + withNewNode:indexedNode + accumulator:accumulator]; + } else { + NSString *childKey = [changePath getFront]; + if ([childKey isEqualToString:@".priority"]) { + NSAssert(changePath.length == 1, @"Can't have a priority with additional path components"); + id oldEventNode = oldEventSnap.node; + id serverNode = viewCache.cachedServerSnap.node; + // we might have overwrites for this priority + id updatedPriority = [writesCache calculateEventCacheAfterServerOverwriteWithChildPath:changePath + existingEventSnap:oldEventNode + existingServerSnap:serverNode]; + if (updatedPriority != nil) { + newEventCache = [self.filter updatePriority:updatedPriority forNode:oldEventSnap.indexedNode]; + } else { + // priority didn't change, keep old node + newEventCache = oldEventSnap.indexedNode; + } + } else { + FPath *childChangePath = [changePath popFront]; + id newEventChild; + if ([oldEventSnap isCompleteForChild:childKey]) { + id serverNode = viewCache.cachedServerSnap.node; + id eventChildUpdate = [writesCache calculateEventCacheAfterServerOverwriteWithChildPath:changePath existingEventSnap:oldEventSnap.node existingServerSnap:serverNode]; + if (eventChildUpdate != nil) { + newEventChild = [[oldEventSnap.node getImmediateChild:childKey] updateChild:childChangePath withNewChild:eventChildUpdate]; + } else { + // Nothing changed, just keep the old child + newEventChild = [oldEventSnap.node getImmediateChild:childKey]; + } + } else { + newEventChild = [writesCache calculateCompleteChild:childKey cache:viewCache.cachedServerSnap]; + } + if (newEventChild != nil) { + newEventCache = [self.filter updateChildIn:oldEventSnap.indexedNode + forChildKey:childKey + newChild:newEventChild + affectedPath:childChangePath + fromSource:source + accumulator:accumulator]; + } else { + // No complete children available or no change + newEventCache = oldEventSnap.indexedNode; + } + } + } + return [viewCache updateEventSnap:newEventCache + isComplete:(oldEventSnap.isFullyInitialized || changePath.isEmpty) + isFiltered:self.filter.filtersNodes]; + } +} + +- (FViewCache *) applyServerOverwriteTo:(FViewCache *)oldViewCache changePath:(FPath *)changePath snap:(id)changedSnap + writesCache:(FWriteTreeRef *)writesCache completeCache:(id)optCompleteCache + filterServerNode:(BOOL)filterServerNode accumulator:(FChildChangeAccumulator *)accumulator { + FCacheNode *oldServerSnap = oldViewCache.cachedServerSnap; + FIndexedNode *newServerCache; + id serverFilter = filterServerNode ? self.filter : self.filter.indexedFilter; + + if (changePath.isEmpty) { + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:changedSnap index:serverFilter.index]; + newServerCache = [serverFilter updateFullNode:oldServerSnap.indexedNode withNewNode:indexed accumulator:nil]; + } else if (serverFilter.filtersNodes && !oldServerSnap.isFiltered) { + // We want to filter the server node, but we didn't filter the server node yet, so simulate a full update + NSAssert(![changePath isEmpty], @"An empty path should been caught in the other branch"); + NSString *childKey = [changePath getFront]; + FPath *updatePath = [changePath popFront]; + id newChild = [[oldServerSnap.node getImmediateChild:childKey] updateChild:updatePath + withNewChild:changedSnap]; + FIndexedNode *indexed = [oldServerSnap.indexedNode updateChild:childKey withNewChild:newChild]; + newServerCache = [serverFilter updateFullNode:oldServerSnap.indexedNode withNewNode:indexed accumulator:nil]; + } else { + NSString *childKey = [changePath getFront]; + if (![oldServerSnap isCompleteForPath:changePath] && changePath.length > 1) { + // We don't update incomplete nodes with updates intended for other listeners. + return oldViewCache; + } + FPath *childChangePath = [changePath popFront]; + id childNode = [oldServerSnap.node getImmediateChild:childKey]; + id newChildNode = [childNode updateChild:childChangePath withNewChild:changedSnap]; + if ([childKey isEqualToString:@".priority"]) { + newServerCache = [serverFilter updatePriority:newChildNode forNode:oldServerSnap.indexedNode]; + } else { + newServerCache = [serverFilter updateChildIn:oldServerSnap.indexedNode + forChildKey:childKey + newChild:newChildNode + affectedPath:childChangePath + fromSource:[FNoCompleteChildSource instance] + accumulator:nil]; + } + } + FViewCache *newViewCache = [oldViewCache updateServerSnap:newServerCache + isComplete:(oldServerSnap.isFullyInitialized || changePath.isEmpty) + isFiltered:serverFilter.filtersNodes]; + id source = [[FWriteTreeCompleteChildSource alloc] initWithWrites:writesCache + viewCache:newViewCache + serverCache:optCompleteCache]; + return [self generateEventCacheAfterServerEvent:newViewCache + path:changePath + writesCache:writesCache + source:source + accumulator:accumulator]; +} + +- (FViewCache *) applyUserOverwriteTo:(FViewCache *)oldViewCache + changePath:(FPath *)changePath + changedSnap:(id)changedSnap + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id)optCompleteCache + accumulator:(FChildChangeAccumulator *)accumulator { + FCacheNode *oldEventSnap = oldViewCache.cachedEventSnap; + FViewCache *newViewCache; + id source = [[FWriteTreeCompleteChildSource alloc] initWithWrites:writesCache + viewCache:oldViewCache + serverCache:optCompleteCache]; + if (changePath.isEmpty) { + FIndexedNode *newIndexed = [FIndexedNode indexedNodeWithNode:changedSnap index:self.filter.index]; + FIndexedNode *newEventCache = [self.filter updateFullNode:oldEventSnap.indexedNode + withNewNode:newIndexed + accumulator:accumulator]; + newViewCache = [oldViewCache updateEventSnap:newEventCache isComplete:YES isFiltered:self.filter.filtersNodes]; + } else { + NSString *childKey = [changePath getFront]; + if ([childKey isEqualToString:@".priority"]) { + FIndexedNode *newEventCache = [self.filter updatePriority:changedSnap + forNode:oldViewCache.cachedEventSnap.indexedNode]; + newViewCache = [oldViewCache updateEventSnap:newEventCache + isComplete:oldEventSnap.isFullyInitialized + isFiltered:oldEventSnap.isFiltered]; + } else { + FPath *childChangePath = [changePath popFront]; + id oldChild = [oldEventSnap.node getImmediateChild:childKey]; + id newChild; + if (childChangePath.isEmpty) { + // Child overwrite, we can replace the child + newChild = changedSnap; + } else { + id childNode = [source completeChild:childKey]; + if (childNode != nil) { + if ([[childChangePath getBack] isEqualToString:@".priority"] && [childNode getChild:[childChangePath parent]].isEmpty) { + // This is a priority update on an empty node. If this node exists on the server, the server + // will send down the priority in the update, so ignore for now + newChild = childNode; + } else { + newChild = [childNode updateChild:childChangePath withNewChild:changedSnap]; + } + } else { + newChild = [FEmptyNode emptyNode]; + } + } + if (![oldChild isEqual:newChild]) { + FIndexedNode *newEventSnap = [self.filter updateChildIn:oldEventSnap.indexedNode + forChildKey:childKey + newChild:newChild + affectedPath:childChangePath + fromSource:source + accumulator:accumulator]; + newViewCache = [oldViewCache updateEventSnap:newEventSnap isComplete:oldEventSnap.isFullyInitialized isFiltered:self.filter.filtersNodes]; + } else { + newViewCache = oldViewCache; + } + } + } + return newViewCache; +} + ++ (BOOL) cache:(FViewCache *)viewCache hasChild:(NSString *)childKey { + return [viewCache.cachedEventSnap isCompleteForChild:childKey]; +} + +/** +* @param changedChildren NSDictionary of child name (NSString*) to child value (id) +*/ +- (FViewCache *) applyUserMergeTo:(FViewCache *)viewCache + path:(FPath *)path + changedChildren:(FCompoundWrite *)changedChildren + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id)serverCache + accumulator:(FChildChangeAccumulator *)accumulator { + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + __block FViewCache *curViewCache = viewCache; + + [changedChildren enumerateWrites:^(FPath *relativePath, id childNode, BOOL *stop) { + FPath *writePath = [path child:relativePath]; + if ([FViewProcessor cache:viewCache hasChild:[writePath getFront]]) { + curViewCache = [self applyUserOverwriteTo:curViewCache + changePath:writePath + changedSnap:childNode + writesCache:writesCache + completeCache:serverCache + accumulator:accumulator]; + } + }]; + + [changedChildren enumerateWrites:^(FPath *relativePath, id childNode, BOOL *stop) { + FPath *writePath = [path child:relativePath]; + if (![FViewProcessor cache:viewCache hasChild:[writePath getFront]]) { + curViewCache = [self applyUserOverwriteTo:curViewCache + changePath:writePath + changedSnap:childNode + writesCache:writesCache + completeCache:serverCache + accumulator:accumulator]; + } + }]; + + return curViewCache; +} + +- (FViewCache *) applyServerMergeTo:(FViewCache *)viewCache + path:(FPath *)path + changedChildren:(FCompoundWrite *)changedChildren + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id)serverCache + filterServerNode:(BOOL)filterServerNode + accumulator:(FChildChangeAccumulator *)accumulator { + // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and + // wait for the complete data update coming soon. + if (viewCache.cachedServerSnap.node.isEmpty && !viewCache.cachedServerSnap.isFullyInitialized) { + return viewCache; + } + + // HACK: In the case of a limit query, there may be some changes that bump things out of the + // window leaving room for new items. It's important we process these changes first, so we + // iterate the changes twice, first processing any that affect items currently in view. + // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server + // and event snap. I'm not sure if this will result in edge cases when a child is in one but + // not the other. + __block FViewCache *curViewCache = viewCache; + FCompoundWrite *actualMerge; + if (path.isEmpty) { + actualMerge = changedChildren; + } else { + actualMerge = [[FCompoundWrite emptyWrite] addCompoundWrite:changedChildren atPath:path]; + } + id serverNode = viewCache.cachedServerSnap.node; + + NSDictionary *childCompoundWrites = actualMerge.childCompoundWrites; + [childCompoundWrites enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FCompoundWrite *childMerge, BOOL *stop) { + if ([serverNode hasChild:childKey]) { + id serverChild = [viewCache.cachedServerSnap.node getImmediateChild:childKey]; + id newChild = [childMerge applyToNode:serverChild]; + curViewCache = [self applyServerOverwriteTo:curViewCache + changePath:[[FPath alloc] initWith:childKey] + snap:newChild + writesCache:writesCache + completeCache:serverCache + filterServerNode:filterServerNode + accumulator:accumulator]; + } + }]; + + [childCompoundWrites enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FCompoundWrite *childMerge, BOOL *stop) { + bool isUnknownDeepMerge = ![viewCache.cachedServerSnap isCompleteForChild:childKey] && childMerge.rootWrite == nil; + if (![serverNode hasChild:childKey] && !isUnknownDeepMerge) { + id serverChild = [viewCache.cachedServerSnap.node getImmediateChild:childKey]; + id newChild = [childMerge applyToNode:serverChild]; + curViewCache = [self applyServerOverwriteTo:curViewCache + changePath:[[FPath alloc] initWith:childKey] + snap:newChild + writesCache:writesCache + completeCache:serverCache + filterServerNode:filterServerNode + accumulator:accumulator]; + } + }]; + + return curViewCache; +} + +- (FViewCache *) ackUserWriteOn:(FViewCache *)viewCache + ackPath:(FPath *)ackPath + affectedTree:(FImmutableTree *)affectedTree + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id )optCompleteCache + accumulator:(FChildChangeAccumulator *)accumulator { + + if ([writesCache shadowingWriteAtPath:ackPath] != nil) { + return viewCache; + } + + // Only filter server node if it is currently filtered + BOOL filterServerNode = viewCache.cachedServerSnap.isFiltered; + + // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update + // now that it won't be shadowed. + FCacheNode *serverCache = viewCache.cachedServerSnap; + if (affectedTree.value != nil) { + // This is an overwrite. + if ((ackPath.isEmpty && serverCache.isFullyInitialized) || [serverCache isCompleteForPath:ackPath]) { + return [self applyServerOverwriteTo:viewCache changePath:ackPath snap:[serverCache.node getChild:ackPath] + writesCache:writesCache completeCache:optCompleteCache + filterServerNode:filterServerNode accumulator:accumulator]; + } else if (ackPath.isEmpty) { + // This is a goofy edge case where we are acking data at this location but don't have full data. We + // should just re-apply whatever we have in our cache as a merge. + FCompoundWrite *changedChildren = [FCompoundWrite emptyWrite]; + for(FNamedNode *child in serverCache.node.childEnumerator) { + changedChildren = [changedChildren addWrite:child.node atKey:child.name]; + } + return [self applyServerMergeTo:viewCache path:ackPath changedChildren:changedChildren + writesCache:writesCache completeCache:optCompleteCache + filterServerNode:filterServerNode accumulator:accumulator]; + } else { + return viewCache; + } + } else { + // This is a merge. + __block FCompoundWrite *changedChildren = [FCompoundWrite emptyWrite]; + [affectedTree forEach:^(FPath *mergePath, id value) { + FPath *serverCachePath = [ackPath child:mergePath]; + if ([serverCache isCompleteForPath:serverCachePath]) { + changedChildren = [changedChildren addWrite:[serverCache.node getChild:serverCachePath] atPath:mergePath]; + } + }]; + return [self applyServerMergeTo:viewCache path:ackPath changedChildren:changedChildren + writesCache:writesCache completeCache:optCompleteCache + filterServerNode:filterServerNode accumulator:accumulator]; + } +} + +- (FViewCache *) revertUserWriteOn:(FViewCache *)viewCache + path:(FPath *)path + writesCache:(FWriteTreeRef *)writesCache + completeCache:(id)optCompleteCache + accumulator:(FChildChangeAccumulator *)accumulator { + if ([writesCache shadowingWriteAtPath:path] != nil) { + return viewCache; + } else { + id source = [[FWriteTreeCompleteChildSource alloc] initWithWrites:writesCache + viewCache:viewCache + serverCache:optCompleteCache]; + FIndexedNode *oldEventCache = viewCache.cachedEventSnap.indexedNode; + FIndexedNode *newEventCache; + if (path.isEmpty || [[path getFront] isEqualToString:@".priority"]) { + id newNode; + if (viewCache.cachedServerSnap.isFullyInitialized) { + newNode = [writesCache calculateCompleteEventCacheWithCompleteServerCache:viewCache.completeServerSnap]; + } else { + newNode = [writesCache calculateCompleteEventChildrenWithCompleteServerChildren:viewCache.cachedServerSnap.node]; + } + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:newNode index:self.filter.index]; + newEventCache = [self.filter updateFullNode:oldEventCache withNewNode:indexedNode accumulator:accumulator]; + } else { + NSString *childKey = [path getFront]; + id newChild = [writesCache calculateCompleteChild:childKey cache:viewCache.cachedServerSnap]; + if (newChild == nil && [viewCache.cachedServerSnap isCompleteForChild:childKey]) { + newChild = [oldEventCache.node getImmediateChild:childKey]; + } + if (newChild != nil) { + newEventCache = [self.filter updateChildIn:oldEventCache + forChildKey:childKey + newChild:newChild + affectedPath:[path popFront] + fromSource:source + accumulator:accumulator]; + } else if (newChild == nil && [viewCache.cachedEventSnap.node hasChild:childKey]) { + // No complete child available, delete the existing one, if any + newEventCache = [self.filter updateChildIn:oldEventCache + forChildKey:childKey + newChild:[FEmptyNode emptyNode] + affectedPath:[path popFront] + fromSource:source + accumulator:accumulator]; + } else { + newEventCache = oldEventCache; + } + if (newEventCache.node.isEmpty && viewCache.cachedServerSnap.isFullyInitialized) { + // We might have reverted all child writes. Maybe the old event was a leaf node. + id complete = [writesCache calculateCompleteEventCacheWithCompleteServerCache:viewCache.completeServerSnap]; + if (complete.isLeafNode) { + FIndexedNode *indexed = [FIndexedNode indexedNodeWithNode:complete]; + newEventCache = [self.filter updateFullNode:newEventCache + withNewNode:indexed + accumulator:accumulator]; + } + } + } + BOOL complete = viewCache.cachedServerSnap.isFullyInitialized || [writesCache shadowingWriteAtPath:[FPath empty]] != nil; + return [viewCache updateEventSnap:newEventCache isComplete:complete isFiltered:self.filter.filtersNodes]; + } +} + +- (FViewCache *) listenCompleteOldCache:(FViewCache *)viewCache + path:(FPath *)path + writesCache:(FWriteTreeRef *)writesCache + serverCache:(id)servercache + accumulator:(FChildChangeAccumulator *)accumulator { + FCacheNode *oldServerNode = viewCache.cachedServerSnap; + FViewCache *newViewCache = [viewCache updateServerSnap:oldServerNode.indexedNode + isComplete:(oldServerNode.isFullyInitialized || path.isEmpty) + isFiltered:oldServerNode.isFiltered]; + return [self generateEventCacheAfterServerEvent:newViewCache path:path writesCache:writesCache source:[FNoCompleteChildSource instance] accumulator:accumulator]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.h new file mode 100644 index 0000000..e211d19 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FViewCache; + + +@interface FViewProcessorResult : NSObject +@property (nonatomic, strong, readonly) FViewCache *viewCache; +/** +* List of FChanges. +*/ +@property (nonatomic, strong, readonly) NSArray *changes; + +- (id) initWithViewCache:(FViewCache *)viewCache changes:(NSArray *)changes; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.m new file mode 100644 index 0000000..3327888 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/FViewProcessorResult.m @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FViewProcessorResult.h" +#import "FViewCache.h" + +@interface FViewProcessorResult () +@property (nonatomic, strong, readwrite) FViewCache *viewCache; +@property (nonatomic, strong, readwrite) NSArray *changes; +@end + +@implementation FViewProcessorResult +- (id) initWithViewCache:(FViewCache *)viewCache changes:(NSArray *)changes { + self = [super init]; + if (self) { + self.viewCache = viewCache; + self.changes = changes; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.h new file mode 100644 index 0000000..a4f8b15 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FTypedefs.h" +#import "FTypedefs_Private.h" + +@protocol FIRAuthInterop; + +@protocol FAuthTokenProvider + +- (void)fetchTokenForcingRefresh:(BOOL)forceRefresh + withCallback:(fbt_void_nsstring_nserror)callback; + +- (void)listenForTokenChanges:(fbt_void_nsstring)listener; + +@end + +@interface FAuthTokenProvider : NSObject + ++ (id)authTokenProviderWithAuth:(id)auth; + +- (instancetype)init NS_UNAVAILABLE; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.m new file mode 100644 index 0000000..5010360 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FAuthTokenProvider.m @@ -0,0 +1,117 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FAuthTokenProvider.h" + +#import +#import +#import +#import + +#import "FUtilities.h" +#import "FIRDatabaseQuery_Private.h" +#import "FIRNoopAuthTokenProvider.h" + +@interface FAuthStateListenerWrapper : NSObject + +@property (nonatomic, copy) fbt_void_nsstring listener; +@property (nonatomic, weak) id auth; + +@end + +@implementation FAuthStateListenerWrapper + +- (instancetype)initWithListener:(fbt_void_nsstring)listener auth:(id)auth { + self = [super init]; + if (self != nil) { + self->_listener = listener; + self->_auth = auth; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(authStateDidChangeNotification:) + name:FIRAuthStateDidChangeInternalNotification + object:nil]; + } + return self; +} + +- (void)authStateDidChangeNotification:(NSNotification *)notification { + NSDictionary *userInfo = notification.userInfo; + if (notification.object == self.auth) { + NSString *token = userInfo[FIRAuthStateDidChangeInternalNotificationTokenKey]; + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + self.listener(token); + }); + } +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +@end + + +@interface FIRFirebaseAuthTokenProvider : NSObject + +@property (nonatomic, strong) id auth; +/** Strong references to the auth listeners as they are only weak in FIRFirebaseApp */ +@property (nonatomic, strong) NSMutableArray *authListeners; + +- (instancetype) initWithAuth:(id)auth; + +@end + +@implementation FIRFirebaseAuthTokenProvider + +- (instancetype)initWithAuth:(id)auth { + self = [super init]; + if (self != nil) { + self->_auth = auth; + self->_authListeners = [NSMutableArray array]; + } + return self; +} + +- (void)fetchTokenForcingRefresh:(BOOL)forceRefresh + withCallback:(fbt_void_nsstring_nserror)callback { + if (self.auth == nil) { + // Signal that Auth is not available by returning nil. + callback(nil, nil); + } else { + [self.auth getTokenForcingRefresh:forceRefresh + withCallback:^(NSString * _Nullable token, NSError * _Nullable error) { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + callback(token, error); + }); + }]; + } +} + +- (void)listenForTokenChanges:(_Nonnull fbt_void_nsstring)listener { + FAuthStateListenerWrapper *wrapper = + [[FAuthStateListenerWrapper alloc] initWithListener:listener auth:self.auth]; + [self.authListeners addObject:wrapper]; +} + +@end + +@implementation FAuthTokenProvider + ++ (id)authTokenProviderWithAuth:(id)authInterop { + return [[FIRFirebaseAuthTokenProvider alloc] initWithAuth:authInterop]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.h new file mode 100644 index 0000000..e27ddb4 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.h @@ -0,0 +1,22 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FAuthTokenProvider.h" + +@interface FIRNoopAuthTokenProvider : NSObject + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.m new file mode 100644 index 0000000..8bf467b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Login/FIRNoopAuthTokenProvider.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRNoopAuthTokenProvider.h" +#import "FAuthTokenProvider.h" +#import "FIRDatabaseQuery_Private.h" + +@implementation FIRNoopAuthTokenProvider + +- (void) fetchTokenForcingRefresh:(BOOL)forceRefresh withCallback:(fbt_void_nsstring_nserror)callback { + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + callback(nil, nil); + }); +} + +- (void) listenForTokenChanges:(fbt_void_nsstring)listener { + // no-op, because token never changes +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.h new file mode 100644 index 0000000..16b49fb --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.h @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FCachePolicy + +- (BOOL)shouldPruneCacheWithSize:(NSUInteger)cacheSize numberOfTrackedQueries:(NSUInteger)numTrackedQueries; +- (BOOL)shouldCheckCacheSize:(NSUInteger)serverUpdatesSinceLastCheck; +- (float)percentOfQueriesToPruneAtOnce; +- (NSUInteger)maxNumberOfQueriesToKeep; + +@end + + +@interface FLRUCachePolicy : NSObject + +@property (nonatomic, readonly) NSUInteger maxSize; + +- (id)initWithMaxSize:(NSUInteger)maxSize; + +@end + +@interface FNoCachePolicy : NSObject + ++ (FNoCachePolicy *)noCachePolicy; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.m new file mode 100644 index 0000000..7da76ef --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FCachePolicy.m @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FCachePolicy.h" + +@interface FLRUCachePolicy () + +@property (nonatomic, readwrite) NSUInteger maxSize; + +@end + +static const NSUInteger kFServerUpdatesBetweenCacheSizeChecks = 1000; +static const NSUInteger kFMaxNumberOfPrunableQueriesToKeep = 1000; +static const float kFPercentOfQueriesToPruneAtOnce = 0.2f; + +@implementation FLRUCachePolicy + +- (id)initWithMaxSize:(NSUInteger)maxSize { + self = [super init]; + if (self != nil) { + self->_maxSize = maxSize; + } + return self; +} + +- (BOOL)shouldPruneCacheWithSize:(NSUInteger)cacheSize numberOfTrackedQueries:(NSUInteger)numTrackedQueries { + return cacheSize > self.maxSize || numTrackedQueries > kFMaxNumberOfPrunableQueriesToKeep; +} + +- (BOOL)shouldCheckCacheSize:(NSUInteger)serverUpdatesSinceLastCheck { + return serverUpdatesSinceLastCheck > kFServerUpdatesBetweenCacheSizeChecks; +} + +- (float)percentOfQueriesToPruneAtOnce { + return kFPercentOfQueriesToPruneAtOnce; +} + +- (NSUInteger)maxNumberOfQueriesToKeep { + return kFMaxNumberOfPrunableQueriesToKeep; +} + +@end + +@implementation FNoCachePolicy + ++ (FNoCachePolicy *)noCachePolicy { + return [[FNoCachePolicy alloc] init]; +} + +- (BOOL)shouldPruneCacheWithSize:(NSUInteger)cacheSize numberOfTrackedQueries:(NSUInteger)numTrackedQueries { + return NO; +} + +- (BOOL)shouldCheckCacheSize:(NSUInteger)serverUpdatesSinceLastCheck { + return NO; +} + +- (float)percentOfQueriesToPruneAtOnce { + return 0; +} + +- (NSUInteger)maxNumberOfQueriesToKeep { + return NSUIntegerMax; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.h new file mode 100644 index 0000000..84f3864 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FStorageEngine.h" +#import "FNode.h" +#import "FPath.h" +#import "FCompoundWrite.h" +#import "FQuerySpec.h" + +@class FCacheNode; +@class FTrackedQuery; +@class FPruneForest; +@class FRepoInfo; + +@interface FLevelDBStorageEngine : NSObject + ++ (NSString *) firebaseDir; + +- (id)initWithPath:(NSString *)path; + +- (void)runLegacyMigration:(FRepoInfo *)info; +- (void)purgeEverything; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.m new file mode 100644 index 0000000..68254ad --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FLevelDBStorageEngine.m @@ -0,0 +1,738 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FLevelDBStorageEngine.h" + +#import +#import "APLevelDB.h" +#import "FSnapshotUtilities.h" +#import "FWriteRecord.h" +#import "FTrackedQuery.h" +#import "FQueryParams.h" +#import "FEmptyNode.h" +#import "FPruneForest.h" +#import "FUtilities.h" +#import "FPendingPut.h" // For legacy migration + +@interface FLevelDBStorageEngine () + +@property (nonatomic, strong) NSString *basePath; +@property (nonatomic, strong) APLevelDB *writesDB; +@property (nonatomic, strong) APLevelDB *serverCacheDB; + +@end + +// WARNING: If you change this, you need to write a migration script +static NSString * const kFPersistenceVersion = @"1"; + +static NSString * const kFServerDBPath = @"server_data"; +static NSString * const kFWritesDBPath = @"writes"; + +static NSString * const kFUserWriteId = @"id"; +static NSString * const kFUserWritePath = @"path"; +static NSString * const kFUserWriteOverwrite = @"o"; +static NSString * const kFUserWriteMerge = @"m"; + +static NSString * const kFTrackedQueryId = @"id"; +static NSString * const kFTrackedQueryPath = @"path"; +static NSString * const kFTrackedQueryParams = @"p"; +static NSString * const kFTrackedQueryLastUse = @"lu"; +static NSString * const kFTrackedQueryIsComplete = @"c"; +static NSString * const kFTrackedQueryIsActive = @"a"; + +static NSString * const kFServerCachePrefix = @"/server_cache/"; +// '~' is the last non-control character in the ASCII table until 127 +// We wan't the entire range of thing stored in the DB +static NSString * const kFServerCacheRangeEnd = @"/server_cache~"; +static NSString * const kFTrackedQueriesPrefix = @"/tracked_queries/"; +static NSString * const kFTrackedQueryKeysPrefix = @"/tracked_query_keys/"; + +// Failed to load JSON because a valid JSON turns out to be NaN while deserializing +static const NSInteger kFNanFailureCode = 3840; + +static NSString* writeRecordKey(NSUInteger writeId) { + return [NSString stringWithFormat:@"%lu", (unsigned long)(writeId)]; +} + +static NSString* serverCacheKey(FPath *path) { + return [NSString stringWithFormat:@"%@%@", kFServerCachePrefix, ([path toStringWithTrailingSlash])]; +} + +static NSString* trackedQueryKey(NSUInteger trackedQueryId) { + return [NSString stringWithFormat:@"%@%lu", kFTrackedQueriesPrefix, (unsigned long)trackedQueryId]; +} + +static NSString* trackedQueryKeysKeyPrefix(NSUInteger trackedQueryId) { + return [NSString stringWithFormat:@"%@%lu/", kFTrackedQueryKeysPrefix, (unsigned long)trackedQueryId]; +} + +static NSString* trackedQueryKeysKey(NSUInteger trackedQueryId, NSString *key) { + return [NSString stringWithFormat:@"%@%lu/%@", kFTrackedQueryKeysPrefix, (unsigned long)trackedQueryId, key]; +} + +@implementation FLevelDBStorageEngine +#pragma mark - Constructors + +- (id)initWithPath:(NSString*)dbPath +{ + self = [super init]; + if (self) { + self.basePath = [[FLevelDBStorageEngine firebaseDir] stringByAppendingPathComponent:dbPath]; + /* For reference: + serverDataDB = [aPersistence createDbByName:@"server_data"]; + FPangolinDB *completenessDb = [aPersistence createDbByName:@"server_complete"]; + */ + [FLevelDBStorageEngine ensureDir:self.basePath markAsDoNotBackup:YES]; + [self runMigration]; + [self openDatabases]; + } + return self; +} + +- (void)runMigration { + // Currently we're at version 1, so all we need to do is write that to a file + NSString *versionFile = [self.basePath stringByAppendingPathComponent:@"version"]; + NSError *error; + NSString *oldVersion = [NSString stringWithContentsOfFile:versionFile encoding:NSUTF8StringEncoding error:&error]; + if (!oldVersion) { + // This is probably fine, we don't have a version file yet + BOOL success = [kFPersistenceVersion writeToFile:versionFile atomically:NO encoding:NSUTF8StringEncoding error:&error]; + if (!success) { + FFWarn(@"I-RDB076001", @"Failed to write version for database: %@", error); + } + } else if ([oldVersion isEqualToString:kFPersistenceVersion]) { + // Everythings fine no need for migration + } else { + // If we add more versions in the future, we need to run migration here + [NSException raise:NSInternalInconsistencyException format:@"Unrecognized database version: %@", oldVersion]; + } +} + +- (void)runLegacyMigration:(FRepoInfo *)info { + NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDir = [dirPaths objectAtIndex:0]; + NSString *firebaseDir = [documentsDir stringByAppendingPathComponent:@"firebase"]; + NSString* repoHashString = [NSString stringWithFormat:@"%@_%@", info.host, info.namespace]; + NSString *legacyBaseDir = [NSString stringWithFormat:@"%@/1/%@/v1", firebaseDir, repoHashString]; + if ([[NSFileManager defaultManager] fileExistsAtPath:legacyBaseDir]) { + FFWarn(@"I-RDB076002", @"Legacy database found, migrating..."); + // We only need to migrate writes + NSError *error = nil; + APLevelDB *writes = [APLevelDB levelDBWithPath:[legacyBaseDir stringByAppendingPathComponent:@"outstanding_puts"] error:&error]; + if (writes != nil) { + __block NSUInteger numberOfWritesRestored = 0; + // Maybe we could use write batches, but what the heck, I'm sure it'll go fine :P + [writes enumerateKeysAndValuesAsData:^(NSString *key, NSData *data, BOOL *stop) { + id pendingPut = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + if ([pendingPut isKindOfClass:[FPendingPut class]]) { + FPendingPut *put = pendingPut; + id newNode = [FSnapshotUtilities nodeFrom:put.data priority:put.priority]; + [self saveUserOverwrite:newNode atPath:put.path writeId:[key integerValue]]; + numberOfWritesRestored++; + } else if ([pendingPut isKindOfClass:[FPendingPutPriority class]]) { + // This is for backwards compatibility. Older clients will save FPendingPutPriority. New ones will need to read it and translate. + FPendingPutPriority *putPriority = pendingPut; + FPath *priorityPath = [putPriority.path childFromString:@".priority"]; + id newNode = [FSnapshotUtilities nodeFrom:putPriority.priority priority:nil]; + [self saveUserOverwrite:newNode atPath:priorityPath writeId:[key integerValue]]; + numberOfWritesRestored++; + } else if ([pendingPut isKindOfClass:[FPendingUpdate class]]) { + FPendingUpdate *update = pendingPut; + FCompoundWrite *merge = [FCompoundWrite compoundWriteWithValueDictionary:update.data]; + [self saveUserMerge:merge atPath:update.path writeId:[key integerValue]]; + numberOfWritesRestored++; + } else { + FFWarn(@"I-RDB076003", @"Failed to migrate legacy write, meh!"); + } + }]; + FFWarn(@"I-RDB076004", @"Migrated %lu writes", (unsigned long)numberOfWritesRestored); + [writes close]; + FFWarn(@"I-RDB076005", @"Deleting legacy database..."); + BOOL success = [[NSFileManager defaultManager] removeItemAtPath:legacyBaseDir error:&error]; + if (!success) { + FFWarn(@"I-RDB076006", @"Failed to delete legacy database: %@", error); + } else { + FFWarn(@"I-RDB076007", @"Finished migrating legacy database."); + } + } else { + FFWarn(@"I-RDB076008", @"Failed to migrate old database: %@", error); + } + } +} + +- (void)openDatabases { + self.serverCacheDB = [self createDB:kFServerDBPath]; + self.writesDB = [self createDB:kFWritesDBPath]; +} + +- (void)purgeDatabase:(NSString*) dbPath { + NSString *path = [self.basePath stringByAppendingPathComponent:dbPath]; + NSError *error; + FFWarn(@"I-RDB076009", @"Deleting database at path %@", path); + BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error]; + if (!success) { + [NSException raise:NSInternalInconsistencyException format:@"Failed to delete database files: %@", error]; + } +} + +- (void)purgeEverything { + [self close]; + [@[kFServerDBPath, kFWritesDBPath] + enumerateObjectsUsingBlock:^(NSString *dbPath, NSUInteger idx, BOOL *stop) { + [self purgeDatabase:dbPath]; + }]; + + [self openDatabases]; +} + +- (void)close { + // autoreleasepool will cause deallocation which will close the DB + @autoreleasepool { + [self.serverCacheDB close]; + self.serverCacheDB = nil; + [self.writesDB close]; + self.writesDB = nil; + } +} + ++ (NSString *) firebaseDir { + #if TARGET_OS_IOS || TARGET_OS_TV + NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDir = [dirPaths objectAtIndex:0]; + return [documentsDir stringByAppendingPathComponent:@"firebase"]; + #elif TARGET_OS_OSX + return [NSHomeDirectory() stringByAppendingPathComponent:@".firebase"]; + #endif +} + +- (APLevelDB *)createDB:(NSString *)dbName { + NSError *err = nil; + NSString *path = [self.basePath stringByAppendingPathComponent:dbName]; + APLevelDB *db = [APLevelDB levelDBWithPath:path error:&err]; + + if (err) { + FFWarn(@"I-RDB076036", @"Failed to read database persistence file '%@': %@", + dbName, [err localizedDescription]); + err = nil; + + // Delete the database and try again. + [self purgeDatabase:dbName]; + db = [APLevelDB levelDBWithPath:path error:&err]; + + if (err) { + NSString *reason = [NSString stringWithFormat:@"Error initializing persistence: %@", [err description]]; + @throw [NSException exceptionWithName:@"FirebaseDatabasePersistenceFailure" reason:reason userInfo:nil]; + } + } + + return db; +} + +- (void)saveUserOverwrite:(id)node atPath:(FPath *)path writeId:(NSUInteger)writeId { + NSDictionary *write = + @{ kFUserWriteId: @(writeId), + kFUserWritePath: [path toStringWithTrailingSlash], + kFUserWriteOverwrite: [node valForExport:YES] }; + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:write options:0 error:&error]; + NSAssert(data, @"Failed to serialize user overwrite: %@, (Error: %@)", write, error); + [self.writesDB setData:data forKey:writeRecordKey(writeId)]; +} + +- (void)saveUserMerge:(FCompoundWrite *)merge atPath:(FPath *)path writeId:(NSUInteger)writeId { + NSDictionary *write = + @{ kFUserWriteId: @(writeId), + kFUserWritePath: [path toStringWithTrailingSlash], + kFUserWriteMerge: [merge valForExport:YES] }; + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:write options:0 error:&error]; + NSAssert(data, @"Failed to serialize user merge: %@ (Error: %@)", write, error); + [self.writesDB setData:data forKey:writeRecordKey(writeId)]; +} + +- (void)removeUserWrite:(NSUInteger)writeId { + [self.writesDB removeKey:writeRecordKey(writeId)]; +} + +- (void)removeAllUserWrites { + __block NSUInteger count = 0; + NSDate *start = [NSDate date]; + id batch = [self.writesDB beginWriteBatch]; + [self.writesDB enumerateKeys:^(NSString *key, BOOL *stop) { + [batch removeKey:key]; + count++; + }]; + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076010", @"Failed to remove all users writes on disk!"); + } else { + FFDebug(@"I-RDB076011", @"Removed %lu writes in %fms", (unsigned long)count, [start timeIntervalSinceNow]*-1000); + } +} + +- (NSArray *)userWrites { + NSDate *date = [NSDate date]; + NSMutableArray *writes = [NSMutableArray array]; + [self.writesDB enumerateKeysAndValuesAsData:^(NSString *key, NSData *data, BOOL *stop) { + NSError *error = nil; + NSDictionary *writeJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; + if (writeJSON == nil) { + if (error.code == kFNanFailureCode) { + FFWarn(@"I-RDB076012", @"Failed to deserialize write (%@), likely because of out of range doubles (Error: %@)", + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], + error); + FFWarn(@"I-RDB076013", @"Removing failed write with key %@", key); + [self.writesDB removeKey:key]; + } else { + [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialize write: %@", error]; + } + } else { + NSInteger writeId = ((NSNumber *)writeJSON[kFUserWriteId]).integerValue; + FPath *path = [FPath pathWithString:writeJSON[kFUserWritePath]]; + FWriteRecord *writeRecord; + if (writeJSON[kFUserWriteMerge] != nil) { + // It's a merge + FCompoundWrite *merge = [FCompoundWrite compoundWriteWithValueDictionary:writeJSON[kFUserWriteMerge]]; + writeRecord = [[FWriteRecord alloc] initWithPath:path merge:merge writeId:writeId]; + } else { + // It's an overwrite + NSAssert(writeJSON[kFUserWriteOverwrite] != nil, @"Persisted write did not contain merge or overwrite!"); + id node = [FSnapshotUtilities nodeFrom:writeJSON[kFUserWriteOverwrite]]; + writeRecord = [[FWriteRecord alloc] initWithPath:path overwrite:node writeId:writeId visible:YES]; + } + [writes addObject:writeRecord]; + } + }]; + // Make sure writes are sorted + [writes sortUsingComparator:^NSComparisonResult(FWriteRecord *one, FWriteRecord *two) { + if (one.writeId < two.writeId) { + return NSOrderedAscending; + } else if (one.writeId > two.writeId) { + return NSOrderedDescending; + } else { + return NSOrderedSame; + } + }]; + FFDebug(@"I-RDB076014", @"Loaded %lu writes in %fms", (unsigned long)writes.count, [date timeIntervalSinceNow]*-1000); + return writes; +} + +- (id)serverCacheAtPath:(FPath *)path { + NSDate *start = [NSDate date]; + id data = [self internalNestedDataForPath:path]; + id node = [FSnapshotUtilities nodeFrom:data]; + FFDebug(@"I-RDB076015", @"Loaded node with %d children at %@ in %fms", [node numChildren], path, [start timeIntervalSinceNow]*-1000); + return node; +} + +- (id)serverCacheForKeys:(NSSet *)keys atPath:(FPath *)path { + NSDate *start = [NSDate date]; + __block id node = [FEmptyNode emptyNode]; + [keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) { + id data = [self internalNestedDataForPath:[path childFromString:key]]; + node = [node updateImmediateChild:key withNewChild:[FSnapshotUtilities nodeFrom:data]]; + }]; + FFDebug(@"I-RDB076016", @"Loaded node with %d children for %lu keys at %@ in %fms", [node numChildren], (unsigned long)keys.count, path, [start timeIntervalSinceNow]*-1000); + return node; +} + +- (void)updateServerCache:(id)node atPath:(FPath *)path merge:(BOOL)merge { + NSDate *start = [NSDate date]; + id batch = [self.serverCacheDB beginWriteBatch]; + // Remove any leaf nodes that might be higher up + [self removeAllLeafNodesOnPath:path batch:batch]; + __block NSUInteger counter = 0; + if (merge) { + // remove any children that exist + [node enumerateChildrenUsingBlock:^(NSString *childKey, id childNode, BOOL *stop) { + FPath *childPath = [path childFromString:childKey]; + [self removeAllWithPrefix:serverCacheKey(childPath) batch:batch database:self.serverCacheDB]; + [self saveNodeInternal:childNode atPath:childPath batch:batch counter:&counter]; + }]; + } else { + // remove everything + [self removeAllWithPrefix:serverCacheKey(path) batch:batch database:self.serverCacheDB]; + [self saveNodeInternal:node atPath:path batch:batch counter:&counter]; + } + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076017", @"Failed to update server cache on disk!"); + } else { + FFDebug(@"I-RDB076018", @"Saved %lu leaf nodes for overwrite in %fms", (unsigned long)counter, [start timeIntervalSinceNow]*-1000); + } +} + +- (void)updateServerCacheWithMerge:(FCompoundWrite *)merge atPath:(FPath *)path { + NSDate *start = [NSDate date]; + __block NSUInteger counter = 0; + id batch = [self.serverCacheDB beginWriteBatch]; + // Remove any leaf nodes that might be higher up + [self removeAllLeafNodesOnPath:path batch:batch]; + [merge enumerateWrites:^(FPath *relativePath, id node, BOOL *stop) { + FPath *childPath = [path child:relativePath]; + [self removeAllWithPrefix:serverCacheKey(childPath) batch:batch database:self.serverCacheDB]; + [self saveNodeInternal:node atPath:childPath batch:batch counter:&counter]; + }]; + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076019", @"Failed to update server cache on disk!"); + } else { + FFDebug(@"I-RDB076020", @"Saved %lu leaf nodes for merge in %fms", (unsigned long)counter, [start timeIntervalSinceNow]*-1000); + } +} + +- (void)saveNodeInternal:(id)node atPath:(FPath *)path batch:(id)batch counter:(NSUInteger *)counter { + id data = [node valForExport:YES]; + if(data != nil && ![data isKindOfClass:[NSNull class]]) { + [self internalSetNestedData:data forKey:serverCacheKey(path) withBatch:batch counter:counter]; + } +} + +- (NSUInteger)serverCacheEstimatedSizeInBytes { + // Use the exact size, because for pruning the approximate size can lead to weird situations where we prune everything + // because no compaction is ever run + return [self.serverCacheDB exactSizeFrom:kFServerCachePrefix to:kFServerCacheRangeEnd]; +} + +- (void)pruneCache:(FPruneForest *)pruneForest atPath:(FPath *)path { + // TODO: be more intelligent, don't scan entire database... + + __block NSUInteger pruned = 0; + __block NSUInteger kept = 0; + NSDate *start = [NSDate date]; + + NSString *prefix = serverCacheKey(path); + id batch = [self.serverCacheDB beginWriteBatch]; + + [self.serverCacheDB enumerateKeysWithPrefix:prefix usingBlock:^(NSString *dbKey, BOOL *stop) { + NSString *pathStr = [dbKey substringFromIndex:prefix.length]; + FPath *relativePath = [[FPath alloc] initWith:pathStr]; + if ([pruneForest shouldPruneUnkeptDescendantsAtPath:relativePath]) { + pruned++; + [batch removeKey:dbKey]; + } else { + kept++; + } + }]; + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076021", @"Failed to prune cache on disk!"); + } else { + FFDebug(@"I-RDB076022", @"Pruned %lu paths, kept %lu paths in %fms", (unsigned long)pruned, (unsigned long)kept, [start timeIntervalSinceNow]*-1000); + } +} + +#pragma mark - Tracked Queries + +- (NSArray *)loadTrackedQueries { + NSDate *date = [NSDate date]; + NSMutableArray *trackedQueries = [NSMutableArray array]; + [self.serverCacheDB enumerateKeysWithPrefix:kFTrackedQueriesPrefix asData:^(NSString *key, NSData *data, BOOL *stop) { + NSError *error = nil; + NSDictionary *queryJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; + if (queryJSON == nil) { + if (error.code == kFNanFailureCode) { + FFWarn(@"I-RDB076023", @"Failed to deserialize tracked query (%@), likely because of out of range doubles (Error: %@)", + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], + error); + FFWarn(@"I-RDB076024", @"Removing failed tracked query with key %@", key); + [self.serverCacheDB removeKey:key]; + } else { + [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialize tracked query: %@", error]; + } + } else { + NSUInteger queryId = ((NSNumber *)queryJSON[kFTrackedQueryId]).unsignedIntegerValue; + FPath *path = [FPath pathWithString:queryJSON[kFTrackedQueryPath]]; + FQueryParams *params = [FQueryParams fromQueryObject:queryJSON[kFTrackedQueryParams]]; + FQuerySpec *query = [[FQuerySpec alloc] initWithPath:path params:params]; + BOOL isComplete = [queryJSON[kFTrackedQueryIsComplete] boolValue]; + BOOL isActive = [queryJSON[kFTrackedQueryIsActive] boolValue]; + NSTimeInterval lastUse = [queryJSON[kFTrackedQueryLastUse] doubleValue]; + + FTrackedQuery *trackedQuery = [[FTrackedQuery alloc] initWithId:queryId + query:query + lastUse:lastUse + isActive:isActive + isComplete:isComplete]; + + [trackedQueries addObject:trackedQuery]; + } + }]; + FFDebug(@"I-RDB076025", @"Loaded %lu tracked queries in %fms", (unsigned long)trackedQueries.count, [date timeIntervalSinceNow]*-1000); + return trackedQueries; +} + +- (void)removeTrackedQuery:(NSUInteger)queryId { + NSDate *start = [NSDate date]; + id batch = [self.serverCacheDB beginWriteBatch]; + [batch removeKey:trackedQueryKey(queryId)]; + __block NSUInteger keyCount = 0; + [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) usingBlock:^(NSString *key, BOOL *stop) { + [batch removeKey:key]; + keyCount++; + }]; + + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076026", @"Failed to remove tracked query on disk!"); + } else { + FFDebug(@"I-RDB076027", @"Removed query with id %lu (and removed %lu keys) in %fms", + (unsigned long)queryId, + (unsigned long)keyCount, + [start timeIntervalSinceNow]*-1000); + } +} + +- (void)saveTrackedQuery:(FTrackedQuery *)query { + NSDate *start = [NSDate date]; + NSDictionary *trackedQuery = + @{ + kFTrackedQueryId: @(query.queryId), + kFTrackedQueryPath: [query.query.path toStringWithTrailingSlash], + kFTrackedQueryParams: [query.query.params wireProtocolParams], + kFTrackedQueryLastUse: @(query.lastUse), + kFTrackedQueryIsComplete: @(query.isComplete), + kFTrackedQueryIsActive: @(query.isActive) + }; + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:trackedQuery options:0 error:&error]; + NSAssert(data, @"Failed to serialize tracked query (Error: %@)", error); + [self.serverCacheDB setData:data forKey:trackedQueryKey(query.queryId)]; + FFDebug(@"I-RDB076028", @"Saved tracked query %lu in %fms", (unsigned long)query.queryId, [start timeIntervalSinceNow]*-1000); +} + +- (void)setTrackedQueryKeys:(NSSet *)keys forQueryId:(NSUInteger)queryId { + NSDate *start = [NSDate date]; + __block NSUInteger removed = 0; + __block NSUInteger added = 0; + id batch = [self.serverCacheDB beginWriteBatch]; + NSMutableSet *seenKeys = [NSMutableSet set]; + // First, delete any keys that might be stored and are not part of the current keys + [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) asStrings:^(NSString *dbKey, NSString *actualKey, BOOL *stop) { + if ([keys containsObject:actualKey]) { + // Already in DB + [seenKeys addObject:actualKey]; + } else { + // Not part of set, delete key + [batch removeKey:dbKey]; + removed++; + } + }]; + + // Next add any keys that are missing in the database + [keys enumerateObjectsUsingBlock:^(NSString *childKey, BOOL *stop) { + if (![seenKeys containsObject:childKey]) { + [batch setString:childKey forKey:trackedQueryKeysKey(queryId, childKey)]; + added++; + } + }]; + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076029", @"Failed to set tracked queries on disk!"); + } else { + FFDebug(@"I-RDB076030", @"Set %lu tracked keys (%lu added, %lu removed) for query %lu in %fms", + (unsigned long)keys.count, + (unsigned long)added, + (unsigned long)removed, + (unsigned long)queryId, + [start timeIntervalSinceNow]*-1000); + } +} + +- (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added removedKeys:(NSSet *)removed forQueryId:(NSUInteger)queryId { + NSDate *start = [NSDate date]; + id batch = [self.serverCacheDB beginWriteBatch]; + [removed enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) { + [batch removeKey:trackedQueryKeysKey(queryId, key)]; + }]; + [added enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) { + [batch setString:key forKey:trackedQueryKeysKey(queryId, key)]; + }]; + BOOL success = [batch commit]; + if (!success) { + FFWarn(@"I-RDB076031", @"Failed to update tracked queries on disk!"); + } else { + FFDebug(@"I-RDB076032", @"Added %lu tracked keys, removed %lu for query %lu in %fms", (unsigned long)added.count, (unsigned long)removed.count, (unsigned long)queryId, [start timeIntervalSinceNow]*-1000); + } +} + +- (NSSet *)trackedQueryKeysForQuery:(NSUInteger)queryId { + NSDate *start = [NSDate date]; + NSMutableSet *set = [NSMutableSet set]; + [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) asStrings:^(NSString *dbKey, NSString *actualKey, BOOL *stop) { + [set addObject:actualKey]; + }]; + FFDebug(@"I-RDB076033", @"Loaded %lu tracked keys for query %lu in %fms", (unsigned long)set.count, (unsigned long)queryId, [start timeIntervalSinceNow]*-1000); + return set; +} + +#pragma mark - Internal methods + +- (void)removeAllLeafNodesOnPath:(FPath *)path batch:(id)batch { + while (!path.isEmpty) { + [batch removeKey:serverCacheKey(path)]; + path = [path parent]; + } + // Make sure to delete any nodes at the root + [batch removeKey:serverCacheKey([FPath empty])]; +} + +- (void)removeAllWithPrefix:(NSString *)prefix batch:(id)batch database:(APLevelDB *)database { + assert(prefix != nil); + + [database enumerateKeysWithPrefix:prefix usingBlock:^(NSString *key, BOOL *stop) { + [batch removeKey:key]; + }]; +} + +#pragma mark - Internal helper methods + +- (void)internalSetNestedData:(id)value forKey:(NSString *)key withBatch:(id)batch counter:(NSUInteger *)counter { + if([value isKindOfClass:[NSDictionary class]]) { + NSDictionary* dictionary = value; + [dictionary enumerateKeysAndObjectsUsingBlock:^(id childKey, id obj, BOOL *stop) { + assert(obj != nil); + NSString* childPath = [NSString stringWithFormat:@"%@%@/", key, childKey]; + [self internalSetNestedData:obj forKey:childPath withBatch:batch counter:counter]; + }]; + } + else { + NSData *data = [self serializePrimitive:value]; + [batch setData:data forKey:key]; + (*counter)++; + } +} + +- (id)internalNestedDataForPath:(FPath *)path { + NSAssert(path != nil, @"Path was nil!"); + + NSString *baseKey = serverCacheKey(path); + + // HACK to make sure iter is freed now to avoid race conditions (if self.db is deleted before iter, you get an access violation). + @autoreleasepool { + APLevelDBIterator* iter = [APLevelDBIterator iteratorWithLevelDB:self.serverCacheDB]; + + [iter seekToKey:baseKey]; + if (iter.key == nil || ![iter.key hasPrefix:baseKey]) { + // No data. + return nil; + } else { + return [self internalNestedDataFromIterator:iter andKeyPrefix:baseKey]; + } + } +} + +- (id) internalNestedDataFromIterator:(APLevelDBIterator*)iterator andKeyPrefix:(NSString*)prefix { + NSString* key = iterator.key; + + if ([key isEqualToString:prefix]) { + id result = [self deserializePrimitive:iterator.valueAsData]; + [iterator nextKey]; + return result; + } else { + NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; + while (key != nil && [key hasPrefix:prefix]) { + NSString *relativePath = [key substringFromIndex:prefix.length]; + NSArray* pathPieces = [relativePath componentsSeparatedByString:@"/"]; + assert(pathPieces.count > 0); + NSString *childName = pathPieces[0]; + NSString *childPath = [NSString stringWithFormat:@"%@%@/", prefix, childName]; + id childValue = [self internalNestedDataFromIterator:iterator andKeyPrefix:childPath]; + [dict setValue:childValue forKey:childName]; + + key = iterator.key; + } + return dict; + } +} + + +- (NSData*) serializePrimitive:(id)value { + // HACK: The built-in serialization only works on dicts and arrays. So we create an array and then strip off + // the leading / trailing byte (the [ and ]). + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:@[value] options:0 error:&error]; + NSAssert(data, @"Failed to serialize primitive: %@", error); + + return [data subdataWithRange:NSMakeRange(1, data.length - 2)]; +} + +- (id)fixDoubleParsing:(id)value __attribute__((no_sanitize("float-cast-overflow"))) { + // The parser for double values in JSONSerialization at the root takes some short-cuts and delivers wrong results + // (wrong rounding) for some double values, including 2.47. Because we use the exact bytes for hashing on the server + // this will lead to hash mismatches. The parser of NSNumber seems to be more in line with what the server expects, + // so we use that here + if ([value isKindOfClass:[NSNumber class]]) { + CFNumberType type = CFNumberGetType((CFNumberRef)value); + if (type == kCFNumberDoubleType || type == kCFNumberFloatType) { + // The NSJSON parser returns all numbers as double values, even those that contain no exponent. To + // make sure that the String conversion below doesn't unexpectedly reduce precision, we make sure that + // our number is indeed not an integer. + if ((double)(int64_t)[value doubleValue] != [value doubleValue]) { + NSString *doubleString = [value stringValue]; + return [NSNumber numberWithDouble:[doubleString doubleValue]]; + } else { + return [NSNumber numberWithLongLong:[value longLongValue]]; + } + } + } + return value; +} + +- (id) deserializePrimitive:(NSData*)data { + NSError *error = nil; + id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; + if (result != nil) { + return [self fixDoubleParsing:result]; + } else { + if (error.code == kFNanFailureCode) { + FFWarn(@"I-RDB076034", @"Failed to load primitive %@, likely because doubles where out of range (Error: %@)", + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], error); + return [NSNull null]; + } else { + [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialiaze primitive: %@", error]; + return nil; + } + } + +} + ++ (void)ensureDir:(NSString*)path markAsDoNotBackup:(BOOL)markAsDoNotBackup { + NSError* error; + BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:path + withIntermediateDirectories:YES + attributes:nil + error:&error]; + if (!success) { + @throw [NSException exceptionWithName:@"FailedToCreatePersistenceDir" reason:@"Failed to create persistence directory." userInfo:@{ @"path": path }]; + } + + if (markAsDoNotBackup) { + NSURL *firebaseDirURL = [NSURL fileURLWithPath:path]; + success = [firebaseDirURL setResourceValue:@YES + forKey:NSURLIsExcludedFromBackupKey + error:&error]; + if (!success) { + FFWarn(@"I-RDB076035", @"Failed to mark firebase database folder as do not backup: %@", error); + [NSException raise:@"Error marking as do not backup" format:@"Failed to mark folder %@ as do not backup", firebaseDirURL]; + } + } +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.h new file mode 100644 index 0000000..0d8de55 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.h @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" + +// These are all legacy classes and are used to migrate older persistence data base to newer ones +// These classes should not be used in newer code + +@interface FPendingPut : NSObject + +@property (nonatomic, strong) FPath* path; +@property (nonatomic, strong) id data; +@property (nonatomic, strong) id priority; + +- (id) initWithPath:(FPath*)aPath andData:(id)aData andPriority:aPriority; +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; +@end + + +@interface FPendingPutPriority : NSObject + +@property (nonatomic, strong) FPath* path; +@property (nonatomic, strong) id priority; + +- (id) initWithPath:(FPath*)aPath andPriority:(id)aPriority; +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; + +@end + + +@interface FPendingUpdate : NSObject + +@property (nonatomic, strong) FPath* path; +@property (nonatomic, strong) NSDictionary* data; + +- (id) initWithPath:(FPath*)aPath andData:(NSDictionary*)aData; +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.m new file mode 100644 index 0000000..12be825 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPendingPut.m @@ -0,0 +1,112 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FPendingPut.h" + +@implementation FPendingPut + +@synthesize path; +@synthesize data; + +- (id) initWithPath:(FPath *)aPath andData:(id)aData andPriority:(id)aPriority { + self = [super init]; + if (self) { + self.path = aPath; + self.data = aData; + self.priority = aPriority; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:[self.path description] forKey:@"path"]; + [aCoder encodeObject:self.data forKey:@"data"]; + [aCoder encodeObject:self.priority forKey:@"priority"]; +} + +- (id)initWithCoder:(NSCoder *)aDecoder { + self = [super init]; + if(self) { + self.path = [[FPath alloc] initWith:[aDecoder decodeObjectForKey:@"path"]]; + self.data = [aDecoder decodeObjectForKey:@"data"]; + self.priority = [aDecoder decodeObjectForKey:@"priority"]; + } + return self; +} + +@end + + +@implementation FPendingPutPriority + +@synthesize path; +@synthesize priority; + +- (id) initWithPath:(FPath *)aPath andPriority:(id)aPriority { + self = [super init]; + if (self) { + self.path = aPath; + self.priority = aPriority; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:[self.path description] forKey:@"path"]; + [aCoder encodeObject:self.priority forKey:@"priority"]; +} + +- (id)initWithCoder:(NSCoder *)aDecoder { + self = [super init]; + if(self) { + self.path = [[FPath alloc] initWith:[aDecoder decodeObjectForKey:@"path"]]; + self.priority = [aDecoder decodeObjectForKey:@"priority"]; + } + return self; +} + +@end + + +@implementation FPendingUpdate + +@synthesize path; +@synthesize data; + +- (id) initWithPath:(FPath *)aPath andData:(id)aData { + self = [super init]; + if (self) { + self.path = aPath; + self.data = aData; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:[self.path description] forKey:@"path"]; + [aCoder encodeObject:self.data forKey:@"data"]; +} + +- (id)initWithCoder:(NSCoder *)aDecoder { + self = [super init]; + if(self) { + self.path = [[FPath alloc] initWith:[aDecoder decodeObjectForKey:@"path"]]; + self.data = [aDecoder decodeObjectForKey:@"data"]; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.h new file mode 100644 index 0000000..a3688b3 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FNode.h" +#import "FCompoundWrite.h" +#import "FQuerySpec.h" +#import "FRepoInfo.h" +#import "FStorageEngine.h" +#import "FCachePolicy.h" +#import "FCacheNode.h" + +@interface FPersistenceManager : NSObject + +- (id)initWithStorageEngine:(id)storageEngine cachePolicy:(id)cachePolicy; +- (void)close; + +- (void)saveUserOverwrite:(id)node atPath:(FPath *)path writeId:(NSUInteger)writeId; +- (void)saveUserMerge:(FCompoundWrite *)merge atPath:(FPath *)path writeId:(NSUInteger)writeId; +- (void)removeUserWrite:(NSUInteger)writeId; +- (void)removeAllUserWrites; +- (NSArray *)userWrites; + +- (FCacheNode *)serverCacheForQuery:(FQuerySpec *)spec; +- (void)updateServerCacheWithNode:(id)node forQuery:(FQuerySpec *)spec; +- (void)updateServerCacheWithMerge:(FCompoundWrite *)merge atPath:(FPath *)path; + +- (void)applyUserWrite:(id)write toServerCacheAtPath:(FPath *)path; +- (void)applyUserMerge:(FCompoundWrite *)merge toServerCacheAtPath:(FPath *)path; + +- (void)setQueryComplete:(FQuerySpec *)spec; +- (void)setQueryActive:(FQuerySpec *)spec; +- (void)setQueryInactive:(FQuerySpec *)spec; + +- (void)setTrackedQueryKeys:(NSSet *)keys forQuery:(FQuerySpec *)query; +- (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added removedKeys:(NSSet *)removed forQuery:(FQuerySpec *)query; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.m new file mode 100644 index 0000000..b488f3e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPersistenceManager.m @@ -0,0 +1,191 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPersistenceManager.h" +#import "FLevelDBStorageEngine.h" +#import "FCacheNode.h" +#import "FIndexedNode.h" +#import "FTrackedQueryManager.h" +#import "FTrackedQuery.h" +#import "FUtilities.h" +#import "FPruneForest.h" +#import "FClock.h" + +@interface FPersistenceManager () + +@property (nonatomic, strong) id storageEngine; +@property (nonatomic, strong) id cachePolicy; +@property (nonatomic, strong) FTrackedQueryManager *trackedQueryManager; +@property (nonatomic) NSUInteger serverCacheUpdatesSinceLastPruneCheck; + +@end + +@implementation FPersistenceManager + +- (id)initWithStorageEngine:(id)storageEngine cachePolicy:(id)cachePolicy { + self = [super init]; + if (self != nil) { + self->_storageEngine = storageEngine; + self->_cachePolicy = cachePolicy; + self->_trackedQueryManager = [[FTrackedQueryManager alloc] initWithStorageEngine:self.storageEngine + clock:[FSystemClock clock]]; + } + return self; +} + +- (void)close { + [self.storageEngine close]; + self.storageEngine = nil; + self.trackedQueryManager = nil; +} + +- (void)saveUserOverwrite:(id)node atPath:(FPath *)path writeId:(NSUInteger)writeId { + [self.storageEngine saveUserOverwrite:node atPath:path writeId:writeId]; +} + +- (void)saveUserMerge:(FCompoundWrite *)merge atPath:(FPath *)path writeId:(NSUInteger)writeId { + [self.storageEngine saveUserMerge:merge atPath:path writeId:writeId]; +} + +- (void)removeUserWrite:(NSUInteger)writeId { + [self.storageEngine removeUserWrite:writeId]; +} + +- (void)removeAllUserWrites { + [self.storageEngine removeAllUserWrites]; +} + +- (NSArray *)userWrites { + return [self.storageEngine userWrites]; +} + +- (FCacheNode *)serverCacheForQuery:(FQuerySpec *)query { + NSSet *trackedKeys; + BOOL complete; + // TODO[offline]: Should we use trackedKeys to find out if this location is a child of a complete query? + if ([self.trackedQueryManager isQueryComplete:query]) { + complete = YES; + FTrackedQuery *trackedQuery = [self.trackedQueryManager findTrackedQuery:query]; + if (!query.loadsAllData && trackedQuery.isComplete) { + trackedKeys = [self.storageEngine trackedQueryKeysForQuery:trackedQuery.queryId]; + } else { + trackedKeys = nil; + } + } else { + complete = NO; + trackedKeys = [self.trackedQueryManager knownCompleteChildrenAtPath:query.path]; + } + + id node; + if (trackedKeys != nil) { + node = [self.storageEngine serverCacheForKeys:trackedKeys atPath:query.path]; + } else { + node = [self.storageEngine serverCacheAtPath:query.path]; + } + + FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:node index:query.index]; + return [[FCacheNode alloc] initWithIndexedNode:indexedNode isFullyInitialized:complete isFiltered:(trackedKeys != nil)]; +} + +- (void)updateServerCacheWithNode:(id)node forQuery:(FQuerySpec *)query { + BOOL merge = !query.loadsAllData; + [self.storageEngine updateServerCache:node atPath:query.path merge:merge]; + [self setQueryComplete:query]; + [self doPruneCheckAfterServerUpdate]; +} + +- (void)updateServerCacheWithMerge:(FCompoundWrite *)merge atPath:(FPath *)path { + [self.storageEngine updateServerCacheWithMerge:merge atPath:path]; + [self doPruneCheckAfterServerUpdate]; +} + +- (void)applyUserMerge:(FCompoundWrite *)merge toServerCacheAtPath:(FPath *)path { + // TODO[offline]: rework this to be more efficient + [merge enumerateWrites:^(FPath *relativePath, id node, BOOL *stop) { + [self applyUserWrite:node toServerCacheAtPath:[path child:relativePath]]; + }]; +} + +- (void)applyUserWrite:(id)write toServerCacheAtPath:(FPath *)path { + // This is a hack to guess whether we already cached this because we got a server data update for this + // write via an existing active default query. If we didn't, then we'll manually cache this and add a + // tracked query to mark it complete and keep it cached. + // Unfortunately this is just a guess and it's possible that we *did* get an update (e.g. via a filtered + // query) and by overwriting the cache here, we'll actually store an incorrect value (e.g. in the case + // that we wrote a ServerValue.TIMESTAMP and the server resolved it to a different value). + // TODO[offline]: Consider reworking. + if (![self.trackedQueryManager hasActiveDefaultQueryAtPath:path]) { + [self.storageEngine updateServerCache:write atPath:path merge:NO]; + [self.trackedQueryManager ensureCompleteTrackedQueryAtPath:path]; + } +} + +- (void)setQueryComplete:(FQuerySpec *)query { + if (query.loadsAllData) { + [self.trackedQueryManager setQueriesCompleteAtPath:query.path]; + } else { + [self.trackedQueryManager setQueryComplete:query]; + } +} + +- (void)setQueryActive:(FQuerySpec *)spec { + [self.trackedQueryManager setQueryActive:spec]; +} + +- (void)setQueryInactive:(FQuerySpec *)spec { + [self.trackedQueryManager setQueryInactive:spec]; +} + +- (void)doPruneCheckAfterServerUpdate { + self.serverCacheUpdatesSinceLastPruneCheck++; + if ([self.cachePolicy shouldCheckCacheSize:self.serverCacheUpdatesSinceLastPruneCheck]) { + FFDebug(@"I-RDB078001", @"Reached prune check threshold. Checking..."); + NSDate *date = [NSDate date]; + self.serverCacheUpdatesSinceLastPruneCheck = 0; + BOOL canPrune = YES; + NSUInteger cacheSize = [self.storageEngine serverCacheEstimatedSizeInBytes]; + FFDebug(@"I-RDB078002", @"Server cache size: %lu", (unsigned long)cacheSize); + while (canPrune && [self.cachePolicy shouldPruneCacheWithSize:cacheSize + numberOfTrackedQueries:self.trackedQueryManager.numberOfPrunableQueries]) { + FPruneForest *pruneForest = [self.trackedQueryManager pruneOldQueries:self.cachePolicy]; + if (pruneForest.prunesAnything) { + [self.storageEngine pruneCache:pruneForest atPath:[FPath empty]]; + } else { + canPrune = NO; + } + cacheSize = [self.storageEngine serverCacheEstimatedSizeInBytes]; + FFDebug(@"I-RDB078003", @"Cache size after pruning: %lu", (unsigned long)cacheSize); + } + FFDebug(@"I-RDB078004", @"Pruning round took %fms", [date timeIntervalSinceNow]*-1000); + } +} + +- (void)setTrackedQueryKeys:(NSSet *)keys forQuery:(FQuerySpec *)query { + NSAssert(!query.loadsAllData, @"We should only track keys for filtered queries"); + FTrackedQuery *trackedQuery = [self.trackedQueryManager findTrackedQuery:query]; + NSAssert(trackedQuery.isActive, @"We only expect tracked keys for currently-active queries."); + [self.storageEngine setTrackedQueryKeys:keys forQueryId:trackedQuery.queryId]; +} + +- (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added removedKeys:(NSSet *)removed forQuery:(FQuerySpec *)query { + NSAssert(!query.loadsAllData, @"We should only track keys for filtered queries"); + FTrackedQuery *trackedQuery = [self.trackedQueryManager findTrackedQuery:query]; + NSAssert(trackedQuery.isActive, @"We only expect tracked keys for currently-active queries."); + [self.storageEngine updateTrackedQueryKeysWithAddedKeys:added removedKeys:removed forQueryId:trackedQuery.queryId]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.h new file mode 100644 index 0000000..9e77217 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FPath; + +@interface FPruneForest : NSObject + ++ (FPruneForest *)empty; + +- (BOOL)prunesAnything; +- (BOOL)shouldPruneUnkeptDescendantsAtPath:(FPath *)path; +- (BOOL)shouldKeepPath:(FPath *)path; +- (BOOL)affectsPath:(FPath *)path; +- (FPruneForest *)child:(NSString *)childKey; +- (FPruneForest *)childAtPath:(FPath *)childKey; +- (FPruneForest *)prunePath:(FPath *)path; +- (FPruneForest *)keepPath:(FPath *)path; +- (FPruneForest *)keepAll:(NSSet *)children atPath:(FPath *)path; +- (FPruneForest *)pruneAll:(NSSet *)children atPath:(FPath *)path; + +- (void)enumarateKeptNodesUsingBlock:(void (^)(FPath *path))block; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.m new file mode 100644 index 0000000..ae5ce91 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FPruneForest.m @@ -0,0 +1,177 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FPruneForest.h" + +#import "FImmutableTree.h" + +@interface FPruneForest () + +@property (nonatomic, strong) FImmutableTree *pruneForest; + +@end + +@implementation FPruneForest + +static BOOL (^kFPrunePredicate)(id) = ^BOOL(NSNumber *pruneValue) { + return [pruneValue boolValue]; +}; + +static BOOL (^kFKeepPredicate)(id) = ^BOOL(NSNumber *pruneValue) { + return ![pruneValue boolValue]; +}; + + ++ (FImmutableTree *)pruneTree { + static dispatch_once_t onceToken; + static FImmutableTree *pruneTree; + dispatch_once(&onceToken, ^{ + pruneTree = [[FImmutableTree alloc] initWithValue:@YES]; + }); + return pruneTree; +} + ++ (FImmutableTree *)keepTree { + static dispatch_once_t onceToken; + static FImmutableTree *keepTree; + dispatch_once(&onceToken, ^{ + keepTree = [[FImmutableTree alloc] initWithValue:@NO]; + }); + return keepTree; +} + +- (id) initWithForest:(FImmutableTree *)tree { + self = [super init]; + if (self != nil) { + self->_pruneForest = tree; + } + return self; +} + ++ (FPruneForest *)empty { + static dispatch_once_t onceToken; + static FPruneForest *forest; + dispatch_once(&onceToken, ^{ + forest = [[FPruneForest alloc] initWithForest:[FImmutableTree empty]]; + }); + return forest; +} + +- (BOOL)prunesAnything { + return [self.pruneForest containsValueMatching:kFPrunePredicate]; +} + +- (BOOL)shouldPruneUnkeptDescendantsAtPath:(FPath *)path { + NSNumber *shouldPrune = [self.pruneForest leafMostValueOnPath:path]; + return shouldPrune != nil && [shouldPrune boolValue]; +} + +- (BOOL)shouldKeepPath:(FPath *)path { + NSNumber *shouldPrune = [self.pruneForest leafMostValueOnPath:path]; + return shouldPrune != nil && ![shouldPrune boolValue]; +} + +- (BOOL)affectsPath:(FPath *)path { + return [self.pruneForest rootMostValueOnPath:path] != nil || ![[self.pruneForest subtreeAtPath:path] isEmpty]; +} + +- (FPruneForest *)child:(NSString *)childKey { + FImmutableTree *childPruneForest = [self.pruneForest.children get:childKey]; + if (childPruneForest == nil) { + if (self.pruneForest.value != nil) { + childPruneForest = [self.pruneForest.value boolValue] ? [FPruneForest pruneTree] : [FPruneForest keepTree]; + } else { + childPruneForest = [FImmutableTree empty]; + } + } else { + if (childPruneForest.value == nil && self.pruneForest.value != nil) { + childPruneForest = [childPruneForest setValue:self.pruneForest.value atPath:[FPath empty]]; + } + } + return [[FPruneForest alloc] initWithForest:childPruneForest]; +} + +- (FPruneForest *)childAtPath:(FPath *)path { + if (path.isEmpty) { + return self; + } else { + return [[self child:path.getFront] childAtPath:[path popFront]]; + } +} + +- (FPruneForest *)prunePath:(FPath *)path { + if ([self.pruneForest rootMostValueOnPath:path matching:kFKeepPredicate]) { + [NSException raise:NSInvalidArgumentException format:@"Can't prune path that was kept previously!"]; + } + if ([self.pruneForest rootMostValueOnPath:path matching:kFPrunePredicate]) { + // This path will already be pruned + return self; + } else { + FImmutableTree *newPruneForest = [self.pruneForest setTree:[FPruneForest pruneTree] atPath:path]; + return [[FPruneForest alloc] initWithForest:newPruneForest]; + } +} + +- (FPruneForest *)keepPath:(FPath *)path { + if ([self.pruneForest rootMostValueOnPath:path matching:kFKeepPredicate]) { + // This path will already be kept + return self; + } else { + FImmutableTree *newPruneForest = [self.pruneForest setTree:[FPruneForest keepTree] atPath:path]; + return [[FPruneForest alloc] initWithForest:newPruneForest]; + } +} + +- (FPruneForest *)keepAll:(NSSet *)children atPath:(FPath *)path { + if ([self.pruneForest rootMostValueOnPath:path matching:kFKeepPredicate]) { + // This path will already be kept + return self; + } else { + return [self setPruneValue:[FPruneForest keepTree] forAll:children atPath:path]; + } +} + +- (FPruneForest *)pruneAll:(NSSet *)children atPath:(FPath *)path { + if ([self.pruneForest rootMostValueOnPath:path matching:kFKeepPredicate]) { + [NSException raise:NSInvalidArgumentException format:@"Can't prune path that was kept previously!"]; + } + if ([self.pruneForest rootMostValueOnPath:path matching:kFPrunePredicate]) { + // This path will already be pruned + return self; + } else { + return [self setPruneValue:[FPruneForest pruneTree] forAll:children atPath:path]; + } +} + +- (FPruneForest *)setPruneValue:(FImmutableTree *)pruneValue forAll:(NSSet *)children atPath:(FPath *)path { + FImmutableTree *subtree = [self.pruneForest subtreeAtPath:path]; + __block FImmutableSortedDictionary *childrenDictionary = subtree.children; + [children enumerateObjectsUsingBlock:^(NSString *childKey, BOOL *stop) { + childrenDictionary = [childrenDictionary insertKey:childKey withValue:pruneValue]; + }]; + FImmutableTree *newSubtree = [[FImmutableTree alloc] initWithValue:subtree.value children:childrenDictionary]; + return [[FPruneForest alloc] initWithForest:[self.pruneForest setTree:newSubtree atPath:path]]; +} + +- (void)enumarateKeptNodesUsingBlock:(void (^)(FPath *))block { + [self.pruneForest forEach:^(FPath *path, id value) { + if (value != nil && ![value boolValue]) { + block(path); + } + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FStorageEngine.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FStorageEngine.h new file mode 100644 index 0000000..4f168e7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FStorageEngine.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FNode; +@class FPruneForest; +@class FPath; +@class FCompoundWrite; +@class FQuerySpec; +@class FTrackedQuery; + +@protocol FStorageEngine + +- (void)close; + +- (void)saveUserOverwrite:(id)node atPath:(FPath *)path writeId:(NSUInteger)writeId; +- (void)saveUserMerge:(FCompoundWrite *)merge atPath:(FPath *)path writeId:(NSUInteger)writeId; +- (void)removeUserWrite:(NSUInteger)writeId; +- (void)removeAllUserWrites; +- (NSArray *)userWrites; + +- (id)serverCacheAtPath:(FPath *)path; +- (id)serverCacheForKeys:(NSSet *)keys atPath:(FPath *)path; +- (void)updateServerCache:(id)node atPath:(FPath *)path merge:(BOOL)merge; +- (void)updateServerCacheWithMerge:(FCompoundWrite *)merge atPath:(FPath *)path; +- (NSUInteger)serverCacheEstimatedSizeInBytes; + +- (void)pruneCache:(FPruneForest *)pruneForest atPath:(FPath *)path; + +- (NSArray *)loadTrackedQueries; +- (void)removeTrackedQuery:(NSUInteger)queryId; +- (void)saveTrackedQuery:(FTrackedQuery *)query; + +- (void)setTrackedQueryKeys:(NSSet *)keys forQueryId:(NSUInteger)queryId; +- (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added removedKeys:(NSSet *)removed forQueryId:(NSUInteger)queryId; +- (NSSet *)trackedQueryKeysForQuery:(NSUInteger)queryId; + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.h new file mode 100644 index 0000000..7bc8ef1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FQuerySpec; + +@interface FTrackedQuery : NSObject + +@property (nonatomic, readonly) NSUInteger queryId; +@property (nonatomic, strong, readonly) FQuerySpec *query; +@property (nonatomic, readonly) NSTimeInterval lastUse; +@property (nonatomic, readonly) BOOL isComplete; +@property (nonatomic, readonly) BOOL isActive; + +- (id)initWithId:(NSUInteger)queryId query:(FQuerySpec *)query lastUse:(NSTimeInterval)lastUse isActive:(BOOL)isActive; +- (id)initWithId:(NSUInteger)queryId + query:(FQuerySpec *)query + lastUse:(NSTimeInterval)lastUse + isActive:(BOOL)isActive + isComplete:(BOOL)isComplete; + +- (FTrackedQuery *)updateLastUse:(NSTimeInterval)lastUse; +- (FTrackedQuery *)setComplete; +- (FTrackedQuery *)setActiveState:(BOOL)isActive; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.m new file mode 100644 index 0000000..1720805 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQuery.m @@ -0,0 +1,102 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTrackedQuery.h" + +#import "FQuerySpec.h" + +@interface FTrackedQuery () + +@property (nonatomic, readwrite) NSUInteger queryId; +@property (nonatomic, strong, readwrite) FQuerySpec *query; +@property (nonatomic, readwrite) NSTimeInterval lastUse; +@property (nonatomic, readwrite) BOOL isComplete; +@property (nonatomic, readwrite) BOOL isActive; + +@end + + +@implementation FTrackedQuery + +- (id)initWithId:(NSUInteger)queryId + query:(FQuerySpec *)query + lastUse:(NSTimeInterval)lastUse + isActive:(BOOL)isActive + isComplete:(BOOL)isComplete { + self = [super init]; + if (self != nil) { + self->_queryId = queryId; + self->_query = query; + self->_lastUse = lastUse; + self->_isComplete = isComplete; + self->_isActive = isActive; + } + return self; +} + +- (id)initWithId:(NSUInteger)queryId query:(FQuerySpec *)query lastUse:(NSTimeInterval)lastUse isActive:(BOOL)isActive { + return [self initWithId:queryId query:query lastUse:lastUse isActive:isActive isComplete:NO]; +} + +- (FTrackedQuery *)updateLastUse:(NSTimeInterval)lastUse { + return [[FTrackedQuery alloc] initWithId:self.queryId + query:self.query + lastUse:lastUse + isActive:self.isActive + isComplete:self.isComplete]; +} + +- (FTrackedQuery *)setComplete { + return [[FTrackedQuery alloc] initWithId:self.queryId + query:self.query + lastUse:self.lastUse + isActive:self.isActive + isComplete:YES]; +} + +- (FTrackedQuery *)setActiveState:(BOOL)isActive { + return [[FTrackedQuery alloc] initWithId:self.queryId + query:self.query + lastUse:self.lastUse + isActive:isActive + isComplete:self.isComplete]; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[FTrackedQuery class]]) { + return NO; + } + FTrackedQuery *other = (FTrackedQuery *)object; + if (self.queryId != other.queryId) return NO; + if (self.query != other.query && ![self.query isEqual:other.query]) return NO; + if (self.lastUse != other.lastUse) return NO; + if (self.isComplete != other.isComplete) return NO; + if (self.isActive != other.isActive) return NO; + + return YES; +} + +- (NSUInteger)hash { + NSUInteger hash = self.queryId; + hash = hash * 31 + self.query.hash; + hash = hash * 31 + (self.isActive ? 1 : 0); + hash = hash * 31 + (NSUInteger)self.lastUse; + hash = hash * 31 + (self.isComplete ? 1 : 0); + hash = hash * 31 + (self.isActive ? 1 : 0); + return hash; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.h new file mode 100644 index 0000000..ba2631b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.h @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FStorageEngine; +@protocol FClock; +@protocol FCachePolicy; +@class FQuerySpec; +@class FPath; +@class FTrackedQuery; +@class FPruneForest; + +@interface FTrackedQueryManager : NSObject + +- (id)initWithStorageEngine:(id)storageEngine clock:(id)clock; + +- (FTrackedQuery *)findTrackedQuery:(FQuerySpec *)query; + +- (BOOL)isQueryComplete:(FQuerySpec *)query; + +- (void)removeTrackedQuery:(FQuerySpec *)query; +- (void)setQueryComplete:(FQuerySpec *)query; +- (void)setQueriesCompleteAtPath:(FPath *)path; +- (void)setQueryActive:(FQuerySpec *)query; +- (void)setQueryInactive:(FQuerySpec *)query; + +- (BOOL)hasActiveDefaultQueryAtPath:(FPath *)path; +- (void)ensureCompleteTrackedQueryAtPath:(FPath *)path; + +- (FPruneForest *)pruneOldQueries:(id)cachePolicy; +- (NSUInteger)numberOfPrunableQueries; +- (NSSet *)knownCompleteChildrenAtPath:(FPath *)path; + +// For testing +- (void)verifyCache; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.m new file mode 100644 index 0000000..9176f25 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Persistence/FTrackedQueryManager.m @@ -0,0 +1,322 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTrackedQueryManager.h" +#import "FImmutableTree.h" +#import "FLevelDBStorageEngine.h" +#import "FUtilities.h" +#import "FTrackedQuery.h" +#import "FPruneForest.h" +#import "FClock.h" +#import "FUtilities.h" +#import "FCachePolicy.h" + +@interface FTrackedQueryManager () + +@property (nonatomic, strong) FImmutableTree *trackedQueryTree; +@property (nonatomic, strong) id storageEngine; +@property (nonatomic, strong) id clock; +@property (nonatomic) NSUInteger currentQueryId; + +@end + +@implementation FTrackedQueryManager + +- (id)initWithStorageEngine:(id)storageEngine clock:(id)clock { + self = [super init]; + if (self != nil) { + self->_storageEngine = storageEngine; + self->_clock = clock; + self->_trackedQueryTree = [FImmutableTree empty]; + + NSTimeInterval lastUse = [clock currentTime]; + + NSArray *trackedQueries = [self.storageEngine loadTrackedQueries]; + [trackedQueries enumerateObjectsUsingBlock:^(FTrackedQuery *trackedQuery, NSUInteger idx, BOOL *stop) { + self.currentQueryId = MAX(trackedQuery.queryId + 1, self.currentQueryId); + if (trackedQuery.isActive) { + trackedQuery = [[trackedQuery setActiveState:NO] updateLastUse:lastUse]; + FFDebug(@"I-RDB081001", @"Setting active query %lu from previous app start inactive", (unsigned long)trackedQuery.queryId); + [self.storageEngine saveTrackedQuery:trackedQuery]; + } + [self cacheTrackedQuery:trackedQuery]; + }]; + } + return self; +} + ++ (void)assertValidTrackedQuery:(FQuerySpec *)query { + NSAssert(!query.loadsAllData || query.isDefault, @"Can't have tracked non-default query that loads all data"); +} + ++ (FQuerySpec *)normalizeQuery:(FQuerySpec *)query { + return query.loadsAllData ? [FQuerySpec defaultQueryAtPath:query.path] : query; +} + +- (FTrackedQuery *)findTrackedQuery:(FQuerySpec *)query { + query = [FTrackedQueryManager normalizeQuery:query]; + NSDictionary *set = [self.trackedQueryTree valueAtPath:query.path]; + return set[query.params]; +} + +- (void)removeTrackedQuery:(FQuerySpec *)query { + query = [FTrackedQueryManager normalizeQuery:query]; + FTrackedQuery *trackedQuery = [self findTrackedQuery:query]; + NSAssert(trackedQuery, @"Tracked query must exist to be removed!"); + + [self.storageEngine removeTrackedQuery:trackedQuery.queryId]; + NSMutableDictionary *trackedQueries = [self.trackedQueryTree valueAtPath:query.path]; + [trackedQueries removeObjectForKey:query.params]; +} + +- (void)setQueryActive:(FQuerySpec *)query { + [self setQueryActive:YES forQuery:query]; +} + +- (void)setQueryInactive:(FQuerySpec *)query { + [self setQueryActive:NO forQuery:query]; +} + +- (void)setQueryActive:(BOOL)isActive forQuery:(FQuerySpec *)query { + query = [FTrackedQueryManager normalizeQuery:query]; + FTrackedQuery *trackedQuery = [self findTrackedQuery:query]; + + // Regardless of whether it's now active or no langer active, we update the lastUse time + NSTimeInterval lastUse = [self.clock currentTime]; + if (trackedQuery != nil) { + trackedQuery = [[trackedQuery updateLastUse:lastUse] setActiveState:isActive]; + [self.storageEngine saveTrackedQuery:trackedQuery]; + } else { + NSAssert(isActive, @"If we're setting the query to inactive, we should already be tracking it!"); + trackedQuery = [[FTrackedQuery alloc] initWithId:self.currentQueryId++ + query:query + lastUse:lastUse + isActive:isActive]; + [self.storageEngine saveTrackedQuery:trackedQuery]; + } + + [self cacheTrackedQuery:trackedQuery]; +} + +- (void)setQueryComplete:(FQuerySpec *)query { + query = [FTrackedQueryManager normalizeQuery:query]; + FTrackedQuery *trackedQuery = [self findTrackedQuery:query]; + if (!trackedQuery) { + // We might have removed a query and pruned it before we got the complete message from the server... + FFWarn(@"I-RDB081002", @"Trying to set a query complete that is not tracked!"); + } else if (!trackedQuery.isComplete) { + trackedQuery = [trackedQuery setComplete]; + [self.storageEngine saveTrackedQuery:trackedQuery]; + [self cacheTrackedQuery:trackedQuery]; + } else { + // Nothing to do, already marked complete + } +} + +- (void)setQueriesCompleteAtPath:(FPath *)path { + [[self.trackedQueryTree subtreeAtPath:path] forEach:^(FPath *childPath, NSDictionary *trackedQueries) { + [trackedQueries enumerateKeysAndObjectsUsingBlock:^(FQueryParams *parms, FTrackedQuery *trackedQuery, BOOL *stop) { + if (!trackedQuery.isComplete) { + FTrackedQuery *newTrackedQuery = [trackedQuery setComplete]; + [self.storageEngine saveTrackedQuery:newTrackedQuery]; + [self cacheTrackedQuery:newTrackedQuery]; + } + }]; + }]; +} + +- (BOOL)isQueryComplete:(FQuerySpec *)query { + if ([self isIncludedInDefaultCompleteQuery:query]) { + return YES; + } else if (query.loadsAllData) { + // We didn't find a default complete query, so must not be complete. + return NO; + } else { + NSDictionary *trackedQueries = [self.trackedQueryTree valueAtPath:query.path]; + return [trackedQueries[query.params] isComplete]; + } +} + +- (BOOL)hasActiveDefaultQueryAtPath:(FPath *)path { + return [self.trackedQueryTree rootMostValueOnPath:path matching:^BOOL(NSDictionary *trackedQueries) { + return [trackedQueries[[FQueryParams defaultInstance]] isActive]; + }] != nil; +} + +- (void)ensureCompleteTrackedQueryAtPath:(FPath *)path { + FQuerySpec *query = [FQuerySpec defaultQueryAtPath:path]; + if (![self isIncludedInDefaultCompleteQuery:query]) { + FTrackedQuery *trackedQuery = [self findTrackedQuery:query]; + if (trackedQuery == nil) { + trackedQuery = [[FTrackedQuery alloc] initWithId:self.currentQueryId++ + query:query + lastUse:[self.clock currentTime] + isActive:NO + isComplete:YES]; + } else { + NSAssert(!trackedQuery.isComplete, @"This should have been handled above!"); + trackedQuery = [trackedQuery setComplete]; + } + [self.storageEngine saveTrackedQuery:trackedQuery]; + [self cacheTrackedQuery:trackedQuery]; + } +} + +- (BOOL)isIncludedInDefaultCompleteQuery:(FQuerySpec *)query { + return [self.trackedQueryTree findRootMostMatchingPath:query.path predicate:^BOOL(NSDictionary *trackedQueries) { + return [trackedQueries[[FQueryParams defaultInstance]] isComplete]; + }] != nil; +} + +- (void)cacheTrackedQuery:(FTrackedQuery *)query { + [FTrackedQueryManager assertValidTrackedQuery:query.query]; + NSMutableDictionary *trackedDict = [self.trackedQueryTree valueAtPath:query.query.path]; + if (trackedDict == nil) { + trackedDict = [NSMutableDictionary dictionary]; + self.trackedQueryTree = [self.trackedQueryTree setValue:trackedDict atPath:query.query.path]; + } + trackedDict[query.query.params] = query; +} + +- (NSUInteger) numberOfQueriesToPrune:(id)cachePolicy prunableCount:(NSUInteger)numPrunable { + NSUInteger numPercent = (NSUInteger)ceilf(numPrunable * [cachePolicy percentOfQueriesToPruneAtOnce]); + NSUInteger maxToKeep = [cachePolicy maxNumberOfQueriesToKeep]; + NSUInteger numMax = (numPrunable > maxToKeep) ? numPrunable - maxToKeep : 0; + // Make sure we get below number of max queries to prune + return MAX(numMax, numPercent); +} + +- (FPruneForest *)pruneOldQueries:(id)cachePolicy { + NSMutableArray *pruneableQueries = [NSMutableArray array]; + NSMutableArray *unpruneableQueries = [NSMutableArray array]; + [self.trackedQueryTree forEach:^(FPath *path, NSDictionary *trackedQueries) { + [trackedQueries enumerateKeysAndObjectsUsingBlock:^(FQueryParams *params, FTrackedQuery *trackedQuery, BOOL *stop) { + if (!trackedQuery.isActive) { + [pruneableQueries addObject:trackedQuery]; + } else { + [unpruneableQueries addObject:trackedQuery]; + } + }]; + }]; + [pruneableQueries sortUsingComparator:^NSComparisonResult(FTrackedQuery *q1, FTrackedQuery *q2) { + if (q1.lastUse < q2.lastUse) { + return NSOrderedAscending; + } else if (q1.lastUse > q2.lastUse) { + return NSOrderedDescending; + } else { + return NSOrderedSame; + } + }]; + + + __block FPruneForest *pruneForest = [FPruneForest empty]; + NSUInteger numToPrune = [self numberOfQueriesToPrune:cachePolicy prunableCount:pruneableQueries.count]; + + // TODO: do in transaction + for (NSUInteger i = 0; i < numToPrune; i++) { + FTrackedQuery *toPrune = pruneableQueries[i]; + pruneForest = [pruneForest prunePath:toPrune.query.path]; + [self removeTrackedQuery:toPrune.query]; + } + + // Keep the rest of the prunable queries + for (NSUInteger i = numToPrune; i < pruneableQueries.count; i++) { + FTrackedQuery *toKeep = pruneableQueries[i]; + pruneForest = [pruneForest keepPath:toKeep.query.path]; + } + + // Also keep unprunable queries + [unpruneableQueries enumerateObjectsUsingBlock:^(FTrackedQuery *toKeep, NSUInteger idx, BOOL *stop) { + pruneForest = [pruneForest keepPath:toKeep.query.path]; + }]; + + return pruneForest; +} + +- (NSUInteger)numberOfPrunableQueries { + __block NSUInteger count = 0; + [self.trackedQueryTree forEach:^(FPath *path, NSDictionary *trackedQueries) { + [trackedQueries enumerateKeysAndObjectsUsingBlock:^(FQueryParams *params, FTrackedQuery *trackedQuery, BOOL *stop) { + if (!trackedQuery.isActive) { + count++; + } + }]; + }]; + return count; +} + +- (NSSet *)filteredQueryIdsAtPath:(FPath *)path { + NSDictionary *queries = [self.trackedQueryTree valueAtPath:path]; + if (queries) { + NSMutableSet *ids = [NSMutableSet set]; + [queries enumerateKeysAndObjectsUsingBlock:^(FQueryParams *params, FTrackedQuery *query, BOOL *stop) { + if (!query.query.loadsAllData) { + [ids addObject:@(query.queryId)]; + } + }]; + return ids; + } else { + return [NSSet set]; + } +} + +- (NSSet *)knownCompleteChildrenAtPath:(FPath *)path { + NSAssert(![self isQueryComplete:[FQuerySpec defaultQueryAtPath:path]], @"Path is fully complete"); + + NSMutableSet *completeChildren = [NSMutableSet set]; + // First, get complete children from any queries at this location. + NSSet *queryIds = [self filteredQueryIdsAtPath:path]; + [queryIds enumerateObjectsUsingBlock:^(NSNumber *queryId, BOOL *stop) { + NSSet *keys = [self.storageEngine trackedQueryKeysForQuery:[queryId unsignedIntegerValue]]; + [completeChildren unionSet:keys]; + }]; + + // Second, get any complete default queries immediately below us. + [[[self.trackedQueryTree subtreeAtPath:path] children] enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + if ([childTree.value[[FQueryParams defaultInstance]] isComplete]) { + [completeChildren addObject:childKey]; + } + }]; + + return completeChildren; +} + +- (void)verifyCache { + NSArray *storedTrackedQueries = [self.storageEngine loadTrackedQueries]; + NSMutableArray *trackedQueries = [NSMutableArray array]; + + [self.trackedQueryTree forEach:^(FPath *path, NSDictionary *queryDict) { + [trackedQueries addObjectsFromArray:queryDict.allValues]; + }]; + NSComparator comparator = ^NSComparisonResult(FTrackedQuery *q1, FTrackedQuery *q2) { + if (q1.queryId < q2.queryId) { + return NSOrderedAscending; + } else if (q1.queryId > q2.queryId) { + return NSOrderedDescending; + } else { + return NSOrderedSame; + } + }; + [trackedQueries sortUsingComparator:comparator]; + storedTrackedQueries = [storedTrackedQueries sortedArrayUsingComparator:comparator]; + + if (![trackedQueries isEqualToArray:storedTrackedQueries]) { + [NSException raise:NSInternalInconsistencyException format:@"Tracked queries and queries stored on disk don't match"]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataEventType.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataEventType.h new file mode 100644 index 0000000..916ce32 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataEventType.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Firebase_FIRDataEventType_h +#define Firebase_FIRDataEventType_h + +#import + +/** + * This enum is the set of events that you can observe at a Firebase Database location. + */ +typedef NS_ENUM(NSInteger, FIRDataEventType) { + /// A new child node is added to a location. + FIRDataEventTypeChildAdded, + /// A child node is removed from a location. + FIRDataEventTypeChildRemoved, + /// A child node at a location changes. + FIRDataEventTypeChildChanged, + /// A child node moves relative to the other child nodes at a location. + FIRDataEventTypeChildMoved, + /// Any data changes at a location or, recursively, at any child node. + FIRDataEventTypeValue +} NS_SWIFT_NAME(DataEventType); + +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataSnapshot.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataSnapshot.h new file mode 100644 index 0000000..02a1e6a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDataSnapshot.h @@ -0,0 +1,147 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FIRDatabaseReference; + +/** + * A FIRDataSnapshot contains data from a Firebase Database location. Any time you read + * Firebase data, you receive the data as a FIRDataSnapshot. + * + * FIRDataSnapshots are passed to the blocks you attach with observeEventType:withBlock: or observeSingleEvent:withBlock:. + * They are efficiently-generated immutable copies of the data at a Firebase Database location. + * They can't be modified and will never change. To modify data at a location, + * use a FIRDatabaseReference (e.g. with setValue:). + */ +NS_SWIFT_NAME(DataSnapshot) +@interface FIRDataSnapshot : NSObject + + +#pragma mark - Navigating and inspecting a snapshot + +/** + * Gets a FIRDataSnapshot for the location at the specified relative path. + * The relative path can either be a simple child key (e.g. 'fred') + * or a deeper slash-separated path (e.g. 'fred/name/first'). If the child + * location has no data, an empty FIRDataSnapshot is returned. + * + * @param childPathString A relative path to the location of child data. + * @return The FIRDataSnapshot for the child location. + */ +- (FIRDataSnapshot *)childSnapshotForPath:(NSString *)childPathString; + + +/** + * Return YES if the specified child exists. + * + * @param childPathString A relative path to the location of a potential child. + * @return YES if data exists at the specified childPathString, else NO. + */ +- (BOOL) hasChild:(NSString *)childPathString; + + +/** + * Return YES if the DataSnapshot has any children. + * + * @return YES if this snapshot has any children, else NO. + */ +- (BOOL) hasChildren; + + +/** + * Return YES if the DataSnapshot contains a non-null value. + * + * @return YES if this snapshot contains a non-null value, else NO. + */ +- (BOOL) exists; + + +#pragma mark - Data export + +/** + * Returns the raw value at this location, coupled with any metadata, such as priority. + * + * Priorities, where they exist, are accessible under the ".priority" key in instances of NSDictionary. + * For leaf locations with priorities, the value will be under the ".value" key. + */ +- (id __nullable) valueInExportFormat; + + +#pragma mark - Properties + +/** + * Returns the contents of this data snapshot as native types. + * + * Data types returned: + * + NSDictionary + * + NSArray + * + NSNumber (also includes booleans) + * + NSString + * + * @return The data as a native object. + */ +@property (strong, readonly, nonatomic, nullable) id value; + + +/** + * Gets the number of children for this DataSnapshot. + * + * @return An integer indicating the number of children. + */ +@property (readonly, nonatomic) NSUInteger childrenCount; + + +/** + * Gets a FIRDatabaseReference for the location that this data came from. + * + * @return A FIRDatabaseReference instance for the location of this data. + */ +@property (nonatomic, readonly, strong) FIRDatabaseReference * ref; + + +/** + * The key of the location that generated this FIRDataSnapshot. + * + * @return An NSString containing the key for the location of this FIRDataSnapshot. + */ +@property (strong, readonly, nonatomic) NSString* key; + + +/** + * An iterator for snapshots of the child nodes in this snapshot. + * You can use the native for..in syntax: + * + * for (FIRDataSnapshot* child in snapshot.children) { + * ... + * } + * + * @return An NSEnumerator of the children. + */ +@property (strong, readonly, nonatomic) NSEnumerator* children; + +/** + * The priority of the data in this FIRDataSnapshot. + * + * @return The priority as a string, or nil if no priority was set. + */ +@property (strong, readonly, nonatomic, nullable) id priority; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabase.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabase.h new file mode 100644 index 0000000..15c8700 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabase.h @@ -0,0 +1,168 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDatabaseReference.h" + +@class FIRApp; + +NS_ASSUME_NONNULL_BEGIN + +/** + * The entry point for accessing a Firebase Database. You can get an instance by calling + * [FIRDatabase database]. To access a location in the database and read or write data, + * use [FIRDatabase reference]. + */ +NS_SWIFT_NAME(Database) +@interface FIRDatabase : NSObject + +/** + * The NSObject initializer that has been marked as unavailable. Use the `database` + * method instead + * + * @return An instancetype instance +*/ +- (instancetype) init __attribute__((unavailable("use the database method instead"))); + +/** + * Gets the instance of FIRDatabase for the default FIRApp. + * + * @return A FIRDatabase instance. + */ ++ (FIRDatabase *) database NS_SWIFT_NAME(database()); + +/** + * Gets a FirebaseDatabase instance for the specified URL. + * + * @param url The URL to the Firebase Database instance you want to access. + * @return A FIRDatabase instance. + */ ++ (FIRDatabase *)databaseWithURL:(NSString *)url NS_SWIFT_NAME(database(url:)); + +/** + * Gets a FirebaseDatabase instance for the specified URL, using the specified + * FirebaseApp. + * + * @param app The FIRApp to get a FIRDatabase for. + * @param url The URL to the Firebase Database instance you want to access. + * @return A FIRDatabase instance. + */ +// clang-format off ++ (FIRDatabase *)databaseForApp:(FIRApp *)app + URL:(NSString *)url NS_SWIFT_NAME(database(app:url:)); +// clang-format on + +/** + * Gets an instance of FIRDatabase for a specific FIRApp. + * + * @param app The FIRApp to get a FIRDatabase for. + * @return A FIRDatabase instance. + */ ++ (FIRDatabase *) databaseForApp:(FIRApp *)app NS_SWIFT_NAME(database(app:)); + +/** The FIRApp instance to which this FIRDatabase belongs. */ +@property (weak, readonly, nonatomic) FIRApp *app; + +/** + * Gets a FIRDatabaseReference for the root of your Firebase Database. + */ +- (FIRDatabaseReference *) reference; + +/** + * Gets a FIRDatabaseReference for the provided path. + * + * @param path Path to a location in your Firebase Database. + * @return A FIRDatabaseReference pointing to the specified path. + */ +- (FIRDatabaseReference *) referenceWithPath:(NSString *)path; + +/** + * Gets a FIRDatabaseReference for the provided URL. The URL must be a URL to a path + * within this Firebase Database. To create a FIRDatabaseReference to a different database, + * create a FIRApp} with a FIROptions object configured with the appropriate database URL. + * + * @param databaseUrl A URL to a path within your database. + * @return A FIRDatabaseReference for the provided URL. +*/ +- (FIRDatabaseReference *) referenceFromURL:(NSString *)databaseUrl; + +/** + * The Firebase Database client automatically queues writes and sends them to the server at the earliest opportunity, + * depending on network connectivity. In some cases (e.g. offline usage) there may be a large number of writes + * waiting to be sent. Calling this method will purge all outstanding writes so they are abandoned. + * + * All writes will be purged, including transactions and onDisconnect writes. The writes will + * be rolled back locally, perhaps triggering events for affected event listeners, and the client will not + * (re-)send them to the Firebase Database backend. + */ +- (void)purgeOutstandingWrites; + +/** + * Shuts down our connection to the Firebase Database backend until goOnline is called. + */ +- (void)goOffline; + +/** + * Resumes our connection to the Firebase Database backend after a previous goOffline call. + */ +- (void)goOnline; + +/** + * The Firebase Database client will cache synchronized data and keep track of all writes you've + * initiated while your application is running. It seamlessly handles intermittent network + * connections and re-sends write operations when the network connection is restored. + * + * However by default your write operations and cached data are only stored in-memory and will + * be lost when your app restarts. By setting this value to `YES`, the data will be persisted + * to on-device (disk) storage and will thus be available again when the app is restarted + * (even when there is no network connectivity at that time). Note that this property must be + * set before creating your first Database reference and only needs to be called once per + * application. + * + */ +@property (nonatomic) BOOL persistenceEnabled NS_SWIFT_NAME(isPersistenceEnabled); + +/** + * By default the Firebase Database client will use up to 10MB of disk space to cache data. If the cache grows beyond + * this size, the client will start removing data that hasn't been recently used. If you find that your application + * caches too little or too much data, call this method to change the cache size. This property must be set before + * creating your first FIRDatabaseReference and only needs to be called once per application. + * + * Note that the specified cache size is only an approximation and the size on disk may temporarily exceed it + * at times. Cache sizes smaller than 1 MB or greater than 100 MB are not supported. + */ +@property (nonatomic) NSUInteger persistenceCacheSizeBytes; + +/** + * Sets the dispatch queue on which all events are raised. The default queue is the main queue. + * + * Note that this must be set before creating your first Database reference. + */ +@property (nonatomic, strong) dispatch_queue_t callbackQueue; + +/** + * Enables verbose diagnostic logging. + * + * @param enabled YES to enable logging, NO to disable. + */ ++ (void) setLoggingEnabled:(BOOL)enabled; + +/** Retrieve the Firebase Database SDK version. */ ++ (NSString *) sdkVersion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseQuery.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseQuery.h new file mode 100644 index 0000000..ef56643 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseQuery.h @@ -0,0 +1,314 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDataEventType.h" +#import "FIRDataSnapshot.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * A FIRDatabaseHandle is used to identify listeners of Firebase Database events. These handles + * are returned by observeEventType: and and can later be passed to removeObserverWithHandle: to + * stop receiving updates. + */ +typedef NSUInteger FIRDatabaseHandle NS_SWIFT_NAME(DatabaseHandle); + +/** + * A FIRDatabaseQuery instance represents a query over the data at a particular location. + * + * You create one by calling one of the query methods (queryOrderedByChild:, queryStartingAtValue:, etc.) + * on a FIRDatabaseReference. The query methods can be chained to further specify the data you are interested in + * observing + */ +NS_SWIFT_NAME(DatabaseQuery) +@interface FIRDatabaseQuery : NSObject + + +#pragma mark - Attach observers to read data + +/** + * observeEventType:withBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; + + +/** + * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot + * and the previous child's key. + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; + + +/** + * observeEventType:withBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. + * + * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. + * @param cancelBlock The block that should be called if this client no longer has permission to receive these events + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot + * and the previous child's key. + * @param cancelBlock The block that should be called if this client no longer has permission to receive these events + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. + * + * The cancelBlock will be called if you do not have permission to read data at this location. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. + * @param cancelBlock The block that will be called if you don't have permission to access this data + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * The cancelBlock will be called if you do not have permission to read data at this location. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. + * @param cancelBlock The block that will be called if you don't have permission to access this data + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +#pragma mark - Detaching observers + +/** + * Detach a block previously attached with observeEventType:withBlock:. + * + * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. + */ +- (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; + + +/** + * Detach all blocks previously attached to this Firebase Database location with observeEventType:withBlock: + */ +- (void) removeAllObservers; + +/** + * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and + * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept + * synced, it will not be evicted from the persistent disk cache. + * + * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. +*/ + - (void) keepSynced:(BOOL)keepSynced; + + +#pragma mark - Querying and limiting + +/** +* queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. +* The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. +* +* @param limit The upper bound, inclusive, for the number of child nodes to receive events for +* @return A FIRDatabaseQuery instance, limited to at most limit child nodes. +*/ +- (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; + + +/** +* queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. +* The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. +* +* @param limit The upper bound, inclusive, for the number of child nodes to receive events for +* @return A FIRDatabaseQuery instance, limited to at most limit child nodes. +*/ +- (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; + +/** + * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of + * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, + * queryEndingAtValue:, or queryEqualToValue:. + * + * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. +*/ +- (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; + +/** + * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. + * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, + * or queryEqualToValue:. + * + * @return A FIRDatabaseQuery instance, ordered by child keys. + */ +- (FIRDatabaseQuery *) queryOrderedByKey; + +/** + * queryOrderedByValue: is used to generate a reference to a view of the data that's been sorted by child value. + * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, + * or queryEqualToValue:. + * + * @return A FIRDatabaseQuery instance, ordered by child value. + */ +- (FIRDatabaseQuery *) queryOrderedByValue; + +/** + * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child + * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, + * or queryEqualToValue:. + * + * @return A FIRDatabaseQuery instance, ordered by child priorities. + */ +- (FIRDatabaseQuery *) queryOrderedByPriority; + +/** + * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value + * greater than or equal to startValue. + * + * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue + */ +- (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; + +/** + * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value + * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. This is most + * useful when implementing pagination in a case where multiple nodes can match the startValue. + * + * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue + * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue + */ +- (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; + +/** + * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value + * less than or equal to endValue. + * + * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue + */ +- (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; + +/** + * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value + * less than endValue, or equal to endValue and with a key less than or equal to childKey. This is most useful when + * implementing pagination in a case where multiple nodes can match the endValue. + * + * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue + * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue + */ +- (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; + +/** + * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal + * to the supplied argument. + * + * @param value The value that the data returned by this FIRDatabaseQuery will have + * @return A FIRDatabaseQuery instance, limited to data with the supplied value. + */ +- (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; + +/** + * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value + * equal to the supplied argument and with their key equal to childKey. There will be at most one node that matches + * because child keys are unique. + * + * @param value The value that the data returned by this FIRDatabaseQuery will have + * @param childKey The name of nodes with the right value + * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. + */ +- (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; + + +#pragma mark - Properties + +/** +* Gets a FIRDatabaseReference for the location of this query. +* +* @return A FIRDatabaseReference for the location of this query. +*/ +@property (nonatomic, readonly, strong) FIRDatabaseReference * ref; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseReference.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseReference.h new file mode 100644 index 0000000..b96585e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRDatabaseReference.h @@ -0,0 +1,718 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDatabaseQuery.h" +#import "FIRDatabase.h" +#import "FIRDataSnapshot.h" +#import "FIRMutableData.h" +#import "FIRTransactionResult.h" +#import "FIRServerValue.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRDatabase; + +/** + * A FIRDatabaseReference represents a particular location in your Firebase Database + * and can be used for reading or writing data to that Firebase Database location. + * + * This class is the starting point for all Firebase Database operations. After you've + * obtained your first FIRDatabaseReference via [FIRDatabase reference], you can use it + * to read data (ie. observeEventType:withBlock:), write data (ie. setValue:), and to + * create new FIRDatabaseReferences (ie. child:). + */ +NS_SWIFT_NAME(DatabaseReference) +@interface FIRDatabaseReference : FIRDatabaseQuery + + +#pragma mark - Getting references to children locations + +/** + * Gets a FIRDatabaseReference for the location at the specified relative path. + * The relative path can either be a simple child key (e.g. 'fred') or a + * deeper slash-separated path (e.g. 'fred/name/first'). + * + * @param pathString A relative path from this location to the desired child location. + * @return A FIRDatabaseReference for the specified relative path. + */ +- (FIRDatabaseReference *)child:(NSString *)pathString; + +/** + * childByAppendingPath: is deprecated, use child: instead. + */ +- (FIRDatabaseReference *)childByAppendingPath:(NSString *)pathString __deprecated_msg("use child: instead"); + +/** + * childByAutoId generates a new child location using a unique key and returns a + * FIRDatabaseReference to it. This is useful when the children of a Firebase Database + * location represent a list of items. + * + * The unique key generated by childByAutoId: is prefixed with a client-generated + * timestamp so that the resulting list will be chronologically-sorted. + * + * @return A FIRDatabaseReference for the generated location. + */ +- (FIRDatabaseReference *) childByAutoId; + + +#pragma mark - Writing data + +/** Write data to this Firebase Database location. + +This will overwrite any data at this location and all child locations. + +Data types that can be set are: + +- NSString -- @"Hello World" +- NSNumber (also includes boolean) -- @YES, @43, @4.333 +- NSDictionary -- @{@"key": @"value", @"nested": @{@"another": @"value"} } +- NSArray + +The effect of the write will be visible immediately and the corresponding +events will be triggered. Synchronization of the data to the Firebase Database +servers will also be started. + +Passing null for the new value is equivalent to calling remove:; +all data at this location or any child location will be deleted. + +Note that setValue: will remove any priority stored at this location, so if priority +is meant to be preserved, you should use setValue:andPriority: instead. + +@param value The value to be written. + */ +- (void) setValue:(nullable id)value; + + +/** + * The same as setValue: with a block that gets triggered after the write operation has + * been committed to the Firebase Database servers. + * + * @param value The value to be written. + * @param block The block to be called after the write has been committed to the Firebase Database servers. + */ +- (void) setValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +/** + * The same as setValue: with an additional priority to be attached to the data being written. + * Priorities are used to order items. + * + * @param value The value to be written. + * @param priority The priority to be attached to that data. + */ +- (void) setValue:(nullable id)value andPriority:(nullable id)priority; + + +/** + * The same as setValue:andPriority: with a block that gets triggered after the write operation has + * been committed to the Firebase Database servers. + * + * @param value The value to be written. + * @param priority The priority to be attached to that data. + * @param block The block to be called after the write has been committed to the Firebase Database servers. + */ +- (void) setValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +/** + * Remove the data at this Firebase Database location. Any data at child locations will also be deleted. + * + * The effect of the delete will be visible immediately and the corresponding events + * will be triggered. Synchronization of the delete to the Firebase Database servers will + * also be started. + * + * remove: is equivalent to calling setValue:nil + */ +- (void) removeValue; + + +/** + * The same as remove: with a block that gets triggered after the remove operation has + * been committed to the Firebase Database servers. + * + * @param block The block to be called after the remove has been committed to the Firebase Database servers. + */ +- (void) removeValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + +/** + * Sets a priority for the data at this Firebase Database location. + * Priorities can be used to provide a custom ordering for the children at a location + * (if no priorities are specified, the children are ordered by key). + * + * You cannot set a priority on an empty location. For this reason + * setValue:andPriority: should be used when setting initial data with a specific priority + * and setPriority: should be used when updating the priority of existing data. + * + * Children are sorted based on this priority using the following rules: + * + * Children with no priority come first. + * Children with a number as their priority come next. They are sorted numerically by priority (small to large). + * Children with a string as their priority come last. They are sorted lexicographically by priority. + * Whenever two children have the same priority (including no priority), they are sorted by key. Numeric + * keys come first (sorted numerically), followed by the remaining keys (sorted lexicographically). + * + * Note that priorities are parsed and ordered as IEEE 754 double-precision floating-point numbers. + * Keys are always stored as strings and are treated as numbers only when they can be parsed as a + * 32-bit integer + * + * @param priority The priority to set at the specified location. + */ +- (void) setPriority:(nullable id)priority; + + +/** + * The same as setPriority: with a block that is called once the priority has + * been committed to the Firebase Database servers. + * + * @param priority The priority to set at the specified location. + * @param block The block that is triggered after the priority has been written on the servers. + */ +- (void) setPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + +/** + * Updates the values at the specified paths in the dictionary without overwriting other + * keys at this location. + * + * @param values A dictionary of the keys to change and their new values + */ +- (void) updateChildValues:(NSDictionary *)values; + +/** + * The same as update: with a block that is called once the update has been committed to the + * Firebase Database servers + * + * @param values A dictionary of the keys to change and their new values + * @param block The block that is triggered after the update has been written on the Firebase Database servers + */ +- (void) updateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +#pragma mark - Attaching observers to read data + +/** + * observeEventType:withBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. + * + * Use removeObserverWithHandle: to stop receiving updates. + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; + + +/** + * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot + * and the previous child's key. + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; + + +/** + * observeEventType:withBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. + * + * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. + * @param cancelBlock The block that should be called if this client no longer has permission to receive these events + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. + * This is the primary way to read data from the Firebase Database. Your block will be triggered + * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. + * + * Use removeObserverWithHandle: to stop receiving updates. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot + * and the previous child's key. + * @param cancelBlock The block that should be called if this client no longer has permission to receive these events + * @return A handle used to unregister this block later using removeObserverWithHandle: + */ +- (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. + * + * The cancelBlock will be called if you do not have permission to read data at this location. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. + * @param cancelBlock The block that will be called if you don't have permission to access this data + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + + +/** + * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and + * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. + * + * The cancelBlock will be called if you do not have permission to read data at this location. + * + * @param eventType The type of event to listen for. + * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. + * @param cancelBlock The block that will be called if you don't have permission to access this data + */ +- (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; + +#pragma mark - Detaching observers + +/** + * Detach a block previously attached with observeEventType:withBlock:. + * + * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. + */ +- (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; + +/** + * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and + * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept + * synced, it will not be evicted from the persistent disk cache. + * + * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. + */ +- (void) keepSynced:(BOOL)keepSynced; + + +/** + * Removes all observers at the current reference, but does not remove any observers at child references. + * removeAllObservers must be called again for each child reference where a listener was established to remove the observers. + */ +- (void) removeAllObservers; + +#pragma mark - Querying and limiting + + +/** + * queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. + * + * @param limit The upper bound, inclusive, for the number of child nodes to receive events for + * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. + */ +- (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; + + +/** + * queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. + * + * @param limit The upper bound, inclusive, for the number of child nodes to receive events for + * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. + */ +- (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; + +/** + * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of + * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, + * queryEndingAtValue:, or queryEqualToValue:. + * + * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. + */ +- (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; + +/** + * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. + * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, + * or queryEqualToValue:. + * + * @return A FIRDatabaseQuery instance, ordered by child keys. + */ +- (FIRDatabaseQuery *) queryOrderedByKey; + +/** + * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child + * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, + * or queryEqualToValue:. + * + * @return A FIRDatabaseQuery instance, ordered by child priorities. + */ +- (FIRDatabaseQuery *) queryOrderedByPriority; + +/** + * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value + * greater than or equal to startValue. + * + * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue + */ +- (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; + +/** + * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value + * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. + * + * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue + * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue + */ +- (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; + +/** + * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value + * less than or equal to endValue. + * + * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue + */ +- (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; + +/** + * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value + * less than endValue, or equal to endValue and with a key less than or equal to childKey. + * + * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery + * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue + * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue + */ +- (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; + +/** + * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal + * to the supplied argument. + * + * @param value The value that the data returned by this FIRDatabaseQuery will have + * @return A FIRDatabaseQuery instance, limited to data with the supplied value. + */ +- (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; + +/** + * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. + * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value + * equal to the supplied argument with a key equal to childKey. There will be at most one node that matches because + * child keys are unique. + * + * @param value The value that the data returned by this FIRDatabaseQuery will have + * @param childKey The key of nodes with the right value + * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. + */ +- (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; + +#pragma mark - Managing presence + +/** + * Ensure the data at this location is set to the specified value when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * onDisconnectSetValue: is especially useful for implementing "presence" systems, + * where a value should be changed or cleared when a user disconnects + * so that he appears "offline" to other users. + * + * @param value The value to be set after the connection is lost. + */ +- (void) onDisconnectSetValue:(nullable id)value; + + +/** + * Ensure the data at this location is set to the specified value when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers + * + * @param value The value to be set after the connection is lost. + * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers + */ +- (void) onDisconnectSetValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +/** + * Ensure the data at this location is set to the specified value and priority when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * @param value The value to be set after the connection is lost. + * @param priority The priority to be set after the connection is lost. + */ +- (void) onDisconnectSetValue:(nullable id)value andPriority:(id)priority; + + +/** + * Ensure the data at this location is set to the specified value and priority when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers + * + * @param value The value to be set after the connection is lost. + * @param priority The priority to be set after the connection is lost. + * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers + */ +- (void) onDisconnectSetValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +/** + * Ensure the data at this location is removed when + * the client is disconnected (due to closing the app, navigating + * to a new page, or network issues). + * + * onDisconnectRemoveValue is especially useful for implementing "presence" systems. + */ +- (void) onDisconnectRemoveValue; + + +/** + * Ensure the data at this location is removed when + * the client is disconnected (due to closing the app, navigating + * to a new page, or network issues). + * + * onDisconnectRemoveValueWithCompletionBlock: is especially useful for implementing "presence" systems. + * + * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers + */ +- (void) onDisconnectRemoveValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + + +/** + * Ensure the data has the specified child values updated when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * + * @param values A dictionary of child node keys and the values to set them to after the connection is lost. + */ +- (void) onDisconnectUpdateChildValues:(NSDictionary *)values; + + +/** + * Ensure the data has the specified child values updated when + * the client is disconnected (due to closing the browser, navigating + * to a new page, or network issues). + * + * + * @param values A dictionary of child node keys and the values to set them to after the connection is lost. + * @param block A block that will be called once the operation has been queued up on the Firebase Database servers + */ +- (void) onDisconnectUpdateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +/** + * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, + * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the + * connection is lost, call cancelDisconnectOperations: + */ +- (void) cancelDisconnectOperations; + + +/** + * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, + * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the + * connection is lost, call cancelDisconnectOperations: + * + * @param block A block that will be triggered once the Firebase Database servers have acknowledged the cancel request. + */ +- (void) cancelDisconnectOperationsWithCompletionBlock:(nullable void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; + + +#pragma mark - Manual Connection Management + +/** + * Manually disconnect the Firebase Database client from the server and disable automatic reconnection. + * + * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, + * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) + * and goOnline( ) methods may be used to manually control the client connection in cases where + * a persistent connection is undesirable. + * + * While offline, the Firebase Database client will no longer receive data updates from the server. However, + * all database operations performed locally will continue to immediately fire events, allowing + * your application to continue behaving normally. Additionally, each operation performed locally + * will automatically be queued and retried upon reconnection to the Firebase Database server. + * + * To reconnect to the Firebase Database server and begin receiving remote events, see goOnline( ). + * Once the connection is reestablished, the Firebase Database client will transmit the appropriate data + * and fire the appropriate events so that your client "catches up" automatically. + * + * Note: Invoking this method will impact all Firebase Database connections. + */ ++ (void) goOffline; + +/** + * Manually reestablish a connection to the Firebase Database server and enable automatic reconnection. + * + * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, + * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) + * and goOnline( ) methods may be used to manually control the client connection in cases where + * a persistent connection is undesirable. + * + * This method should be used after invoking goOffline( ) to disable the active connection. + * Once reconnected, the Firebase Database client will automatically transmit the proper data and fire + * the appropriate events so that your client "catches up" automatically. + * + * To disconnect from the Firebase Database server, see goOffline( ). + * + * Note: Invoking this method will impact all Firebase Database connections. + */ ++ (void) goOnline; + + +#pragma mark - Transactions + +/** + * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData + * instance that contains the current data at this location. Your block should update this data to the value you + * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. + * + * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run + * again with the latest data from the server. + * + * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. + * + * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult + */ +- (void) runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block; + + +/** + * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData + * instance that contains the current data at this location. Your block should update this data to the value you + * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. + * + * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run + * again with the latest data from the server. + * + * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. + * + * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult + * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. + */ +- (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock; + + + +/** + * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData + * instance that contains the current data at this location. Your block should update this data to the value you + * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. + * + * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run + * again with the latest data from the server. + * + * When your block is run, you may decide to abort the transaction by return [FIRTransactionResult abort]. + * + * Since your block may be run multiple times, this client could see several immediate states that don't exist on the server. You can suppress those immediate states until the server confirms the final state of the transaction. + * + * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult + * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. + * @param localEvents Set this to NO to suppress events raised for intermediate states, and only get events based on the final state of the transaction. + */ +- (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(nullable void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock withLocalEvents:(BOOL)localEvents; + + +#pragma mark - Retrieving String Representation + +/** + * Gets the absolute URL of this Firebase Database location. + * + * @return The absolute URL of the referenced Firebase Database location. + */ +- (NSString *) description; + +#pragma mark - Properties + +/** + * Gets a FIRDatabaseReference for the parent location. + * If this instance refers to the root of your Firebase Database, it has no parent, + * and therefore parent( ) will return null. + * + * @return A FIRDatabaseReference for the parent location. + */ +@property (strong, readonly, nonatomic, nullable) FIRDatabaseReference * parent; + + +/** + * Gets a FIRDatabaseReference for the root location + * + * @return A new FIRDatabaseReference to root location. + */ +@property (strong, readonly, nonatomic) FIRDatabaseReference * root; + + +/** + * Gets the last token in a Firebase Database location (e.g. 'fred' in https://SampleChat.firebaseIO-demo.com/users/fred) + * + * @return The key of the location this reference points to. + */ +@property (strong, readonly, nonatomic, nullable) NSString* key; + +/** + * Gets the URL for the Firebase Database location referenced by this FIRDatabaseReference. + * + * @return The url of the location this reference points to. + */ +@property (strong, readonly, nonatomic) NSString* URL; + +/** + * Gets the FIRDatabase instance associated with this reference. + * + * @return The FIRDatabase object for this reference. + */ +@property (strong, readonly, nonatomic) FIRDatabase *database; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRMutableData.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRMutableData.h new file mode 100644 index 0000000..7445d71 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRMutableData.h @@ -0,0 +1,129 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * A FIRMutableData instance is populated with data from a Firebase Database location. + * When you are using runTransactionBlock:, you will be given an instance containing the current + * data at that location. Your block will be responsible for updating that instance to the data + * you wish to save at that location, and then returning using [FIRTransactionResult successWithValue:]. + * + * To modify the data, set its value property to any of the native types support by Firebase Database: + * + * + NSNumber (includes BOOL) + * + NSDictionary + * + NSArray + * + NSString + * + nil / NSNull to remove the data + * + * Note that changes made to a child FIRMutableData instance will be visible to the parent. + */ +NS_SWIFT_NAME(MutableData) +@interface FIRMutableData : NSObject + + +#pragma mark - Inspecting and navigating the data + + +/** + * Returns boolean indicating whether this mutable data has children. + * + * @return YES if this data contains child nodes. + */ +- (BOOL) hasChildren; + + +/** + * Indicates whether this mutable data has a child at the given path. + * + * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' + * @return YES if this data contains a child at the specified relative path + */ +- (BOOL) hasChildAtPath:(NSString *)path; + + +/** + * Used to obtain a FIRMutableData instance that encapsulates the data at the given relative path. + * Note that changes made to the child will be visible to the parent. + * + * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' + * @return A FIRMutableData instance containing the data at the given path + */ +- (FIRMutableData *)childDataByAppendingPath:(NSString *)path; + + +#pragma mark - Properties + + +/** + * To modify the data contained by this instance of FIRMutableData, set this to any of the native types supported by Firebase Database: + * + * + NSNumber (includes BOOL) + * + NSDictionary + * + NSArray + * + NSString + * + nil / NSNull to remove the data + * + * Note that setting this value will override the priority at this location. + * + * @return The current data at this location as a native object + */ +@property (strong, nonatomic, nullable) id value; + + +/** + * Set this property to update the priority of the data at this location. Can be set to the following types: + * + * + NSNumber + * + NSString + * + nil / NSNull to remove the priority + * + * @return The priority of the data at this location + */ +@property (strong, nonatomic, nullable) id priority; + + +/** + * @return The number of child nodes at this location + */ +@property (readonly, nonatomic) NSUInteger childrenCount; + + +/** + * Used to iterate over the children at this location. You can use the native for .. in syntax: + * + * for (FIRMutableData* child in data.children) { + * ... + * } + * + * Note that this enumerator operates on an immutable copy of the child list. So, you can modify the instance + * during iteration, but the new additions will not be visible until you get a new enumerator. + */ +@property (readonly, nonatomic, strong) NSEnumerator* children; + + +/** + * @return The key name of this node, or nil if it is the top-most location + */ +@property (readonly, nonatomic, strong, nullable) NSString* key; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRServerValue.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRServerValue.h new file mode 100644 index 0000000..365590c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRServerValue.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +NS_ASSUME_NONNULL_BEGIN + +/** + * Placeholder values you may write into Firebase Database as a value or priority + * that will automatically be populated by the Firebase Database server. + */ +NS_SWIFT_NAME(ServerValue) +@interface FIRServerValue : NSObject + +/** + * Placeholder value for the number of milliseconds since the Unix epoch + */ ++ (NSDictionary *) timestamp; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRTransactionResult.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRTransactionResult.h new file mode 100644 index 0000000..d356c5c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FIRTransactionResult.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRMutableData.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Used for runTransactionBlock:. An FIRTransactionResult instance is a container for the results of the transaction. + */ +NS_SWIFT_NAME(TransactionResult) +@interface FIRTransactionResult : NSObject + +/** + * Used for runTransactionBlock:. Indicates that the new value should be saved at this location + * + * @param value A FIRMutableData instance containing the new value to be set + * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: + */ ++ (FIRTransactionResult *)successWithValue:(FIRMutableData *)value; + + +/** + * Used for runTransactionBlock:. Indicates that the current transaction should no longer proceed. + * + * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: + */ ++ (FIRTransactionResult *) abort; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FirebaseDatabase.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FirebaseDatabase.h new file mode 100644 index 0000000..e52f5d6 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Public/FirebaseDatabase.h @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FirebaseDatabase_h +#define FirebaseDatabase_h + +#import "FIRDatabase.h" +#import "FIRDatabaseQuery.h" +#import "FIRDatabaseReference.h" +#import "FIRDataEventType.h" +#import "FIRDataSnapshot.h" +#import "FIRMutableData.h" +#import "FIRServerValue.h" +#import "FIRTransactionResult.h" + +#endif /* FirebaseDatabase_h */ diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.h new file mode 100644 index 0000000..ed4879a --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.h @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FWebSocketConnection.h" +#import "FTypedefs.h" + +@protocol FConnectionDelegate; + +@interface FConnection : NSObject + +@property (nonatomic, weak) id delegate; + +- (id)initWith:(FRepoInfo *)aRepoInfo andDispatchQueue:(dispatch_queue_t)queue lastSessionID:(NSString *)lastSessionID; + +- (void)open; +- (void)close; +- (void)sendRequest:(NSDictionary *)dataMsg sensitive:(BOOL)sensitive; + +// FWebSocketDelegate delegate methods +- (void)onMessage:(FWebSocketConnection *)fwebSocket withMessage:(NSDictionary *)message; +- (void)onDisconnect:(FWebSocketConnection *)fwebSocket wasEverConnected:(BOOL)everConnected; + +@end + +typedef enum { + DISCONNECT_REASON_SERVER_RESET = 0, + DISCONNECT_REASON_OTHER = 1 +} FDisconnectReason; + +@protocol FConnectionDelegate + +- (void)onReady:(FConnection *)fconnection atTime:(NSNumber *)timestamp sessionID:(NSString *)sessionID; +- (void)onDataMessage:(FConnection *)fconnection withMessage:(NSDictionary *)message; +- (void)onDisconnect:(FConnection *)fconnection withReason:(FDisconnectReason)reason; +- (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason; + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.m new file mode 100644 index 0000000..08014f6 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FConnection.m @@ -0,0 +1,212 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FConnection.h" +#import "FConstants.h" + +typedef enum { + REALTIME_STATE_CONNECTING = 0, + REALTIME_STATE_CONNECTED = 1, + REALTIME_STATE_DISCONNECTED = 2, +} FConnectionState; + +@interface FConnection () { + FConnectionState state; +} + +@property (nonatomic, strong) FWebSocketConnection* conn; +@property (nonatomic, strong) FRepoInfo* repoInfo; + +@end + +#pragma mark - +#pragma mark FConnection implementation + +@implementation FConnection + +@synthesize delegate; +@synthesize conn; +@synthesize repoInfo; + +#pragma mark - +#pragma mark Initializers + +- (id)initWith:(FRepoInfo *)aRepoInfo andDispatchQueue:(dispatch_queue_t)queue lastSessionID:(NSString *)lastSessionID{ + self = [super init]; + if (self) { + state = REALTIME_STATE_CONNECTING; + self.repoInfo = aRepoInfo; + self.conn = [[FWebSocketConnection alloc] initWith:self.repoInfo andQueue:queue lastSessionID:lastSessionID]; + self.conn.delegate = self; + } + return self; +} + +#pragma mark - +#pragma mark Public method implementation + +- (void)open { + FFLog(@"I-RDB082001", @"Calling open in FConnection"); + [self.conn open]; +} + +- (void) closeWithReason:(FDisconnectReason)reason { + if (state != REALTIME_STATE_DISCONNECTED) { + FFLog(@"I-RDB082002", @"Closing realtime connection."); + state = REALTIME_STATE_DISCONNECTED; + + if (self.conn) { + FFLog(@"I-RDB082003", @"Calling close again."); + [self.conn close]; + self.conn = nil; + } + + [self.delegate onDisconnect:self withReason:reason]; + } +} + +- (void) close { + [self closeWithReason:DISCONNECT_REASON_OTHER]; +} + +- (void) sendRequest:(NSDictionary *)dataMsg sensitive:(BOOL)sensitive { + // since this came from the persistent connection, wrap it in a data message envelope + NSDictionary* msg = @{ + kFWPRequestType: kFWPRequestTypeData, + kFWPRequestDataPayload: dataMsg + }; + [self sendData:msg sensitive:sensitive]; +} + +#pragma mark - +#pragma mark Helpers + + +- (void) sendData:(NSDictionary *)data sensitive:(BOOL)sensitive { + if (state != REALTIME_STATE_CONNECTED) { + @throw [[NSException alloc] initWithName:@"InvalidConnectionState" reason:@"Tried to send data on an unconnected FConnection" userInfo:nil]; + } else { + if (sensitive) { + FFLog(@"I-RDB082004", @"Sending data (contents hidden)"); + } else { + FFLog(@"I-RDB082005", @"Sending: %@", data); + } + [self.conn send:data]; + } +} + +#pragma mark - +#pragma mark FWebSocketConnectinDelegate implementation + +// Corresponds to onConnectionLost in JS +- (void)onDisconnect:(FWebSocketConnection *)fwebSocket wasEverConnected:(BOOL)everConnected { + + self.conn = nil; + if (!everConnected && state == REALTIME_STATE_CONNECTING) { + FFLog(@"I-RDB082006", @"Realtime connection failed."); + + // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away + [self.repoInfo clearInternalHostCache]; + } else if (state == REALTIME_STATE_CONNECTED) { + FFLog(@"I-RDB082007", @"Realtime connection lost."); + } + + [self close]; +} + +// Corresponds to onMessageReceived in JS +- (void)onMessage:(FWebSocketConnection *)fwebSocket withMessage:(NSDictionary *)message { + NSString* rawMessageType = [message objectForKey:kFWPAsyncServerEnvelopeType]; + if(rawMessageType != nil) { + if([rawMessageType isEqualToString:kFWPAsyncServerDataMessage]) { + [self onDataMessage:[message objectForKey:kFWPAsyncServerEnvelopeData]]; + } + else if ([rawMessageType isEqualToString:kFWPAsyncServerControlMessage]) { + [self onControl:[message objectForKey:kFWPAsyncServerEnvelopeData]]; + } + else { + FFLog(@"I-RDB082008", @"Unrecognized server packet type: %@", rawMessageType); + } + } + else { + FFLog(@"I-RDB082009", @"Unrecognized raw server packet received: %@", message); + } +} + +- (void) onDataMessage:(NSDictionary *)message { + // we don't do anything with data messages, just kick them up a level + FFLog(@"I-RDB082010", @"Got data message: %@", message); + [self.delegate onDataMessage:self withMessage:message]; +} + +- (void) onControl:(NSDictionary *)message { + FFLog(@"I-RDB082011", @"Got control message: %@", message); + NSString* type = [message objectForKey:kFWPAsyncServerControlMessageType]; + if([type isEqualToString:kFWPAsyncServerControlMessageShutdown]) { + NSString* reason = [message objectForKey:kFWPAsyncServerControlMessageData]; + [self onConnectionShutdownWithReason:reason]; + } + else if ([type isEqualToString:kFWPAsyncServerControlMessageReset]) { + NSString* host = [message objectForKey:kFWPAsyncServerControlMessageData]; + [self onReset:host]; + } + else if ([type isEqualToString:kFWPAsyncServerHello]) { + NSDictionary* handshakeData = [message objectForKey:kFWPAsyncServerControlMessageData]; + [self onHandshake:handshakeData]; + } + else { + FFLog(@"I-RDB082012", @"Unknown control message returned from server: %@", message); + } +} + +- (void) onConnectionShutdownWithReason:(NSString *)reason { + FFLog(@"I-RDB082013", @"Connection shutdown command received. Shutting down..."); + + [self.delegate onKill:self withReason:reason]; + [self close]; +} + +- (void) onHandshake:(NSDictionary *)handshake { + NSNumber* timestamp = [handshake objectForKey:kFWPAsyncServerHelloTimestamp]; +// NSString* version = [handshake objectForKey:kFWPAsyncServerHelloVersion]; + NSString* host = [handshake objectForKey:kFWPAsyncServerHelloConnectedHost]; + NSString* sessionID = [handshake objectForKey:kFWPAsyncServerHelloSession]; + + self.repoInfo.internalHost = host; + + if (state == REALTIME_STATE_CONNECTING) { + [self.conn start]; + [self onConnection:self.conn readyAtTime:timestamp sessionID:sessionID]; + } +} + +- (void) onConnection:(FWebSocketConnection *)conn readyAtTime:(NSNumber *)timestamp sessionID:(NSString *)sessionID { + FFLog(@"I-RDB082014", @"Realtime connection established"); + state = REALTIME_STATE_CONNECTED; + + [self.delegate onReady:self atTime:timestamp sessionID:sessionID]; +} + +- (void) onReset:(NSString *)host { + FFLog(@"I-RDB082015", @"Got a reset; killing connection to: %@; Updating internalHost to: %@", repoInfo.internalHost, host); + self.repoInfo.internalHost = host; + + // Explicitly close the connection with SERVER_RESET so calling code knows to reconnect immediately. + [self closeWithReason:DISCONNECT_REASON_SERVER_RESET]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.h new file mode 100644 index 0000000..6a14d47 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FSRWebSocket.h" +#import "FUtilities.h" + +@protocol FWebSocketDelegate; + +@interface FWebSocketConnection : NSObject + +@property (nonatomic, weak) id delegate; + +- (id)initWith:(FRepoInfo *)repoInfo andQueue:(dispatch_queue_t)queue lastSessionID:(NSString *)lastSessionID; + +- (void) open; +- (void) close; +- (void) start; +- (void) send:(NSDictionary *)dictionary; + +- (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message; +- (void)webSocketDidOpen:(FSRWebSocket *)webSocket; +- (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error; +- (void)webSocket:(FSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; + +@end + +@protocol FWebSocketDelegate + +- (void)onMessage:(FWebSocketConnection *)fwebSocket withMessage:(NSDictionary *)message; +- (void)onDisconnect:(FWebSocketConnection *)fwebSocket wasEverConnected:(BOOL)everConnected; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.m new file mode 100644 index 0000000..49d6bd8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Realtime/FWebSocketConnection.m @@ -0,0 +1,308 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Targetted compilation is ONLY for testing. UIKit is weak-linked in actual release build. + +#import + +#import +#import "FWebSocketConnection.h" +#import "FConstants.h" +#import "FIRDatabaseReference.h" +#import "FStringUtilities.h" +#import "FIRDatabase_Private.h" + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#endif + +@interface FWebSocketConnection () { + NSMutableString* frame; + BOOL everConnected; + BOOL isClosed; + NSTimer* keepAlive; +} + +- (void) shutdown; +- (void) onClosed; +- (void) closeIfNeverConnected; + +@property (nonatomic, strong) FSRWebSocket* webSocket; +@property (nonatomic, strong) NSNumber* connectionId; +@property (nonatomic, readwrite) int totalFrames; +@property (nonatomic, readonly) BOOL buffering; +@property (nonatomic, readonly) NSString* userAgent; +@property (nonatomic) dispatch_queue_t dispatchQueue; + +- (void)nop:(NSTimer *)timer; + +@end + +@implementation FWebSocketConnection + +@synthesize delegate; +@synthesize webSocket; +@synthesize connectionId; + +- (id)initWith:(FRepoInfo *)repoInfo andQueue:(dispatch_queue_t)queue lastSessionID:(NSString *)lastSessionID { + self = [super init]; + if (self) { + everConnected = NO; + isClosed = NO; + self.connectionId = [FUtilities LUIDGenerator]; + self.totalFrames = 0; + self.dispatchQueue = queue; + frame = nil; + + NSString* connectionUrl = [repoInfo connectionURLWithLastSessionID:lastSessionID]; + NSString* ua = [self userAgent]; + FFLog(@"I-RDB083001", @"(wsc:%@) Connecting to: %@ as %@", self.connectionId, connectionUrl, ua); + + NSURLRequest* req = [[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:connectionUrl]]; + self.webSocket = [[FSRWebSocket alloc] initWithURLRequest:req queue:queue andUserAgent:ua]; + [self.webSocket setDelegateDispatchQueue:queue]; + self.webSocket.delegate = self; + } + return self; +} + +- (NSString *) userAgent { + NSString* systemVersion; + NSString* deviceName; + BOOL hasUiDeviceClass = NO; + + // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual release build. + #if TARGET_OS_IOS || TARGET_OS_TV + Class uiDeviceClass = NSClassFromString(@"UIDevice"); + if (uiDeviceClass) { + systemVersion = [uiDeviceClass currentDevice].systemVersion; + deviceName = [uiDeviceClass currentDevice].model; + hasUiDeviceClass = YES; + } + #endif + + if (!hasUiDeviceClass) { + NSDictionary *systemVersionDictionary = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]; + systemVersion = [systemVersionDictionary objectForKey:@"ProductVersion"]; + deviceName = [systemVersionDictionary objectForKey:@"ProductName"]; + } + + NSString* bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; + + // Sanitize '/'s in deviceName and bundleIdentifier for stats + deviceName = [FStringUtilities sanitizedForUserAgent:deviceName]; + bundleIdentifier = [FStringUtilities sanitizedForUserAgent:bundleIdentifier]; + + // Firebase/5/__//{device model / os (Mac OS X, iPhone, etc.}_ + NSString* ua = [NSString stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion, [FIRDatabase buildVersion], systemVersion, deviceName, bundleIdentifier]; + return ua; +} + +- (BOOL) buffering { + return frame != nil; +} + +#pragma mark - +#pragma mark Public FWebSocketConnection methods + +- (void) open { + FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.", self.connectionId); + assert(delegate); + everConnected = NO; + // TODO Assert url + [self.webSocket open]; + dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC); + dispatch_after(when, self.dispatchQueue, ^{ + [self closeIfNeverConnected]; + }); +} + +- (void) close { + FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.", self.connectionId); + isClosed = YES; + [self.webSocket close]; +} + +- (void) start { + // Start is a no-op for websockets. +} + +- (void) send:(NSDictionary *)dictionary { + + [self resetKeepAlive]; + + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary + options:kNilOptions error:nil]; + + NSString* data = [[NSString alloc] initWithData:jsonData + encoding:NSUTF8StringEncoding]; + + NSArray* dataSegs = [FUtilities splitString:data intoMaxSize:kWebsocketMaxFrameSize]; + + // First send the header so the server knows how many segments are forthcoming + if (dataSegs.count > 1) { + [self.webSocket send:[NSString stringWithFormat:@"%u", (unsigned int)dataSegs.count]]; + } + + // Then, actually send the segments. + for(NSString * segment in dataSegs) { + [self.webSocket send:segment]; + } +} + +- (void) nop:(NSTimer *)timer { + if (!isClosed) { + FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId); + [self.webSocket send:@"0"]; + } + else { + FFLog(@"I-RDB083005", @"(wsc:%@) No more websocket; invalidating nop timer.", self.connectionId); + [timer invalidate]; + } +} + +- (void) handleNewFrameCount:(int) numFrames { + self.totalFrames = numFrames; + frame = [[NSMutableString alloc] initWithString:@""]; + FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d", self.connectionId, self.totalFrames); +} + +- (NSString *) extractFrameCount:(NSString *) message { + if ([message length] <= 4) { + int frameCount = [message intValue]; + if (frameCount > 0) { + [self handleNewFrameCount:frameCount]; + return nil; + } + } + [self handleNewFrameCount:1]; + return message; +} + +- (void) appendFrame:(NSString *) message { + [frame appendString:message]; + self.totalFrames = self.totalFrames - 1; + + if (self.totalFrames == 0) { + // Call delegate and pass an immutable version of the frame + NSDictionary* json = [NSJSONSerialization JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding] + options:kNilOptions + error:nil]; + frame = nil; + FFLog(@"I-RDB083007", @"(wsc:%@) handleIncomingFrame sending complete frame: %d", self.connectionId, self.totalFrames); + + @autoreleasepool { + [self.delegate onMessage:self withMessage:json]; + } + } +} + +- (void) handleIncomingFrame:(NSString *) message { + [self resetKeepAlive]; + if (self.buffering) { + [self appendFrame:message]; + } else { + NSString *remaining = [self extractFrameCount:message]; + if (remaining) { + [self appendFrame:remaining]; + } + } +} + +#pragma mark - +#pragma mark SRWebSocketDelegate implementation +- (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message +{ + [self handleIncomingFrame:message]; +} + +- (void)webSocketDidOpen:(FSRWebSocket *)webSocket +{ + FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId); + + everConnected = YES; + + dispatch_async(dispatch_get_main_queue(), ^{ + self->keepAlive = [NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval + target:self + selector:@selector(nop:) + userInfo:nil + repeats:YES]; + FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off", self.connectionId); + }); +} + +- (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error +{ + FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@", self.connectionId, [error description]); + [self onClosed]; +} + +- (void)webSocket:(FSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean +{ + FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@", self.connectionId, (long)code, reason); + [self onClosed]; +} + +#pragma mark - +#pragma mark Private methods + +/** + * Note that the close / onClosed / shutdown cycle here is a little different from the javascript client. + * In order to properly handle deallocation, no close-related action is taken at a higher level until we + * have received notification from the websocket itself that it is closed. Otherwise, we end up deallocating + * this class and the FConnection class before the websocket has a change to call some of its delegate methods. + * So, since close is the external close handler, we just set a flag saying not to call our own delegate method + * and close the websocket. That will trigger a callback into this class that can then do things like clean up + * the keepalive timer. + */ + +- (void) closeIfNeverConnected { + if (!everConnected) { + FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect", self.connectionId); + [self.webSocket close]; + } +} + +- (void) shutdown { + isClosed = YES; + + // Call delegate methods + [self.delegate onDisconnect:self wasEverConnected:everConnected]; + +} + +- (void) onClosed { + if (!isClosed) { + FFLog(@"I-RDB083013", @"Websocket is closing itself"); + [self shutdown]; + } + self.webSocket = nil; + if (keepAlive.isValid) { + [keepAlive invalidate]; + } +} + +- (void) resetKeepAlive { + NSDate* newTime = [NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval]; + // Calling setFireDate is actually kinda' expensive, so wait at least 5 seconds before updating it. + if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) { + FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@", self.connectionId, newTime, [keepAlive fireDate]); + [keepAlive setFireDate:newTime]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.h new file mode 100644 index 0000000..9eebdae --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" +#import "FTypedefs.h" +#import "FTypedefs_Private.h" +#import "FImmutableSortedDictionary.h" + +@class FNamedNode; + +@interface FChildrenNode : NSObject + +- (id)initWithChildren:(FImmutableSortedDictionary *)someChildren; +- (id)initWithPriority:(id)aPriority children:(FImmutableSortedDictionary *)someChildren; + +// FChildrenNode specific methods + +- (void) enumerateChildrenAndPriorityUsingBlock:(void (^)(NSString *, id, BOOL *))block; + +- (FNamedNode *) firstChild; +- (FNamedNode *) lastChild; + +@property (nonatomic, strong) FImmutableSortedDictionary* children; +@property (nonatomic, strong) id priorityNode; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.m new file mode 100644 index 0000000..d53ae80 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FChildrenNode.m @@ -0,0 +1,385 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FChildrenNode.h" +#import "FEmptyNode.h" +#import "FConstants.h" +#import "FStringUtilities.h" +#import "FUtilities.h" +#import "FNamedNode.h" +#import "FMaxNode.h" +#import "FTransformedEnumerator.h" +#import "FSnapshotUtilities.h" +#import "FTransformedEnumerator.h" +#import "FPriorityIndex.h" +#import "FUtilities.h" + +@interface FChildrenNode () +@property (nonatomic, strong) NSString *lazyHash; +@end + +@implementation FChildrenNode + +// Note: The only reason we allow nil priority is to for EmptyNode, since we can't use +// EmptyNode as the priority of EmptyNode. We might want to consider making EmptyNode its own +// class instead of an empty ChildrenNode. + +- (id)init { + return [self initWithPriority:nil children:[FImmutableSortedDictionary dictionaryWithComparator:[FUtilities keyComparator]]]; +} + +- (id)initWithChildren:(FImmutableSortedDictionary *)someChildren { + return [self initWithPriority:nil children:someChildren]; +} + +- (id)initWithPriority:(id)aPriority children:(FImmutableSortedDictionary *)someChildren { + if (someChildren.isEmpty && aPriority != nil && ![aPriority isEmpty]) { + [NSException raise:NSInvalidArgumentException format:@"Can't create empty node with priority!"]; + } + self = [super init]; + if(self) { + self.children = someChildren; + self.priorityNode = aPriority; + } + return self; +} + +- (NSString *) description { + return [[self valForExport:YES] description]; +} + +#pragma mark - +#pragma mark FNode methods + + +- (BOOL) isLeafNode { + return NO; +} + +- (id) getPriority { + if (self.priorityNode) { + return self.priorityNode; + } else { + return [FEmptyNode emptyNode]; + } + +} + +- (id) updatePriority:(id)aPriority { + if ([self.children isEmpty]) { + return [FEmptyNode emptyNode]; + } else { + return [[FChildrenNode alloc] initWithPriority:aPriority children:self.children]; + } +} + +- (id) getImmediateChild:(NSString *) childName { + if ([childName isEqualToString:@".priority"]) { + return [self getPriority]; + } else { + id child = [self.children objectForKey:childName]; + return (child == nil) ? [FEmptyNode emptyNode] : child; + } +} + +- (id) getChild:(FPath *)path { + NSString* front = [path getFront]; + if(front == nil) { + return self; + } + else { + return [[self getImmediateChild:front] getChild:[path popFront]]; + } +} + +- (BOOL)hasChild:(NSString *)childName { + return ![self getImmediateChild:childName].isEmpty; +} + + +- (id) updateImmediateChild:(NSString *)childName withNewChild:(id)newChildNode { + NSAssert(newChildNode != nil, @"Should always be passing nodes."); + + if ([childName isEqualToString:@".priority"]) { + return [self updatePriority:newChildNode]; + } else { + FImmutableSortedDictionary *newChildren; + if (newChildNode.isEmpty) { + newChildren = [self.children removeObjectForKey:childName]; + } else { + newChildren = [self.children setObject:newChildNode forKey:childName]; + } + if (newChildren.isEmpty) { + return [FEmptyNode emptyNode]; + } else { + return [[FChildrenNode alloc] initWithPriority:self.getPriority children:newChildren]; + } + } +} + +- (id) updateChild:(FPath *)path withNewChild:(id)newChildNode { + NSString* front = [path getFront]; + if(front == nil) { + return newChildNode; + } else { + NSAssert(![front isEqualToString:@".priority"] || path.length == 1, @".priority must be the last token in a path."); + id newImmediateChild = [[self getImmediateChild:front] updateChild:[path popFront] withNewChild:newChildNode]; + return [self updateImmediateChild:front withNewChild:newImmediateChild]; + } +} + +- (BOOL) isEmpty { + return [self.children isEmpty]; +} + +- (int) numChildren { + return [self.children count]; +} + +- (id) val { + return [self valForExport:NO]; +} + +- (id) valForExport:(BOOL)exp { + if([self isEmpty]) { + return [NSNull null]; + } + + __block int numKeys = 0; + __block NSInteger maxKey = 0; + __block BOOL allIntegerKeys = YES; + + NSMutableDictionary* obj = [[NSMutableDictionary alloc] initWithCapacity:[self.children count]]; + [self enumerateChildrenUsingBlock:^(NSString *key, id childNode, BOOL *stop) { + [obj setObject:[childNode valForExport:exp] forKey:key]; + + numKeys++; + + // If we already found a string key, don't bother with any of this + if (!allIntegerKeys) { + return; + } + + // Treat leading zeroes that are not exactly "0" as strings + NSString* firstChar = [key substringWithRange:NSMakeRange(0, 1)]; + if ([firstChar isEqualToString:@"0"] && [key length] > 1) { + allIntegerKeys = NO; + } else { + NSNumber *keyAsNum = [FUtilities intForString:key]; + if (keyAsNum != nil) { + NSInteger keyAsInt = [keyAsNum integerValue]; + if (keyAsInt > maxKey) { + maxKey = keyAsInt; + } + } else { + allIntegerKeys = NO; + } + } + }]; + + if (!exp && allIntegerKeys && maxKey < 2 * numKeys) { + // convert to an array + NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:maxKey + 1]; + for (int i = 0; i <= maxKey; ++i) { + NSString* keyString = [NSString stringWithFormat:@"%i", i]; + id child = obj[keyString]; + if (child != nil) { + [array addObject:child]; + } else { + [array addObject:[NSNull null]]; + } + } + return array; + } else { + + if(exp && [self getPriority] != nil && !self.getPriority.isEmpty) { + obj[kPayloadPriority] = [self.getPriority val]; + } + + return obj; + } +} + +- (NSString *) dataHash { + if (self.lazyHash == nil) { + NSMutableString *toHash = [[NSMutableString alloc] init]; + + if (!self.getPriority.isEmpty) { + [toHash appendString:@"priority:"]; + [FSnapshotUtilities appendHashRepresentationForLeafNode:(FLeafNode *)self.getPriority + toString:toHash + hashVersion:FDataHashVersionV1]; + [toHash appendString:@":"]; + } + + __block BOOL sawPriority = NO; + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + sawPriority = sawPriority || [[node getPriority] isEmpty]; + *stop = sawPriority; + }]; + if (sawPriority) { + NSMutableArray *array = [NSMutableArray array]; + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + FNamedNode *namedNode = [[FNamedNode alloc] initWithName:key andNode:node]; + [array addObject:namedNode]; + }]; + [array sortUsingComparator:^NSComparisonResult(FNamedNode *namedNode1, FNamedNode *namedNode2) { + return [[FPriorityIndex priorityIndex] compareNamedNode:namedNode1 toNamedNode:namedNode2]; + }]; + [array enumerateObjectsUsingBlock:^(FNamedNode *namedNode, NSUInteger idx, BOOL *stop) { + NSString *childHash = [namedNode.node dataHash]; + if (![childHash isEqualToString:@""]) { + [toHash appendFormat:@":%@:%@", namedNode.name, childHash]; + } + }]; + } else { + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + NSString *childHash = [node dataHash]; + if (![childHash isEqualToString:@""]) { + [toHash appendFormat:@":%@:%@", key, childHash]; + } + }]; + } + self.lazyHash = [toHash isEqualToString:@""] ? @"" : [FStringUtilities base64EncodedSha1:toHash]; + } + return self.lazyHash; +} + +- (NSComparisonResult)compare:(id )other { + // children nodes come last, unless this is actually an empty node, then we come first. + if (self.isEmpty) { + if (other.isEmpty) { + return NSOrderedSame; + } else { + return NSOrderedAscending; + } + } else if (other.isLeafNode || other.isEmpty) { + return NSOrderedDescending; + } else if (other == [FMaxNode maxNode]) { + return NSOrderedAscending; + } else { + // Must be another node with children. + return NSOrderedSame; + } +} + +- (BOOL)isEqual:(id )other { + if (other == self) { + return YES; + } else if (other == nil) { + return NO; + } else if (other.isLeafNode) { + return NO; + } else if (self.isEmpty && [other isEmpty]) { + // Empty nodes do not have priority + return YES; + } else { + FChildrenNode *otherChildrenNode = other; + if (![self.getPriority isEqual:other.getPriority]) { + return NO; + } else if (self.children.count == otherChildrenNode.children.count) { + __block BOOL equal = YES; + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + id child = [otherChildrenNode getImmediateChild:key]; + if (![child isEqual:node]) { + equal = NO; + *stop = YES; + } + }]; + return equal; + } else { + return NO; + } + } +} + +- (NSUInteger)hash { + __block NSUInteger hashCode = 0; + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + hashCode = 31 * hashCode + key.hash; + hashCode = 17 * hashCode + node.hash; + }]; + return 17 * hashCode + self.priorityNode.hash; +} + +- (void) enumerateChildrenAndPriorityUsingBlock:(void (^)(NSString *, id, BOOL *))block +{ + if ([self.getPriority isEmpty]) { + [self enumerateChildrenUsingBlock:block]; + } else { + __block BOOL passedPriorityKey = NO; + [self enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + if (!passedPriorityKey && [FUtilities compareKey:key toKey:@".priority"] == NSOrderedDescending) { + passedPriorityKey = YES; + BOOL stopAfterPriority = NO; + block(@".priority", [self getPriority], &stopAfterPriority); + if (stopAfterPriority) return; + } + block(key, node, stop); + }]; + } +} + +- (void) enumerateChildrenUsingBlock:(void (^)(NSString *, id, BOOL *))block +{ + [self.children enumerateKeysAndObjectsUsingBlock:block]; +} + +- (void) enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *, id, BOOL *))block +{ + [self.children enumerateKeysAndObjectsReverse:reverse usingBlock:block]; +} + +- (NSEnumerator *)childEnumerator +{ + return [[FTransformedEnumerator alloc] initWithEnumerator:self.children.keyEnumerator andTransform:^id(NSString *key) { + return [FNamedNode nodeWithName:key node:[self getImmediateChild:key]]; + }]; +} + +- (NSString *) predecessorChildKey:(NSString *)childKey +{ + return [self.children getPredecessorKey:childKey]; +} + +#pragma mark - +#pragma mark FChildrenNode specific methods + +- (id) childrenGetter:(id)key { + return [self.children objectForKey:key]; +} + +- (FNamedNode *)firstChild +{ + NSString *childKey = self.children.minKey; + if (childKey) { + return [[FNamedNode alloc] initWithName:childKey andNode:[self getImmediateChild:childKey]]; + } else { + return nil; + } +} + +- (FNamedNode *)lastChild +{ + NSString *childKey = self.children.maxKey; + if (childKey) { + return [[FNamedNode alloc] initWithName:childKey andNode:[self getImmediateChild:childKey]]; + } else { + return nil; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.h new file mode 100644 index 0000000..c67cfc7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.h @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FImmutableTree; +@protocol FNode; +@class FPath; + +/** +* This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with +* dealing with priority writes and multiple nested writes. At any given path, there is only allowed to be one write +* modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write to +* reflect the write added. +*/ +@interface FCompoundWrite : NSObject + +- (id) initWithWriteTree:(FImmutableTree *)tree; + +/** + * Creates a compound write with NSDictionary from path string to object + */ ++ (FCompoundWrite *) compoundWriteWithValueDictionary:(NSDictionary *)dictionary; +/** + * Creates a compound write with NSDictionary from path string to node + */ ++ (FCompoundWrite *) compoundWriteWithNodeDictionary:(NSDictionary *)dictionary; + ++ (FCompoundWrite *) emptyWrite; + +- (FCompoundWrite *) addWrite:(id)node atPath:(FPath *)path; +- (FCompoundWrite *) addWrite:(id)node atKey:(NSString *)key; +- (FCompoundWrite *) addCompoundWrite:(FCompoundWrite *)node atPath:(FPath *)path; +- (FCompoundWrite *) removeWriteAtPath:(FPath *)path; +- (id)rootWrite; +- (BOOL) hasCompleteWriteAtPath:(FPath *)path; +- (id) completeNodeAtPath:(FPath *)path; +- (NSArray *) completeChildren; +- (NSDictionary *)childCompoundWrites; +- (FCompoundWrite *) childCompoundWriteAtPath:(FPath *)path; +- (id) applyToNode:(id)node; +- (void)enumerateWrites:(void (^)(FPath *path, idnode, BOOL *stop))block; + +- (NSDictionary *)valForExport:(BOOL)exportFormat; + +- (BOOL) isEmpty; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.m new file mode 100644 index 0000000..8887095 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FCompoundWrite.m @@ -0,0 +1,257 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FCompoundWrite.h" +#import "FImmutableTree.h" +#import "FNode.h" +#import "FPath.h" +#import "FNamedNode.h" +#import "FSnapshotUtilities.h" + +@interface FCompoundWrite () +@property (nonatomic, strong) FImmutableTree *writeTree; +@end + +@implementation FCompoundWrite + +- (id) initWithWriteTree:(FImmutableTree *)tree { + self = [super init]; + if (self) { + self.writeTree = tree; + } + return self; +} + ++ (FCompoundWrite *)compoundWriteWithValueDictionary:(NSDictionary *)dictionary { + __block FImmutableTree *writeTree = [FImmutableTree empty]; + [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *pathString, id value, BOOL *stop) { + id node = [FSnapshotUtilities nodeFrom:value]; + FImmutableTree *tree = [[FImmutableTree alloc] initWithValue:node]; + writeTree = [writeTree setTree:tree atPath:[[FPath alloc] initWith:pathString]]; + }]; + return [[FCompoundWrite alloc] initWithWriteTree:writeTree]; +} + ++ (FCompoundWrite *)compoundWriteWithNodeDictionary:(NSDictionary *)dictionary { + __block FImmutableTree *writeTree = [FImmutableTree empty]; + [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *pathString, id node, BOOL *stop) { + FImmutableTree *tree = [[FImmutableTree alloc] initWithValue:node]; + writeTree = [writeTree setTree:tree atPath:[[FPath alloc] initWith:pathString]]; + }]; + return [[FCompoundWrite alloc] initWithWriteTree:writeTree]; +} + ++ (FCompoundWrite *) emptyWrite { + static dispatch_once_t pred = 0; + static FCompoundWrite *empty = nil; + dispatch_once(&pred, ^{ + empty = [[FCompoundWrite alloc] initWithWriteTree:[[FImmutableTree alloc] initWithValue:nil]]; + }); + return empty; +} + +- (FCompoundWrite *) addWrite:(id)node atPath:(FPath *)path { + if (path.isEmpty) { + return [[FCompoundWrite alloc] initWithWriteTree:[[FImmutableTree alloc] initWithValue:node]]; + } else { + FTuplePathValue *rootMost = [self.writeTree findRootMostValueAndPath:path]; + if (rootMost != nil) { + FPath *relativePath = [FPath relativePathFrom:rootMost.path to:path]; + id value = [rootMost.value updateChild:relativePath withNewChild:node]; + return [[FCompoundWrite alloc] initWithWriteTree:[self.writeTree setValue:value atPath:rootMost.path]]; + } else { + FImmutableTree *subtree = [[FImmutableTree alloc] initWithValue:node]; + FImmutableTree *newWriteTree = [self.writeTree setTree:subtree atPath:path]; + return [[FCompoundWrite alloc] initWithWriteTree:newWriteTree]; + } + } +} + +- (FCompoundWrite *) addWrite:(id)node atKey:(NSString *)key { + return [self addWrite:node atPath:[[FPath alloc] initWith:key]]; +} + +- (FCompoundWrite *) addCompoundWrite:(FCompoundWrite *)compoundWrite atPath:(FPath *)path { + __block FCompoundWrite *newWrite = self; + [compoundWrite.writeTree forEach:^(FPath *childPath, id value) { + newWrite = [newWrite addWrite:value atPath:[path child:childPath]]; + }]; + return newWrite; +} + +/** +* Will remove a write at the given path and deeper paths. This will not modify a write at a higher location, +* which must be removed by calling this method with that path. +* @param path The path at which a write and all deeper writes should be removed. +* @return The new FWriteCompound with the removed path. +*/ +- (FCompoundWrite *) removeWriteAtPath:(FPath *)path { + if (path.isEmpty) { + return [FCompoundWrite emptyWrite]; + } else { + FImmutableTree *newWriteTree = [self.writeTree setTree:[FImmutableTree empty] atPath:path]; + return [[FCompoundWrite alloc] initWithWriteTree:newWriteTree]; + } +} + +/** +* Returns whether this FCompoundWrite will fully overwrite a node at a given location and can therefore be considered +* "complete". +* @param path The path to check for +* @return Whether there is a complete write at that path. +*/ +- (BOOL) hasCompleteWriteAtPath:(FPath *)path { + return [self completeNodeAtPath:path] != nil; +} + +/** +* Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate +* writes from depeer paths, but will return child nodes from a more shallow path. +* @param path The path to get a complete write +* @return The node if complete at that path, or nil otherwise. +*/ +- (id) completeNodeAtPath:(FPath *)path { + FTuplePathValue *rootMost = [self.writeTree findRootMostValueAndPath:path]; + if (rootMost != nil) { + FPath *relativePath = [FPath relativePathFrom:rootMost.path to:path]; + return [rootMost.value getChild:relativePath]; + } else { + return nil; + } +} + +// TODO: change into traversal method... +- (NSArray *) completeChildren { + NSMutableArray *children = [[NSMutableArray alloc] init]; + if (self.writeTree.value != nil) { + id node = self.writeTree.value; + [node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + [children addObject:[[FNamedNode alloc] initWithName:key andNode:node]]; + }]; + } else { + [self.writeTree.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + if (childTree.value != nil) { + [children addObject:[[FNamedNode alloc] initWithName:childKey andNode:childTree.value]]; + } + }]; + } + return children; +} + + +// TODO: change into enumarate method +- (NSDictionary *)childCompoundWrites { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + [self.writeTree.children enumerateKeysAndObjectsUsingBlock:^(NSString *key, FImmutableTree *childWrite, BOOL *stop) { + dict[key] = [[FCompoundWrite alloc] initWithWriteTree:childWrite]; + }]; + return dict; +} + +- (FCompoundWrite *) childCompoundWriteAtPath:(FPath *)path { + if (path.isEmpty) { + return self; + } else { + id shadowingNode = [self completeNodeAtPath:path]; + if (shadowingNode != nil) { + return [[FCompoundWrite alloc] initWithWriteTree:[[FImmutableTree alloc] initWithValue:shadowingNode]]; + } else { + return [[FCompoundWrite alloc] initWithWriteTree:[self.writeTree subtreeAtPath:path]]; + } + } +} + +- (id) applySubtreeWrite:(FImmutableTree *)subtreeWrite atPath:(FPath *)relativePath toNode:(id)node { + if (subtreeWrite.value != nil) { + // Since a write there is always a leaf, we're done here. + return [node updateChild:relativePath withNewChild:subtreeWrite.value]; + } else { + __block id priorityWrite = nil; + __block id blockNode = node; + [subtreeWrite.children enumerateKeysAndObjectsUsingBlock:^(NSString *childKey, FImmutableTree *childTree, BOOL *stop) { + if ([childKey isEqualToString:@".priority"]) { + // Apply priorities at the end so we don't update priorities for either empty nodes or forget to apply + // priorities to empty nodes that are later filled. + NSAssert(childTree.value != nil, @"Priority writes must always be leaf nodes"); + priorityWrite = childTree.value; + } else { + blockNode = [self applySubtreeWrite:childTree atPath:[relativePath childFromString:childKey] toNode:blockNode]; + } + }]; + // If there was a priority write, we only apply it if the node is not empty + if (![blockNode getChild:relativePath].isEmpty && priorityWrite != nil) { + blockNode = [blockNode updateChild:[relativePath childFromString:@".priority"] withNewChild:priorityWrite]; + } + return blockNode; + } +} + +- (void)enumerateWrites:(void (^)(FPath *, id, BOOL *))block { + __block BOOL stop = NO; + // TODO: add stop to tree iterator... + [self.writeTree forEach:^(FPath *path, id value) { + if (!stop) { + block(path, value, &stop); + } + }]; +} + +/** +* Applies this FCompoundWrite to a node. The node is returned with all writes from this FCompoundWrite applied to the node. +* @param node The node to apply this FCompoundWrite to +* @return The node with all writes applied +*/ +- (id) applyToNode:(id)node { + return [self applySubtreeWrite:self.writeTree atPath:[FPath empty] toNode:node]; +} + +/** +* Return true if this CompoundWrite is empty and therefore does not modify any nodes. +* @return Whether this CompoundWrite is empty +*/ +- (BOOL) isEmpty { + return self.writeTree.isEmpty; +} + +- (id) rootWrite { + return self.writeTree.value; +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[FCompoundWrite class]]) { + return NO; + } + FCompoundWrite *other = (FCompoundWrite *)object; + return [[self valForExport:YES] isEqualToDictionary:[other valForExport:YES]]; +} + +- (NSUInteger)hash { + return [[self valForExport:YES] hash]; +} + +- (NSDictionary *)valForExport:(BOOL)exportFormat { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self.writeTree forEach:^(FPath *path, id value) { + dictionary[path.wireFormat] = [value valForExport:exportFormat]; + }]; + return dictionary; +} + +- (NSString *)description { + return [[self valForExport:YES] description]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.h new file mode 100644 index 0000000..ab404c2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.h @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@interface FEmptyNode : NSObject + ++ (id) emptyNode; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.m new file mode 100644 index 0000000..f41e118 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FEmptyNode.m @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FEmptyNode.h" +#import "FChildrenNode.h" + +@implementation FEmptyNode + ++ (id) emptyNode { + static FChildrenNode* empty = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + empty = [[FChildrenNode alloc] init]; + }); + return empty; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.h new file mode 100644 index 0000000..fd2db37 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.h @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#import + +#import "FNode.h" +#import "FIndex.h" +#import "FNamedNode.h" + +/** + * Represents a node together with an index. The index and node are updated in unison. In the case where the index + * does not affect the ordering (i.e. the ordering is identical to the key ordering) this class uses a fallback index + * to save memory. Everything operating on the index must special case the fallback index. + */ +@interface FIndexedNode : NSObject + +@property (nonatomic, strong, readonly) id node; + ++ (FIndexedNode *)indexedNodeWithNode:(id)node; ++ (FIndexedNode *)indexedNodeWithNode:(id)node index:(id)index; + +- (BOOL)hasIndex:(id)index; +- (FIndexedNode *)updateChild:(NSString *)key withNewChild:(id)newChildNode; +- (FIndexedNode *)updatePriority:(id)priority; + +- (FNamedNode *)firstChild; +- (FNamedNode *)lastChild; + +- (NSString *)predecessorForChildKey:(NSString *)childKey childNode:(id)childNode index:(id)index; + +- (void)enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *key, id node, BOOL *stop))block; + +- (NSEnumerator *)childEnumerator; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.m new file mode 100644 index 0000000..9dc60e1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FIndexedNode.m @@ -0,0 +1,202 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIndexedNode.h" + +#import "FImmutableSortedSet.h" +#import "FIndex.h" +#import "FPriorityIndex.h" +#import "FKeyIndex.h" +#import "FChildrenNode.h" + +static FImmutableSortedSet *FALLBACK_INDEX; + +@interface FIndexedNode () + +@property (nonatomic, strong) id node; +/** + * The indexed set is initialized lazily to prevent creation when it is not needed + */ +@property (nonatomic, strong) FImmutableSortedSet *indexed; +@property (nonatomic, strong) id index; + +@end + +@implementation FIndexedNode + ++ (FImmutableSortedSet *)fallbackIndex { + static FImmutableSortedSet *fallbackIndex; + static dispatch_once_t once; + dispatch_once(&once, ^{ + fallbackIndex = [[FImmutableSortedSet alloc] init]; + }); + return fallbackIndex; +} + ++ (FIndexedNode *)indexedNodeWithNode:(id)node +{ + return [[FIndexedNode alloc] initWithNode:node index:[FPriorityIndex priorityIndex]]; +} + ++ (FIndexedNode *)indexedNodeWithNode:(id)node index:(id)index +{ + return [[FIndexedNode alloc] initWithNode:node index:index]; +} + +- (id)initWithNode:(id)node index:(id)index +{ + // Initialize indexed lazily + return [self initWithNode:node index:index indexed:nil]; +} + +- (id)initWithNode:(id)node index:(id)index indexed:(FImmutableSortedSet *)indexed +{ + self = [super init]; + if (self != nil) { + self->_node = node; + self->_index = index; + self->_indexed = indexed; + } + return self; +} + +- (void)ensureIndexed +{ + if (!self.indexed) { + if ([self.index isEqual:[FKeyIndex keyIndex]]) { + self.indexed = [FIndexedNode fallbackIndex]; + } else { + __block BOOL sawChild = NO; + [self.node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + sawChild = sawChild || [self.index isDefinedOn:node]; + *stop = sawChild; + }]; + if (sawChild) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + [self.node enumerateChildrenUsingBlock:^(NSString *key, id node, BOOL *stop) { + FNamedNode *namedNode = [[FNamedNode alloc] initWithName:key andNode:node]; + dict[namedNode] = [NSNull null]; + }]; + // Make sure to assign index here, because the comparator will be retained and using self will cause a + // cycle + id index = self.index; + self.indexed = [FImmutableSortedSet setWithKeysFromDictionary:dict + comparator:^NSComparisonResult(FNamedNode *namedNode1, FNamedNode *namedNode2) { + return [index compareNamedNode:namedNode1 toNamedNode:namedNode2]; + }]; + } else { + self.indexed = [FIndexedNode fallbackIndex]; + } + } + } +} + +- (BOOL)hasIndex:(id)index +{ + return [self.index isEqual:index]; +} + +- (FIndexedNode *)updateChild:(NSString *)key withNewChild:(id)newChildNode +{ + id newNode = [self.node updateImmediateChild:key withNewChild:newChildNode]; + if (self.indexed == [FIndexedNode fallbackIndex] && ![self.index isDefinedOn:newChildNode]) { + // doesn't affect the index, no need to create an index + return [[FIndexedNode alloc] initWithNode:newNode index:self.index indexed:[FIndexedNode fallbackIndex]]; + } else if (!self.indexed || self.indexed == [FIndexedNode fallbackIndex]) { + // No need to index yet, index lazily + return [[FIndexedNode alloc] initWithNode:newNode index:self.index]; + } else { + id oldChild = [self.node getImmediateChild:key]; + FImmutableSortedSet *newIndexed = [self.indexed removeObject:[FNamedNode nodeWithName:key node:oldChild]]; + if (![newChildNode isEmpty]) { + newIndexed = [newIndexed addObject:[FNamedNode nodeWithName:key node:newChildNode]]; + } + return [[FIndexedNode alloc] initWithNode:newNode index:self.index indexed:newIndexed]; + } +} + +- (FIndexedNode *)updatePriority:(id)priority +{ + return [[FIndexedNode alloc] initWithNode:[self.node updatePriority:priority] + index:self.index + indexed:self.indexed]; +} + +- (FNamedNode *)firstChild +{ + if (![self.node isKindOfClass:[FChildrenNode class]]) { + return nil; + } else { + [self ensureIndexed]; + if (self.indexed == [FIndexedNode fallbackIndex]) { + return [((FChildrenNode *)self.node) firstChild]; + } else { + return self.indexed.firstObject; + } + } +} + +- (FNamedNode *)lastChild +{ + if (![self.node isKindOfClass:[FChildrenNode class]]) { + return nil; + } else { + [self ensureIndexed]; + if (self.indexed == [FIndexedNode fallbackIndex]) { + return [((FChildrenNode *)self.node) lastChild]; + } else { + return self.indexed.lastObject; + } + } +} + +- (NSString *)predecessorForChildKey:(NSString *)childKey childNode:(id)childNode index:(id)index +{ + if (![self.index isEqual:index]) { + [NSException raise:NSInvalidArgumentException format:@"Index not available in IndexedNode!"]; + } + [self ensureIndexed]; + if (self.indexed == [FIndexedNode fallbackIndex]) { + return [self.node predecessorChildKey:childKey]; + } else { + FNamedNode *node = [self.indexed predecessorEntry:[FNamedNode nodeWithName:childKey node:childNode]]; + return node.name; + } +} + +- (void)enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *, id, BOOL *))block +{ + [self ensureIndexed]; + if (self.indexed == [FIndexedNode fallbackIndex]) { + [self.node enumerateChildrenReverse:reverse usingBlock:block]; + } else { + [self.indexed enumerateObjectsReverse:reverse usingBlock:^(FNamedNode *namedNode, BOOL *stop) { + block(namedNode.name, namedNode.node, stop); + }]; + } +} + +- (NSEnumerator *)childEnumerator +{ + [self ensureIndexed]; + if (self.indexed == [FIndexedNode fallbackIndex]) { + return [self.node childEnumerator]; + } else { + return [self.indexed objectEnumerator]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.h new file mode 100644 index 0000000..15e0132 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + + +@interface FLeafNode : NSObject + +- (id)initWithValue:(id)aValue; +- (id)initWithValue:(id)aValue withPriority:(id)aPriority; + +@property (nonatomic, strong) id value; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.m new file mode 100644 index 0000000..a26e057 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FLeafNode.m @@ -0,0 +1,250 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FLeafNode.h" +#import "FEmptyNode.h" +#import "FChildrenNode.h" +#import "FConstants.h" +#import "FImmutableSortedDictionary.h" +#import "FUtilities.h" +#import "FStringUtilities.h" +#import "FSnapshotUtilities.h" + +@interface FLeafNode () +@property (nonatomic, strong) id priorityNode; +@property (nonatomic, strong) NSString *lazyHash; + +@end + +@implementation FLeafNode + +@synthesize value; +@synthesize priorityNode; + +- (id)initWithValue:(id)aValue { + self = [super init]; + if (self) { + self.value = aValue; + self.priorityNode = [FEmptyNode emptyNode]; + } + return self; +} + +- (id)initWithValue:(id)aValue withPriority:(id)aPriority { + self = [super init]; + if (self) { + self.value = aValue; + [FSnapshotUtilities validatePriorityNode:aPriority]; + self.priorityNode = aPriority; + } + return self; +} + +#pragma mark - +#pragma mark FNode methods + +- (BOOL) isLeafNode { + return YES; +} + +- (id) getPriority { + return self.priorityNode; +} + +- (id) updatePriority:(id)aPriority { + return [[FLeafNode alloc] initWithValue:self.value withPriority:aPriority]; +} + +- (id) getImmediateChild:(NSString *) childName { + if ([childName isEqualToString:@".priority"]) { + return self.priorityNode; + } else { + return [FEmptyNode emptyNode]; + } +} + +- (id) getChild:(FPath *)path { + if (path.getFront == nil) { + return self; + } else if ([[path getFront] isEqualToString:@".priority"]) { + return [self getPriority]; + } else { + return [FEmptyNode emptyNode]; + } +} + +- (BOOL)hasChild:(NSString *)childName { + return [childName isEqualToString:@".priority"] && ![self getPriority].isEmpty; +} + + +- (NSString *)predecessorChildKey:(NSString *)childKey +{ + return nil; +} + +- (id) updateImmediateChild:(NSString *)childName withNewChild:(id)newChildNode { + if ([childName isEqualToString:@".priority"]) { + return [self updatePriority:newChildNode]; + } else if (newChildNode.isEmpty) { + return self; + } else { + FChildrenNode* childrenNode = [[FChildrenNode alloc] init]; + childrenNode = [childrenNode updateImmediateChild:childName withNewChild:newChildNode]; + childrenNode = [childrenNode updatePriority:self.priorityNode]; + return childrenNode; + } +} + +- (id) updateChild:(FPath *)path withNewChild:(id)newChildNode { + NSString* front = [path getFront]; + if(front == nil) { + return newChildNode; + } else if (newChildNode.isEmpty && ![front isEqualToString:@".priority"]) { + return self; + } else { + NSAssert(![front isEqualToString:@".priority"] || path.length == 1, @".priority must be the last token in a path."); + return [self updateImmediateChild:front withNewChild: + [[FEmptyNode emptyNode] updateChild:[path popFront] withNewChild:newChildNode]]; + } +} + +- (id) val { + return [self valForExport:NO]; +} + +- (id) valForExport:(BOOL)exp { + if(exp && !self.getPriority.isEmpty) { + return @{kPayloadValue : self.value, + kPayloadPriority : [[self getPriority] val]}; + } + else { + return self.value; + } +} + +- (BOOL)isEqual:(id )other { + if(other == self) { + return YES; + } else if (other.isLeafNode) { + FLeafNode *otherLeaf = other; + if ([FUtilities getJavascriptType:self.value] != [FUtilities getJavascriptType:otherLeaf.value]) { + return NO; + } + return [otherLeaf.value isEqual:self.value] && [otherLeaf.priorityNode isEqual:self.priorityNode]; + } else { + return NO; + } +} + +- (NSUInteger)hash { + return [self.value hash] * 17 + self.priorityNode.hash; +} + +- (id )withIndex:(id )index { + return self; +} + +- (BOOL)isIndexed:(id )index { + return YES; +} + +- (BOOL) isEmpty { + return NO; +} + +- (int) numChildren { + return 0; +} + +- (void) enumerateChildrenUsingBlock:(void (^)(NSString *, id, BOOL *))block +{ + // Nothing to iterate over +} + +- (void) enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *, id, BOOL *))block +{ + // Nothing to iterate over +} + +- (NSEnumerator *)childEnumerator +{ + // Nothing to iterate over + return [@[] objectEnumerator]; +} + +- (NSString *) dataHash { + if (self.lazyHash == nil) { + NSMutableString *toHash = [[NSMutableString alloc] init]; + [FSnapshotUtilities appendHashRepresentationForLeafNode:self toString:toHash hashVersion:FDataHashVersionV1]; + + self.lazyHash = [FStringUtilities base64EncodedSha1:toHash]; + } + return self.lazyHash; +} + +- (NSComparisonResult)compare:(id )other { + if (other == [FEmptyNode emptyNode]) { + return NSOrderedDescending; + } else if ([other isKindOfClass:[FChildrenNode class]]) { + return NSOrderedAscending; + } else { + NSAssert(other.isLeafNode, @"Compared against unknown type of node."); + return [self compareToLeafNode:(FLeafNode*)other]; + } +} + ++ (NSArray*) valueTypeOrder { + static NSArray* valueOrder = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + valueOrder = @[kJavaScriptObject, kJavaScriptBoolean, kJavaScriptNumber, kJavaScriptString]; + }); + return valueOrder; +} + +- (NSComparisonResult) compareToLeafNode:(FLeafNode*)other { + NSString* thisLeafType = [FUtilities getJavascriptType:self.value]; + NSString* otherLeafType = [FUtilities getJavascriptType:other.value]; + NSUInteger thisIndex = [[FLeafNode valueTypeOrder] indexOfObject:thisLeafType]; + NSUInteger otherIndex = [[FLeafNode valueTypeOrder] indexOfObject:otherLeafType]; + assert(thisIndex >= 0 && otherIndex >= 0); + if (otherIndex == thisIndex) { + // Same type. Compare values. + if (thisLeafType == kJavaScriptObject) { + // Deferred value nodes are all equal, but we should also never get to this point... + return NSOrderedSame; + } else if (thisLeafType == kJavaScriptString) { + return [self.value compare:other.value options:NSLiteralSearch]; + } else { + return [self.value compare:other.value]; + } + } else { + return thisIndex > otherIndex ? NSOrderedDescending : NSOrderedAscending; + } +} + +- (NSString *) description { + return [[self valForExport:YES] description]; +} + +- (void) forEachChildDo:(fbt_bool_nsstring_node)action { + // There are no children, so there is nothing to do. + return; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FNode.h new file mode 100644 index 0000000..1316756 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FNode.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" +#import "FTypedefs_Private.h" + +@protocol FIndex; + +@protocol FNode + +- (BOOL) isLeafNode; +- (id) getPriority; +- (id) updatePriority:(id)priority; +- (id) getImmediateChild:(NSString *)childKey; +- (id) getChild:(FPath *)path; +- (NSString *) predecessorChildKey:(NSString *)childKey; +- (id) updateImmediateChild:(NSString *)childKey withNewChild:(id)newChildNode; +- (id) updateChild:(FPath *)path withNewChild:(id)newChildNode; +- (BOOL) hasChild:(NSString*)childKey; +- (BOOL) isEmpty; +- (int) numChildren; +- (id) val; +- (id) valForExport:(BOOL)exp; +- (NSString *) dataHash; +- (NSComparisonResult) compare:(id)other; +- (BOOL) isEqual:(id)other; +- (void)enumerateChildrenUsingBlock:(void (^)(NSString *key, id node, BOOL *stop))block; +- (void)enumerateChildrenReverse:(BOOL)reverse usingBlock:(void (^)(NSString *key, id node, BOOL *stop))block; + +- (NSEnumerator *)childEnumerator; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.h new file mode 100644 index 0000000..2a28788 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@class FImmutableSortedDictionary; +@class FCompoundWrite; +@class FLeafNode; +@protocol FNode; + +typedef NS_ENUM(NSInteger, FDataHashVersion) { + FDataHashVersionV1, + FDataHashVersionV2, +}; + +@interface FSnapshotUtilities : NSObject + ++ (id) nodeFrom:(id)val; ++ (id) nodeFrom:(id)val priority:(id)priority; ++ (id) nodeFrom:(id)val withValidationFrom:(NSString *)fn; ++ (id) nodeFrom:(id)val priority:(id)priority withValidationFrom:(NSString *)fn; ++ (FCompoundWrite *) compoundWriteFromDictionary:(NSDictionary *)values withValidationFrom:(NSString *)fn; ++ (void) validatePriorityNode:(id)priorityNode; ++ (void)appendHashRepresentationForLeafNode:(FLeafNode *)val + toString:(NSMutableString *)string + hashVersion:(FDataHashVersion)hashVersion; ++ (void)appendHashV2RepresentationForString:(NSString *)string toString:(NSMutableString *)mutableString; + ++ (NSUInteger)estimateSerializedNodeSize:(id)node; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.m new file mode 100644 index 0000000..c6012d3 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Snapshot/FSnapshotUtilities.m @@ -0,0 +1,301 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FSnapshotUtilities.h" +#import "FEmptyNode.h" +#import "FLeafNode.h" +#import "FConstants.h" +#import "FUtilities.h" +#import "FChildrenNode.h" +#import "FLLRBValueNode.h" +#import "FValidation.h" +#import "FMaxNode.h" +#import "FNamedNode.h" +#import "FCompoundWrite.h" + +@implementation FSnapshotUtilities + ++ (id) nodeFrom:(id)val { + return [FSnapshotUtilities nodeFrom:val priority:nil]; +} + ++ (id) nodeFrom:(id)val priority:(id)priority { + return [FSnapshotUtilities nodeFrom:val priority:priority withValidationFrom:@"nodeFrom:priority:"]; +} + ++ (id) nodeFrom:(id)val withValidationFrom:(NSString *)fn { + return [FSnapshotUtilities nodeFrom:val priority:nil withValidationFrom:fn]; +} + ++ (id) nodeFrom:(id)val priority:(id)priority withValidationFrom:(NSString *)fn { + return [FSnapshotUtilities nodeFrom:val priority:priority withValidationFrom:fn atDepth:0 path:[[NSMutableArray alloc] init]]; +} + ++ (id) nodeFrom:(id)val priority:(id)aPriority withValidationFrom:(NSString *)fn atDepth:(int)depth path:(NSMutableArray *)path { + @autoreleasepool { + return [FSnapshotUtilities internalNodeFrom:val priority:aPriority withValidationFrom:fn atDepth:depth path:path]; + } +} + ++ (id) internalNodeFrom:(id)val priority:(id)aPriority withValidationFrom:(NSString *)fn atDepth:(int)depth path:(NSMutableArray *)path { + + + if (depth > kFirebaseMaxObjectDepth) { + NSRange range; + range.location = 0; + range.length = 100; + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Max object depth exceeded: %@...", fn, pathString] userInfo:nil]; + } + + if (val == nil || val == [NSNull null]) { + // Null is a valid type to store + return [FEmptyNode emptyNode]; + } + + [FValidation validateFrom:fn isValidPriorityValue:aPriority withPath:path]; + id priority = [FSnapshotUtilities nodeFrom:aPriority]; + + id value = val; + BOOL isLeafNode = NO; + + if([value isKindOfClass:[NSDictionary class]]) { + NSDictionary* dict = val; + if(dict[kPayloadPriority] != nil) { + id rawPriority = [dict objectForKey:kPayloadPriority]; + [FValidation validateFrom:fn isValidPriorityValue:rawPriority withPath:path]; + priority = [FSnapshotUtilities nodeFrom:rawPriority]; + } + + if(dict[kPayloadValue] != nil) { + value = [dict objectForKey:kPayloadValue]; + if ([FValidation validateFrom:fn isValidLeafValue:value withPath:path]) { + isLeafNode = YES; + } else { + @throw [[NSException alloc] + initWithName:@"InvalidLeafValueType" + reason:[NSString stringWithFormat:@"(%@) Invalid data type used with .value. Can only use " + "NSString and NSNumber or be null. Found %@ instead.", + fn, [[value class] description]] userInfo:nil]; + } + } + } + + if([FValidation validateFrom:fn isValidLeafValue:value withPath:path]) { + isLeafNode = YES; + } + + if (isLeafNode) { + return [[FLeafNode alloc] initWithValue:value withPriority:priority]; + } + + // Unlike with JS, we have to handle the dictionary and array cases separately. + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary* dval = (NSDictionary *)value; + NSMutableDictionary *children = [NSMutableDictionary dictionaryWithCapacity:dval.count]; + + // Avoid creating a million newPaths by appending to old one + for (id keyId in dval) { + [FValidation validateFrom:fn validDictionaryKey:keyId withPath:path]; + NSString* key = (NSString*)keyId; + + if (![key hasPrefix:kPayloadMetadataPrefix]) { + [path addObject:key]; + id childNode = [FSnapshotUtilities nodeFrom:dval[key] priority:nil withValidationFrom:fn atDepth:depth + 1 path:path]; + [path removeLastObject]; + + if (![childNode isEmpty]) { + children[key] = childNode; + } + } + } + + if ([children count] == 0) { + return [FEmptyNode emptyNode]; + } else { + FImmutableSortedDictionary *childrenDict = [FImmutableSortedDictionary fromDictionary:children + withComparator:[FUtilities keyComparator]]; + return [[FChildrenNode alloc] initWithPriority:priority children:childrenDict]; + } + } else if([value isKindOfClass:[NSArray class]]) { + NSArray* aval = (NSArray *)value; + NSMutableDictionary* children = [NSMutableDictionary dictionaryWithCapacity:aval.count]; + + for(int i = 0; i < [aval count]; i++) { + NSString* key = [NSString stringWithFormat:@"%i", i]; + [path addObject:key]; + id childNode = [FSnapshotUtilities nodeFrom:[aval objectAtIndex:i] priority:nil withValidationFrom:fn atDepth:depth + 1 path:path]; + [path removeLastObject]; + + if (![childNode isEmpty]) { + children[key] = childNode; + } + } + + if ([children count] == 0) { + return [FEmptyNode emptyNode]; + } else { + FImmutableSortedDictionary *childrenDict = [FImmutableSortedDictionary fromDictionary:children + withComparator:[FUtilities keyComparator]]; + return [[FChildrenNode alloc] initWithPriority:priority children:childrenDict]; + } + } else { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" + reason:[NSString stringWithFormat:@"(%@) Cannot store object of type %@ at %@. " + "Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.", + fn, [[value class] description], pathString] userInfo:nil]; + } +} + ++ (FCompoundWrite *) compoundWriteFromDictionary:(NSDictionary *)values withValidationFrom:(NSString *)fn { + FCompoundWrite *compoundWrite = [FCompoundWrite emptyWrite]; + + NSMutableArray *updatePaths = [NSMutableArray arrayWithCapacity:values.count]; + for (NSString *keyId in values) { + id value = values[keyId]; + [FValidation validateFrom:fn validUpdateDictionaryKey:keyId withValue:value]; + + FPath* path = [FPath pathWithString:keyId]; + id node = [FSnapshotUtilities nodeFrom:value withValidationFrom:fn]; + + [updatePaths addObject:path]; + compoundWrite = [compoundWrite addWrite:node atPath:path]; + } + + // Check that the update paths are not descendants of each other. + [updatePaths sortUsingComparator:^NSComparisonResult(FPath* left, FPath* right) { + return [left compare:right]; + }]; + FPath *prevPath = nil; + for (FPath *path in updatePaths) { + if (prevPath != nil && [prevPath contains:path]) { + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Invalid path in object. Path (%@) is an ancestor of (%@).", fn, prevPath, path] userInfo:nil]; + } + prevPath = path; + } + + return compoundWrite; +} + ++ (void)validatePriorityNode:(id )priorityNode { + assert(priorityNode != nil); + if (priorityNode.isLeafNode) { + id val = priorityNode.val; + if ([val isKindOfClass:[NSDictionary class]]) { + NSDictionary* valDict __unused = (NSDictionary*)val; + NSAssert(valDict[kServerValueSubKey] != nil, @"Priority can't be object unless it's a deferred value"); + } else { + NSString *jsType __unused = [FUtilities getJavascriptType:val]; + NSAssert(jsType == kJavaScriptString || jsType == kJavaScriptNumber, @"Priority of unexpected type."); + } + } else { + NSAssert(priorityNode == [FMaxNode maxNode] || priorityNode.isEmpty, @"Priority of unexpected type."); + } + // Don't call getPriority() on MAX_NODE to avoid hitting assertion. + NSAssert(priorityNode == [FMaxNode maxNode] || priorityNode.getPriority.isEmpty, + @"Priority nodes can't have a priority of their own."); +} + ++ (void)appendHashRepresentationForLeafNode:(FLeafNode *)leafNode + toString:(NSMutableString *)string + hashVersion:(FDataHashVersion)hashVersion { + NSAssert(hashVersion == FDataHashVersionV1 || hashVersion == FDataHashVersionV2, + @"Unknown hash version: %lu", (unsigned long)hashVersion); + if (!leafNode.getPriority.isEmpty) { + [string appendString:@"priority:"]; + [FSnapshotUtilities appendHashRepresentationForLeafNode:leafNode.getPriority toString:string hashVersion:hashVersion]; + [string appendString:@":"]; + } + + NSString *jsType = [FUtilities getJavascriptType:leafNode.val]; + [string appendString:jsType]; + [string appendString:@":"]; + + + if (jsType == kJavaScriptBoolean) { + NSString *boolString = [leafNode.val boolValue] ? kJavaScriptTrue : kJavaScriptFalse; + [string appendString:boolString]; + } else if (jsType == kJavaScriptNumber) { + NSString *numberString = [FUtilities ieee754StringForNumber:leafNode.val]; + [string appendString:numberString]; + } else if (jsType == kJavaScriptString) { + if (hashVersion == FDataHashVersionV1) { + [string appendString:leafNode.val]; + } else { + NSAssert(hashVersion == FDataHashVersionV2, @"Invalid hash version found"); + [FSnapshotUtilities appendHashV2RepresentationForString:leafNode.val toString:string]; + } + } else { + [NSException raise:NSInvalidArgumentException format:@"Unknown value for hashing: %@", leafNode]; + } +} + ++ (void)appendHashV2RepresentationForString:(NSString *)string + toString:(NSMutableString *)mutableString { + string = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]; + string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; + [mutableString appendString:@"\""]; + [mutableString appendString:string]; + [mutableString appendString:@"\""]; +} + ++ (NSUInteger)estimateLeafNodeSize:(FLeafNode *)leafNode { + NSString *jsType = [FUtilities getJavascriptType:leafNode.val]; + // These values are somewhat arbitrary, but we don't need an exact value so prefer performance over exact value + NSUInteger valueSize; + if (jsType == kJavaScriptNumber) { + valueSize = 8; // estimate each float with 8 bytes + } else if (jsType == kJavaScriptBoolean) { + valueSize = 4; // true or false need roughly 4 bytes + } else if (jsType == kJavaScriptString) { + valueSize = 2 + [leafNode.val length]; // add 2 for quotes + } else { + [NSException raise:NSInvalidArgumentException format:@"Unknown leaf type: %@", leafNode]; + return 0; + } + + if (leafNode.getPriority.isEmpty) { + return valueSize; + } else { + // Account for extra overhead due to the extra JSON object and the ".value" and ".priority" keys, colons, comma + NSUInteger leafPriorityOverhead = 2 + 8 + 11 + 2 + 1; + return leafPriorityOverhead + valueSize + [FSnapshotUtilities estimateLeafNodeSize:leafNode.getPriority]; + } +} + ++ (NSUInteger)estimateSerializedNodeSize:(id)node { + if ([node isEmpty]) { + return 4; // null keyword + } else if ([node isLeafNode]) { + return [FSnapshotUtilities estimateLeafNodeSize:node]; + } else { + NSAssert([node isKindOfClass:[FChildrenNode class]], @"Unexpected node type: %@", [node class]); + __block NSUInteger sum = 1; // opening brackets + [((FChildrenNode *)node) enumerateChildrenAndPriorityUsingBlock:^(NSString *key, idchild, BOOL *stop) { + sum += key.length; + sum += 4; // quotes around key and colon and (comma or closing bracket) + sum += [FSnapshotUtilities estimateSerializedNodeSize:child]; + }]; + return sum; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.h new file mode 100644 index 0000000..589dc25 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FAtomicNumber : NSObject + +- (NSNumber *) getAndIncrement; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.m new file mode 100644 index 0000000..4a14caa --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FAtomicNumber.m @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FAtomicNumber.h" + +@interface FAtomicNumber() { + unsigned long number; +} + +@property (nonatomic, strong) NSLock* lock; + +@end + +@implementation FAtomicNumber + +@synthesize lock; + +- (id)init +{ + self = [super init]; + if (self) { + number = 1; + self.lock = [[NSLock alloc] init]; + } + return self; +} + +- (NSNumber *) getAndIncrement { + NSNumber* result; + + // See: http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW14 to improve, etc. + + [self.lock lock]; + result = [NSNumber numberWithUnsignedLong:number]; + number = number + 1; + [self.lock unlock]; + + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.h new file mode 100644 index 0000000..069e10f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.h @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRDatabaseQuery.h" +#import "FIRDatabaseConfig.h" +#import "FTypedefs_Private.h" + +@interface FEventEmitter : NSObject + +- (id) initWithAllowedEvents:(NSArray *)theAllowedEvents queue:(dispatch_queue_t)queue; + +- (id) getInitialEventForType:(NSString *)eventType; +- (void) triggerEventType:(NSString *)eventType data:(id)data; + +- (FIRDatabaseHandle)observeEventType:(NSString *)eventType withBlock:(fbt_void_id)block; +- (void) removeObserverForEventType:(NSString *)eventType withHandle:(FIRDatabaseHandle)handle; + +- (void) validateEventType:(NSString *)eventType; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.m new file mode 100644 index 0000000..f7c569b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FEventEmitter.m @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#import "FEventEmitter.h" +#import "FUtilities.h" +#import "FRepoManager.h" +#import "FIRDatabaseQuery_Private.h" + +@interface FEventListener : NSObject + +@property (nonatomic, copy) fbt_void_id userCallback; +@property (nonatomic) FIRDatabaseHandle handle; + +@end + +@implementation FEventListener + +@synthesize userCallback; +@synthesize handle; + +@end + + +@interface FEventEmitter () + +@property (nonatomic, strong) NSArray *allowedEvents; +@property (nonatomic, strong) NSMutableDictionary *listeners; +@property (nonatomic, strong) dispatch_queue_t queue; + +@end + + +@implementation FEventEmitter + +@synthesize allowedEvents; +@synthesize listeners; + +- (id) initWithAllowedEvents:(NSArray *)theAllowedEvents queue:(dispatch_queue_t)queue { + if (theAllowedEvents == nil || [theAllowedEvents count] == 0) { + @throw [NSException exceptionWithName:@"AllowedEventsValidation" reason:@"FEventEmitters must be initialized with at least one valid event." userInfo:nil]; + } + + self = [super init]; + + if (self) { + self.allowedEvents = [theAllowedEvents copy]; + self.listeners = [[NSMutableDictionary alloc] init]; + self.queue = queue; + } + + return self; +} + +- (id) getInitialEventForType:(NSString *)eventType { + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"You must override getInitialEvent: when subclassing FEventEmitter" userInfo:nil]; +} + +- (void) triggerEventType:(NSString *)eventType data:(id)data { + [self validateEventType:eventType]; + NSMutableDictionary *eventTypeListeners = [self.listeners objectForKey:eventType]; + for (FEventListener *listener in eventTypeListeners) { + [self triggerListener:listener withData:data]; + } +} + +- (void) triggerListener:(FEventListener *)listener withData:(id)data { + // TODO, should probably get this from FRepo or something although it ends up being the same. (Except maybe for testing) + if (listener.userCallback) { + dispatch_async(self.queue, ^{ + listener.userCallback(data); + }); + } +} + +- (FIRDatabaseHandle)observeEventType:(NSString *)eventType withBlock:(fbt_void_id)block { + [self validateEventType:eventType]; + + // Create listener + FEventListener *listener = [[FEventListener alloc] init]; + listener.handle = [[FUtilities LUIDGenerator] integerValue]; + listener.userCallback = block; // copies block automatically + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self addEventListener:listener forEventType:eventType]; + }); + + return listener.handle; +} + +- (void) addEventListener:(FEventListener *)listener forEventType:(NSString *)eventType { + // Get or initializer listeners map [FIRDatabaseHandle -> callback block] for eventType + NSMutableArray *eventTypeListeners = [self.listeners objectForKey:eventType]; + if (eventTypeListeners == nil) { + eventTypeListeners = [[NSMutableArray alloc] init]; + [self.listeners setObject:eventTypeListeners forKey:eventType]; + } + + // Add listener and fire the current event for this listener + [eventTypeListeners addObject:listener]; + id initialData = [self getInitialEventForType:eventType]; + [self triggerListener:listener withData:initialData]; +} + +- (void) removeObserverForEventType:(NSString *)eventType withHandle:(FIRDatabaseHandle)handle { + [self validateEventType:eventType]; + + dispatch_async([FIRDatabaseQuery sharedQueue], ^{ + [self removeEventListenerWithHandle:handle forEventType:eventType]; + }); +} + +- (void)removeEventListenerWithHandle:(FIRDatabaseHandle)handle forEventType:(NSString *)eventType { + NSMutableArray *eventTypeListeners = [self.listeners objectForKey:eventType]; + for (FEventListener *listener in [eventTypeListeners copy]) { + if (handle == NSNotFound || handle == listener.handle) { + [eventTypeListeners removeObject:listener]; + } + } +} + + +- (void) validateEventType:(NSString *)eventType { + if ([self.allowedEvents indexOfObject:eventType] == NSNotFound) { + @throw [NSException exceptionWithName:@"InvalidEventType" + reason:[NSString stringWithFormat:@"%@ is not a valid event type. %@ is the list of valid events.", + eventType, self.allowedEvents] + userInfo:nil]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.h new file mode 100644 index 0000000..2da54f0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.h @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FNextPushId : NSObject + ++ (NSString *) get:(NSTimeInterval)now; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.m new file mode 100644 index 0000000..ee3ba13 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FNextPushId.m @@ -0,0 +1,63 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FNextPushId.h" +#import "FUtilities.h" + +static NSString *const PUSH_CHARS = @"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; + +@implementation FNextPushId + ++ (NSString *) get:(NSTimeInterval)currentTime { + static long long lastPushTime = 0; + static int lastRandChars[12]; + + long long now = (long long)(currentTime * 1000); + + BOOL duplicateTime = now == lastPushTime; + lastPushTime = now; + + unichar timeStampChars[8]; + for(int i = 7; i >= 0; i--) { + timeStampChars[i] = [PUSH_CHARS characterAtIndex:(now % 64)]; + now = (long long)floor(now / 64); + } + + NSMutableString* id = [[NSMutableString alloc] init]; + [id appendString:[NSString stringWithCharacters:timeStampChars length:8]]; + + + if(!duplicateTime) { + for(int i = 0; i < 12; i++) { + lastRandChars[i] = (int)floor(arc4random() % 64); + } + } + else { + int i = 0; + for(i = 11; i >= 0 && lastRandChars[i] == 63; i--) { + lastRandChars[i] = 0; + } + lastRandChars[i]++; + } + + for(int i = 0; i < 12; i++) { + [id appendFormat:@"%C", [PUSH_CHARS characterAtIndex:lastRandChars[i]]]; + } + + return [NSString stringWithString:id]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.h new file mode 100644 index 0000000..7145f86 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FRepoInfo.h" +#import "FPath.h" + +@interface FParsedUrl : NSObject + +@property (nonatomic, strong) FRepoInfo* repoInfo; +@property (nonatomic, strong) FPath* path; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.m new file mode 100644 index 0000000..eb83330 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FParsedUrl.m @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FParsedUrl.h" + +@implementation FParsedUrl + +@synthesize repoInfo; +@synthesize path; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.h new file mode 100644 index 0000000..34ac9af --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FStringUtilities : NSObject + ++ (NSString *) base64EncodedSha1:(NSString *)str; ++ (NSString *) urlDecoded:(NSString *)url; ++ (NSString *) urlEncoded:(NSString *)url; ++ (NSString *) sanitizedForUserAgent:(NSString *)str; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.m new file mode 100644 index 0000000..dff58e0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FStringUtilities.m @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FStringUtilities.h" +#import "NSData+SRB64Additions.h" + +@implementation FStringUtilities + +// http://stackoverflow.com/questions/3468268/objective-c-sha1 +// http://stackoverflow.com/questions/7310457/ios-objective-c-sha-1-and-base64-problem ++ (NSString *) base64EncodedSha1:(NSString *)str { + const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding]; + // NSString reports length in characters, but we want it in bytes, which strlen will give us. + unsigned long dataLen = strlen(cstr); + NSData *data = [NSData dataWithBytes:cstr length:dataLen]; + uint8_t digest[CC_SHA1_DIGEST_LENGTH]; + CC_SHA1(data.bytes, (unsigned int)data.length, digest); + NSData* output = [[NSData alloc] initWithBytes:digest length:CC_SHA1_DIGEST_LENGTH]; + return [FSRUtilities base64EncodedStringFromData:output]; +} + ++ (NSString *) urlDecoded:(NSString *)url { + NSString* replaced = [url stringByReplacingOccurrencesOfString:@"+" withString:@" "]; + NSString* decoded = [replaced stringByRemovingPercentEncoding]; + // This is kind of a hack, but is generally how the js client works. We could run into trouble if + // some piece is a correctly escaped %-sequence, and another isn't. But, that's bad input anyways... + if (decoded) { + return decoded; + } else { + return replaced; + } +} + ++ (NSString *) urlEncoded:(NSString *)url { + // Didn't seem like there was an Apple NSCharacterSet that had our version of the encoding + // So I made my own, following RFC 2396 https://www.ietf.org/rfc/rfc2396.txt + // allowedCharacters = alphanum | "-" | "_" | "~" + NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_~"]; + return [url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; +} + ++ (NSString *) sanitizedForUserAgent:(NSString *)str { + return [str stringByReplacingOccurrencesOfString:@"/|_" withString:@"|" options:NSRegularExpressionSearch range:NSMakeRange(0, [str length])]; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FTypedefs.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FTypedefs.h new file mode 100644 index 0000000..4a24ca5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FTypedefs.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#ifndef Firebase_FTypedefs_h +#define Firebase_FTypedefs_h + +/** + * Stub... + */ +@class FIRDataSnapshot; +@class FIRDatabaseReference; +@class FAuthData; +@protocol FNode; + +// fbt = Firebase Block Typedef + +typedef void (^fbt_void_void)(void); +typedef void (^fbt_void_datasnapshot_nsstring) (FIRDataSnapshot *snapshot, NSString *prevName); +typedef void (^fbt_void_datasnapshot) (FIRDataSnapshot *snapshot); +typedef void (^fbt_void_user)(FAuthData *user); +typedef void (^fbt_void_nsstring_id)(NSString* status, id data); +typedef void (^fbt_void_nserror_id)(NSError* error, id data); +typedef void (^fbt_void_nserror)(NSError *error); +typedef void (^fbt_void_nserror_ref)(NSError* error, FIRDatabaseReference * ref); +typedef void (^fbt_void_nserror_user)(NSError* error, FAuthData * user); +typedef void (^fbt_void_nserror_json)(NSError* error, NSDictionary* json); +typedef void (^fbt_void_nsdictionary)(NSDictionary *data); +typedef id (^fbt_id_node_nsstring)(id node, NSString* childName); + +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.h new file mode 100644 index 0000000..f7fe7a5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.h @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FParsedUrl.h" + +@interface FUtilities : NSObject + ++ (NSArray *) splitString:(NSString *)str intoMaxSize:(const unsigned int)size; ++ (NSNumber *) LUIDGenerator; ++ (FParsedUrl *) parseUrl:(NSString *)url; ++ (NSString *) getJavascriptType:(id)obj; ++ (NSError *) errorForStatus:(NSString *)status andReason:(NSString *)reason; ++ (NSNumber *) intForString:(NSString *)string; ++ (NSString *) ieee754StringForNumber:(NSNumber *)val; ++ (void) setLoggingEnabled:(BOOL)enabled; ++ (BOOL) getLoggingEnabled; + ++ (NSString*) minName; ++ (NSString*) maxName; ++ (NSComparisonResult) compareKey:(NSString *)a toKey:(NSString *)b; ++ (NSComparator) stringComparator; ++ (NSComparator) keyComparator; + ++ (double)randomDouble; + +@end + +typedef enum { + FLogLevelDebug = 1, + FLogLevelInfo = 2, + FLogLevelWarn = 3, + FLogLevelError = 4, + FLogLevelNone = 5 +} FLogLevel; + +// Log tags +FOUNDATION_EXPORT NSString *const kFPersistenceLogTag; + +#define FFLog(code, format, ...) FFDebug((code), (format), ##__VA_ARGS__) + +#define FFDebug(code, format, ...) do { \ + if (FFIsLoggingEnabled(FLogLevelDebug)) { \ + FIRLogDebug(kFIRLoggerDatabase, (code), (format), ##__VA_ARGS__); \ + } \ +} while(0) + +#define FFInfo(code, format, ...) do { \ + if (FFIsLoggingEnabled(FLogLevelInfo)) { \ + FIRLogError(kFIRLoggerDatabase, (code), (format), ##__VA_ARGS__); \ + } \ +} while(0) + +#define FFWarn(code, format, ...) do { \ + if (FFIsLoggingEnabled(FLogLevelWarn)) { \ + FIRLogWarning(kFIRLoggerDatabase, (code), (format), ##__VA_ARGS__); \ + } \ +} while(0) + +BOOL FFIsLoggingEnabled(FLogLevel logLevel); +void firebaseUncaughtExceptionHandler(NSException *exception); +void firebaseJobsTroll(void); diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.m new file mode 100644 index 0000000..d0a9a43 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FUtilities.m @@ -0,0 +1,390 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FUtilities.h" +#import "FStringUtilities.h" +#import "FConstants.h" +#import "FAtomicNumber.h" + +#define ARC4RANDOM_MAX 0x100000000 +#define INTEGER_32_MIN (-2147483648) +#define INTEGER_32_MAX 2147483647 + +#pragma mark - +#pragma mark C functions + +static FLogLevel logLevel = FLogLevelInfo; // Default log level is info +static NSMutableDictionary* options = nil; + +BOOL FFIsLoggingEnabled(FLogLevel level) { + return level >= logLevel; +} + +void firebaseJobsTroll(void) { + FFLog(@"I-RDB095001", @"password super secret; JFK conspiracy; Hello there! Having fun digging through Firebase? We're always hiring! jobs@firebase.com"); +} + +#pragma mark - +#pragma mark Private property and singleton specification + +@interface FUtilities() { + +} + +@property (nonatomic, strong) FAtomicNumber* localUid; + ++ (FUtilities*)singleton; + +@end + +@implementation FUtilities + +@synthesize localUid; + +- (id)init +{ + self = [super init]; + if (self) { + self.localUid = [[FAtomicNumber alloc] init]; + } + return self; +} + +// TODO: We really want to be able to set the log level ++ (void) setLoggingEnabled:(BOOL)enabled { + logLevel = enabled ? FLogLevelDebug : FLogLevelInfo; +} + ++ (BOOL) getLoggingEnabled { + return logLevel == FLogLevelDebug; +} + ++ (FUtilities*) singleton +{ + static dispatch_once_t pred = 0; + __strong static id _sharedObject = nil; + dispatch_once(&pred, ^{ + _sharedObject = [[self alloc] init]; // or some other init method + }); + return _sharedObject; +} + +// Refactor as a category of NSString ++ (NSArray *) splitString:(NSString *) str intoMaxSize:(const unsigned int) size { + if(str.length <= size) { + return [NSArray arrayWithObject:str]; + } + + NSMutableArray* dataSegs = [[NSMutableArray alloc] init]; + for(int c = 0; c < str.length; c += size) { + if (c + size > str.length) { + int rangeStart = c; + unsigned long rangeLength = size - ((c + size) - str.length); + [dataSegs addObject:[str substringWithRange:NSMakeRange(rangeStart, rangeLength)]]; + } + else { + int rangeStart = c; + int rangeLength = size; + [dataSegs addObject:[str substringWithRange:NSMakeRange(rangeStart, rangeLength)]]; + } + } + return dataSegs; +} + ++ (NSNumber *) LUIDGenerator { + FUtilities* f = [FUtilities singleton]; + return [f.localUid getAndIncrement]; +} + ++ (NSString *) decodePath:(NSString *)pathString { + NSMutableArray* decodedPieces = [[NSMutableArray alloc] init]; + NSArray* pieces = [pathString componentsSeparatedByString:@"/"]; + for (NSString* piece in pieces) { + if (piece.length > 0) { + [decodedPieces addObject:[FStringUtilities urlDecoded:piece]]; + } + } + return [NSString stringWithFormat:@"/%@", [decodedPieces componentsJoinedByString:@"/"]]; +} + ++ (FParsedUrl *) parseUrl:(NSString *)url { + NSString* original = url; + //NSURL* n = [[NSURL alloc] initWithString:url] + + NSString* host; + NSString* namespace; + bool secure; + + NSString* scheme = nil; + FPath* path = nil; + NSRange colonIndex = [url rangeOfString:@"//"]; + if (colonIndex.location != NSNotFound) { + scheme = [url substringToIndex:colonIndex.location - 1]; + url = [url substringFromIndex:colonIndex.location + 2]; + } + NSInteger slashIndex = [url rangeOfString:@"/"].location; + if (slashIndex == NSNotFound) { + slashIndex = url.length; + } + + host = [[url substringToIndex:slashIndex] lowercaseString]; + if (slashIndex >= url.length) { + url = @""; + } else { + url = [url substringFromIndex:slashIndex + 1]; + } + + NSArray *parts = [host componentsSeparatedByString:@"."]; + if([parts count] == 3) { + NSInteger colonIndex = [[parts objectAtIndex:2] rangeOfString:@":"].location; + if (colonIndex != NSNotFound) { + // we have a port, use the provided scheme + secure = [scheme isEqualToString:@"https"]; + } else { + secure = YES; + } + + namespace = [[parts objectAtIndex:0] lowercaseString]; + NSString* pathString = [self decodePath:[NSString stringWithFormat:@"/%@", url]]; + path = [[FPath alloc] initWith:pathString]; + } + else { + [NSException raise:@"No Firebase database specified." format:@"No Firebase database found for input: %@", url]; + } + + FRepoInfo* repoInfo = [[FRepoInfo alloc] initWithHost:host isSecure:secure withNamespace:namespace]; + + FFLog(@"I-RDB095002", @"---> Parsed (%@) to: (%@,%@); ns=(%@); path=(%@)", original, [repoInfo description], [repoInfo connectionURL], repoInfo.namespace, [path description]); + + FParsedUrl* parsedUrl = [[FParsedUrl alloc] init]; + parsedUrl.repoInfo = repoInfo; + parsedUrl.path = path; + + return parsedUrl; +} + +/* + case str: JString => priString + "string:" + str.s; + case bool: JBool => priString + "boolean:" + bool.value; + case double: JDouble => priString + "number:" + double.num; + case int: JInt => priString + "number:" + int.num; + case _ => { + error("Leaf node has value '" + data.value + "' of invalid type '" + data.value.getClass.toString + "'"); + ""; + } + */ + ++ (NSString *) getJavascriptType:(id)obj { + if ([obj isKindOfClass:[NSDictionary class]]) { + return kJavaScriptObject; + } else if([obj isKindOfClass:[NSString class]]) { + return kJavaScriptString; + } + else if ([obj isKindOfClass:[NSNumber class]]) { + // We used to just compare to @encode(BOOL) as suggested at + // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber, but on arm64, @encode(BOOL) returns "B" + // instead of "c" even though objCType still returns 'c' (signed char). So check both. + if(strcmp([obj objCType], @encode(BOOL)) == 0 || + strcmp([obj objCType], @encode(signed char)) == 0) { + return kJavaScriptBoolean; + } + else { + return kJavaScriptNumber; + } + } + else { + return kJavaScriptNull; + } +} + ++ (NSError *) errorForStatus:(NSString *)status andReason:(NSString *)reason { + static dispatch_once_t pred = 0; + __strong static NSDictionary* errorMap = nil; + __strong static NSDictionary* errorCodes = nil; + dispatch_once(&pred, ^{ + errorMap = @{ + @"permission_denied": @"Permission Denied", + @"unavailable": @"Service is unavailable", + kFErrorWriteCanceled: @"Write cancelled by user" + }; + errorCodes = @{ + @"permission_denied": @1, + @"unavailable": @2, + kFErrorWriteCanceled: @3 + }; + }); + + if ([status isEqualToString:kFWPResponseForActionStatusOk]) { + return nil; + } else { + NSInteger code; + NSString* desc = nil; + if (reason) { + desc = reason; + } else if ([errorMap objectForKey:status] != nil) { + desc = [errorMap objectForKey:status]; + } else { + desc = status; + } + + if ([errorCodes objectForKey:status] != nil) { + NSNumber* num = [errorCodes objectForKey:status]; + code = [num integerValue]; + } else { + // XXX what to do here? + code = 9999; + } + + return [[NSError alloc] initWithDomain:kFErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey: desc}]; + } +} + ++ (NSNumber *) intForString:(NSString *)string { + static NSCharacterSet *notDigits = nil; + if (!notDigits) { + notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; + } + if ([string rangeOfCharacterFromSet:notDigits].length == 0) { + NSInteger num; + NSScanner* scanner = [NSScanner scannerWithString:string]; + if ([scanner scanInteger:&num]) { + return [NSNumber numberWithInteger:num]; + } + } + return nil; +} + ++ (NSString *) ieee754StringForNumber:(NSNumber *)val { + double d = [val doubleValue]; + NSData* data = [NSData dataWithBytes:&d length:sizeof(double)]; + NSMutableString* str = [[NSMutableString alloc] init]; + const unsigned char* buffer = (const unsigned char*)[data bytes]; + for (int i = 0; i < data.length; i++) { + unsigned char byte = buffer[7 - i]; + [str appendFormat:@"%02x", byte]; + } + return str; +} + +static inline BOOL tryParseStringToInt(__unsafe_unretained NSString* str, NSInteger* integer) { + // First do some cheap checks (NOTE: The below checks are significantly faster than an equivalent regex :-( ). + NSUInteger length = str.length; + if (length > 11 || length == 0) { + return NO; + } + long long value = 0; + BOOL negative = NO; + NSUInteger i = 0; + if ([str characterAtIndex:0] == '-') { + if (length == 1) { + return NO; + } + negative = YES; + i = 1; + } + for(; i < length; i++) { + unichar c = [str characterAtIndex:i]; + // Must be a digit, or '-' if it's the first char. + if (c < '0' || c > '9') { + return NO; + } else { + int charValue = c - '0'; + value = value*10 + charValue; + } + } + + value = (negative) ? -value : value; + + if (value < INTEGER_32_MIN || value > INTEGER_32_MAX) { + return NO; + } else { + *integer = (NSInteger)value; + return YES; + } +} + ++ (NSString *) maxName { + static dispatch_once_t once; + static NSString *maxName; + dispatch_once(&once, ^{ + maxName = [[NSString alloc] initWithFormat:@"[MAX_NAME]"]; + }); + return maxName; +} + ++ (NSString *) minName { + static dispatch_once_t once; + static NSString *minName; + dispatch_once(&once, ^{ + minName = [[NSString alloc] initWithFormat:@"[MIN_NAME]"]; + }); + return minName; +} + ++ (NSComparisonResult) compareKey:(NSString *)a toKey:(NSString *)b { + if (a == b) { + return NSOrderedSame; + } else if (a == [FUtilities minName] || b == [FUtilities maxName]) { + return NSOrderedAscending; + } else if (b == [FUtilities minName] || a == [FUtilities maxName]) { + return NSOrderedDescending; + } else { + NSInteger aAsInt, bAsInt; + if (tryParseStringToInt(a, &aAsInt)) { + if (tryParseStringToInt(b, &bAsInt)) { + if (aAsInt > bAsInt) { + return NSOrderedDescending; + } else if (aAsInt < bAsInt) { + return NSOrderedAscending; + } else if (a.length > b.length) { + return NSOrderedDescending; + } else if (a.length < b.length) { + return NSOrderedAscending; + } else { + return NSOrderedSame; + } + } else { + return (NSComparisonResult) NSOrderedAscending; + } + } else if (tryParseStringToInt(b, &bAsInt)) { + return (NSComparisonResult) NSOrderedDescending; + } else { + // Perform literal character by character search to prevent a > b && b > a issues. + // Note that calling -(NSString *)decomposedStringWithCanonicalMapping also works. + return [a compare:b options:NSLiteralSearch]; + } + } +} + ++ (NSComparator) keyComparator { + return ^NSComparisonResult(__unsafe_unretained NSString *a, __unsafe_unretained NSString *b) { + return [FUtilities compareKey:a toKey:b]; + }; +} + ++ (NSComparator) stringComparator { + return ^NSComparisonResult(__unsafe_unretained NSString *a, __unsafe_unretained NSString *b) { + return [a compare:b]; + }; +} + ++ (double) randomDouble { + return ((double) arc4random() / ARC4RANDOM_MAX); +} + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.h new file mode 100644 index 0000000..faa8f76 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" +#import "FIRDataEventType.h" +#import "FParsedUrl.h" +#import "FTypedefs.h" + +@interface FValidation : NSObject + ++ (void) validateFrom:(NSString *)fn writablePath:(FPath *)path; ++ (void) validateFrom:(NSString *)fn knownEventType:(FIRDataEventType)event; ++ (void) validateFrom:(NSString *)fn validPathString:(NSString *)pathString; ++ (void) validateFrom:(NSString *)fn validRootPathString:(NSString *)pathString; ++ (void) validateFrom:(NSString *)fn validKey:(NSString *)key; ++ (void) validateFrom:(NSString *)fn validURL:(FParsedUrl *)parsedUrl; + ++ (void) validateToken:(NSString *)token; + +// Functions for handling passing errors back ++ (void) handleError:(NSError *)error withUserCallback:(fbt_void_nserror_id)userCallback; ++ (void) handleError:(NSError *)error withSuccessCallback:(fbt_void_nserror)userCallback; + +// Functions used for validating while creating snapshots in FSnapshotUtilities ++ (BOOL) validateFrom:(NSString*)fn isValidLeafValue:(id)value withPath:(NSArray*)path; ++ (void) validateFrom:(NSString*)fn validDictionaryKey:(id)keyId withPath:(NSArray*)path; ++ (void) validateFrom:(NSString*)fn validUpdateDictionaryKey:(id)keyId withValue:(id)value; ++ (void) validateFrom:(NSString*)fn isValidPriorityValue:(id)value withPath:(NSArray*)path; ++ (BOOL) validatePriorityValue:value; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.m new file mode 100644 index 0000000..f088da2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/FValidation.m @@ -0,0 +1,312 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FValidation.h" +#import "FConstants.h" +#import "FParsedUrl.h" +#import "FTypedefs.h" + + +// Have to escape: * ? + [ ( ) { } ^ $ | \ . / +// See: https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html + +NSString *const kInvalidPathCharacters = @"[].#$"; +NSString *const kInvalidKeyCharacters = @"[].#$/"; + +@implementation FValidation + ++ (void) validateFrom:(NSString *)fn writablePath:(FPath *)path { + if([[path getFront] isEqualToString:kDotInfoPrefix]) { + @throw [[NSException alloc] initWithName:@"WritablePathValidation" reason:[NSString stringWithFormat:@"(%@) failed to path %@: Can't modify data under %@", fn, [path description], kDotInfoPrefix] userInfo:nil]; + } +} + ++ (void) validateFrom:(NSString*)fn knownEventType:(FIRDataEventType)event { + switch (event) { + case FIRDataEventTypeValue: + case FIRDataEventTypeChildAdded: + case FIRDataEventTypeChildChanged: + case FIRDataEventTypeChildMoved: + case FIRDataEventTypeChildRemoved: + return; + break; + default: + @throw [[NSException alloc] initWithName:@"KnownEventTypeValidation" reason:[NSString stringWithFormat:@"(%@) Unknown event type: %d", fn, (int) event] userInfo:nil]; + break; + } +} + ++ (BOOL) isValidPathString:(NSString *)pathString { + static dispatch_once_t token; + static NSCharacterSet *badPathChars = nil; + dispatch_once(&token, ^{ + badPathChars = [NSCharacterSet characterSetWithCharactersInString:kInvalidPathCharacters]; + }); + return pathString != nil && [pathString length] != 0 && + [pathString rangeOfCharacterFromSet:badPathChars].location == NSNotFound; +} + ++ (void) validateFrom:(NSString *)fn validPathString:(NSString *)pathString { + if(! [self isValidPathString:pathString]) { + @throw [[NSException alloc] initWithName:@"InvalidPathValidation" reason:[NSString stringWithFormat:@"(%@) Must be a non-empty string and not contain '.' '#' '$' '[' or ']'", fn] userInfo:nil]; + } +} + ++ (void) validateFrom:(NSString *)fn validRootPathString:(NSString *)pathString { + static dispatch_once_t token; + static NSRegularExpression *dotInfoRegex = nil; + dispatch_once(&token, ^{ + dotInfoRegex = [NSRegularExpression regularExpressionWithPattern:@"^\\/*\\.info(\\/|$)" options:0 error:nil]; + }); + + NSString *tempPath = pathString; + // HACK: Obj-C regex are kinda' slow. Do a plain string search first before bothering with the regex. + if ([pathString rangeOfString:@".info"].location != NSNotFound) { + tempPath = [dotInfoRegex stringByReplacingMatchesInString:pathString options:0 range:NSMakeRange(0, pathString.length) withTemplate:@"/"]; + } + [self validateFrom:fn validPathString:tempPath]; +} + ++ (BOOL) isValidKey:(NSString *)key { + static dispatch_once_t token; + static NSCharacterSet *badKeyChars = nil; + dispatch_once(&token, ^{ + badKeyChars = [NSCharacterSet characterSetWithCharactersInString:kInvalidKeyCharacters]; + }); + return key != nil && key.length > 0 && [key rangeOfCharacterFromSet:badKeyChars].location == NSNotFound; +} + ++ (void) validateFrom:(NSString *)fn validKey:(NSString *)key { + if (![self isValidKey:key]) { + @throw [[NSException alloc] initWithName:@"InvalidKeyValidation" reason:[NSString stringWithFormat:@"(%@) Must be a non-empty string and not contain '/' '.' '#' '$' '[' or ']'", fn] userInfo:nil]; + } +} + ++ (void) validateFrom:(NSString *)fn validURL:(FParsedUrl *)parsedUrl { + NSString* pathString = [parsedUrl.path description]; + [self validateFrom:fn validRootPathString:pathString]; +} + +#pragma mark - +#pragma mark Authentication validation + ++ (BOOL) stringNonempty:(NSString *)str { + return str != nil && ![str isKindOfClass:[NSNull class]] && str.length > 0; +} + ++ (void) validateToken:(NSString *)token { + if (![FValidation stringNonempty:token]) { + [NSException raise:NSInvalidArgumentException format:@"Can't have empty string or nil for custom token"]; + } +} + +#pragma mark - +#pragma mark Handling authentication errors + +/** +* This function immediately calls the callback. +* It assumes that it is not on FirebaseWorker thread. +* It assumes it's on a user-controlled thread. +*/ ++ (void) handleError:(NSError *)error withUserCallback:(fbt_void_nserror_id)userCallback { + if (userCallback) { + userCallback(error, nil); + } +} + +/** +* This function immediately calls the callback. +* It assumes that it is not on FirebaseWorker thread. +* It assumes it's on a user-controlled thread. +*/ ++ (void) handleError:(NSError *)error withSuccessCallback:(fbt_void_nserror)userCallback { + if (userCallback) { + userCallback(error); + } +} + +#pragma mark - +#pragma mark Snapshot validation + ++ (BOOL) validateFrom:(NSString*)fn isValidLeafValue:(id)value withPath:(NSArray*)path { + if ([value isKindOfClass:[NSString class]]) { + // Try to avoid conversion to bytes if possible + NSString* theString = value; + if ([theString maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] > kFirebaseMaxLeafSize && + [theString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > kFirebaseMaxLeafSize) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) String exceeds max size of %u utf8 bytes: %@", fn, (int)kFirebaseMaxLeafSize, pathString] userInfo:nil]; + } + return YES; + } + + else if ([value isKindOfClass:[NSNumber class]]) { + // Cannot store NaN, but otherwise can store NSNumbers. + if ([[NSDecimalNumber notANumber] isEqualToNumber:value]) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store NaN at path: %@.", fn, pathString] userInfo:nil]; + } + return YES; + } + + else if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary* dval = value; + if (dval[kServerValueSubKey] != nil) { + if ([dval count] > 1) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store other keys with server value keys.%@.", fn, pathString] userInfo:nil]; + } + return YES; + } + return NO; + } + + else if (value == [NSNull null] || value == nil) { + // Null is valid type to store at leaf + return YES; + } + + return NO; +} + ++ (NSString*) parseAndValidateKey:(id)keyId fromFunction:(NSString*)fn path:(NSArray*)path { + if (![keyId isKindOfClass:[NSString class]]) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString* pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Non-string keys are not allowed in object at path: %@", fn, pathString] userInfo:nil]; + } + return (NSString*)keyId; +} + ++ (void) validateFrom:(NSString*)fn validDictionaryKey:(id)keyId withPath:(NSArray*)path { + NSString *key = [self parseAndValidateKey:keyId fromFunction:fn path:path]; + if (![key isEqualToString:kPayloadPriority] && ![key isEqualToString:kPayloadValue] && ![key isEqualToString:kServerValueSubKey] && ![FValidation isValidKey:key]) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Invalid key in object at path: %@. Keys must be non-empty and cannot contain '/' '.' '#' '$' '[' or ']'", fn, pathString] userInfo:nil]; + } +} + ++ (void) validateFrom:(NSString*)fn validUpdateDictionaryKey:(id)keyId withValue:(id)value { + FPath *path = [FPath pathWithString:[self parseAndValidateKey:keyId fromFunction:fn path:@[]]]; + __block NSInteger keyNum = 0; + [path enumerateComponentsUsingBlock:^void (NSString *key, BOOL *stop) { + if ([key isEqualToString:kPayloadPriority] && keyNum == [path length] - 1) { + [self validateFrom:fn isValidPriorityValue:value withPath:@[]]; + } else { + keyNum++; + + if (![FValidation isValidKey:key]) { + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Invalid key in object. Keys must be non-empty and cannot contain '.' '#' '$' '[' or ']'", fn] userInfo:nil]; + } + } + }]; +} + ++ (void) validateFrom:(NSString*)fn isValidPriorityValue:(id)value withPath:(NSArray*)path { + [self validateFrom:fn isValidPriorityValue:value withPath:path throwError:YES]; +} + +/** +* Returns YES if priority is valid. +*/ ++ (BOOL)validatePriorityValue:value { + return [self validateFrom:nil isValidPriorityValue:value withPath:nil throwError:NO]; +} + +/** +* Helper for validating priorities. If passed YES for throwError, it'll throw descriptive errors on validation +* problems. Else, it'll just return YES/NO. +*/ ++ (BOOL) validateFrom:(NSString*)fn isValidPriorityValue:(id)value withPath:(NSArray*)path throwError:(BOOL)throwError { + if ([value isKindOfClass:[NSNumber class]]) { + if ([[NSDecimalNumber notANumber] isEqualToNumber:value]) { + if (throwError) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store NaN as priority at path: %@.", fn, pathString] userInfo:nil]; + } else { + return NO; + } + } else if (value == (id) kCFBooleanFalse || value == (id) kCFBooleanTrue) { + if (throwError) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store true/false as priority at path: %@.", fn, pathString] userInfo:nil]; + } else { + return NO; + } + } + } + else if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dval = value; + if (dval[kServerValueSubKey] != nil) { + if ([dval count] > 1) { + if (throwError) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store other keys with server value keys as priority at path: %@.", fn, pathString] userInfo:nil]; + } else { + return NO; + } + } + } else { + if (throwError) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store an NSDictionary as priority at path: %@.", fn, pathString] userInfo:nil]; + } else { + return NO; + } + } + } + else if ([value isKindOfClass:[NSArray class]]) { + if (throwError) { + NSRange range; + range.location = 0; + range.length = MIN(path.count, 50); + NSString *pathString = [[path subarrayWithRange:range] componentsJoinedByString:@"."]; + @throw [[NSException alloc] initWithName:@"InvalidFirebaseData" reason:[NSString stringWithFormat:@"(%@) Cannot store an NSArray as priority at path: %@.", fn, pathString] userInfo:nil]; + } else { + return NO; + } + } + + // It's valid! + return YES; +} +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.h new file mode 100644 index 0000000..bceeed2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTypedefs.h" + +@interface FTupleBoolBlock : NSObject + +@property (nonatomic, readwrite) BOOL boolean; +@property (nonatomic, copy) fbt_void_void block; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.m new file mode 100644 index 0000000..c4cd8bf --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleBoolBlock.m @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleBoolBlock.h" + +@implementation FTupleBoolBlock + +@synthesize boolean; +@synthesize block; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.h new file mode 100644 index 0000000..6ec2375 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.h @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTypedefs_Private.h" + +@interface FTupleCallbackStatus : NSObject +@property (nonatomic, copy) fbt_void_nsstring_nsstring block; +@property (nonatomic) NSString* status; +@property (nonatomic) NSString* errorReason; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.m new file mode 100644 index 0000000..05914bf --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.m @@ -0,0 +1,22 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleCallbackStatus.h" + +@implementation FTupleCallbackStatus +@synthesize block; +@synthesize status; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.h new file mode 100644 index 0000000..ff84bbb --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FIRDatabaseReference.h" + +@interface FTupleFirebase : NSObject + +@property (nonatomic, strong) FIRDatabaseReference * one; +@property (nonatomic, strong) FIRDatabaseReference * two; +@property (nonatomic, strong) FIRDatabaseReference * three; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.m new file mode 100644 index 0000000..3956f8b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleFirebase.m @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleFirebase.h" + +@implementation FTupleFirebase + +@synthesize one; +@synthesize two; +@synthesize three; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.h new file mode 100644 index 0000000..fbf62c7 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" +#import "FNode.h" + +@interface FTupleNodePath : NSObject + +@property (nonatomic, strong) FPath* path; +@property (nonatomic, strong) id node; + +- (id) initWithNode:(id)aNode andPath:(FPath *)aPath; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.m new file mode 100644 index 0000000..eefc0c2 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleNodePath.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleNodePath.h" + +@implementation FTupleNodePath + +@synthesize path; +@synthesize node; + +- (id) initWithNode:(id)aNode andPath:(FPath *)aPath { + self = [super init]; + if (self) { + self.path = aPath; + self.node = aNode; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.h new file mode 100644 index 0000000..6fcb746 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@interface FTupleObjectNode : NSObject + +- (id)initWithObject:(id)aObj andNode:(id)aNode; + +@property (nonatomic, strong) id node; +@property (nonatomic, strong) id obj; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.m new file mode 100644 index 0000000..4c533b0 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjectNode.m @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#import "FTupleObjectNode.h" + +@implementation FTupleObjectNode + +@synthesize obj; +@synthesize node; + +- (id)initWithObject:(id)aObj andNode:(id)aNode { + self = [super init]; + if (self) { + self.obj = aObj; + self.node = aNode; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.h new file mode 100644 index 0000000..4ff1fcf --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.h @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FTupleObjects : NSObject + +@property (nonatomic, strong) id objA; +@property (nonatomic, strong) id objB; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.m new file mode 100644 index 0000000..a9e4c88 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleObjects.m @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleObjects.h" + +@implementation FTupleObjects + +@synthesize objA; +@synthesize objB; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.h new file mode 100644 index 0000000..91ad5e4 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTypedefs_Private.h" + +@interface FTupleOnDisconnect : NSObject + +@property (strong, nonatomic) NSString* pathString; +@property (strong, nonatomic) NSString* action; +@property (strong, nonatomic) id data; +@property (strong, nonatomic) fbt_void_nsstring_nsstring onComplete; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.m new file mode 100644 index 0000000..bd45822 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.m @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleOnDisconnect.h" + +@implementation FTupleOnDisconnect + +@synthesize pathString; +@synthesize action; +@synthesize data; +@synthesize onComplete; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.h new file mode 100644 index 0000000..f7ed423 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FPath; + +@interface FTuplePathValue : NSObject +@property (nonatomic, strong, readonly) FPath *path; +@property (nonatomic, strong, readonly) id value; +- (id) initWithPath:(FPath *)aPath value:(id)aValue; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.m new file mode 100644 index 0000000..49240aa --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTuplePathValue.m @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTuplePathValue.h" +#import "FPath.h" + +@interface FTuplePathValue () +@property (nonatomic, strong, readwrite) id value; +@property (nonatomic, strong, readwrite) FPath *path; +@end + +@implementation FTuplePathValue +@synthesize path; +@synthesize value; + +- (id) initWithPath:(FPath *)aPath value:(id)aValue { + self = [super init]; + if (self) { + self.value = aValue; + self.path = aPath; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.h new file mode 100644 index 0000000..f986916 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FTupleRemovedQueriesEvents : NSObject +/** +* `FIRDatabaseQuery`s removed with [SyncPoint removeEventRegistration:] +*/ +@property (nonatomic, strong, readonly) NSArray *removedQueries; +/** +* cancel events as FEvent +*/ +@property (nonatomic, strong, readonly) NSArray *cancelEvents; + +- (id) initWithRemovedQueries:(NSArray *)removed cancelEvents:(NSArray *)events; +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.m new file mode 100644 index 0000000..818d16b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.m @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleRemovedQueriesEvents.h" + +@interface FTupleRemovedQueriesEvents () +@property (nonatomic, strong, readwrite) NSArray *removedQueries; +@property (nonatomic, strong, readwrite) NSArray *cancelEvents; +@end + +@implementation FTupleRemovedQueriesEvents +@synthesize removedQueries; +@synthesize cancelEvents; + +- (id) initWithRemovedQueries:(NSArray *)removed cancelEvents:(NSArray *)events { + self = [super init]; + if (self) { + self.removedQueries = removed; + self.cancelEvents = events; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.h new file mode 100644 index 0000000..5133d6d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" + +@interface FTupleSetIdPath : NSObject + +- (id) initWithSetId:(NSNumber *)aSetId andPath:(FPath *)aPath; + +@property (strong, nonatomic) NSNumber* setId; +@property (strong, nonatomic) FPath* path; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.m new file mode 100644 index 0000000..5d3312b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleSetIdPath.m @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleSetIdPath.h" + +@implementation FTupleSetIdPath + +@synthesize path; +@synthesize setId; + +- (id) initWithSetId:(NSNumber *)aSetId andPath:(FPath *)aPath { + self = [super init]; + if (self) { + self.setId = aSetId; + self.path = aPath; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.h new file mode 100644 index 0000000..e3fec80 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FNode.h" + +@interface FTupleStringNode : NSObject + +- (id)initWithString:(NSString *)aString andNode:(id)aNode; + +@property (nonatomic, strong) id node; +@property (nonatomic, strong) NSString* string; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.m new file mode 100644 index 0000000..f058a8e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleStringNode.m @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleStringNode.h" + +@implementation FTupleStringNode + +@synthesize string; +@synthesize node; + +- (id)initWithString:(NSString *)aString andNode:(id)aNode { + self = [super init]; + if (self) { + self.string = aString; + self.node = aNode; + } + return self; +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.h new file mode 100644 index 0000000..bc62b2d --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTupleStringNode.h" + +@interface FTupleTSN : NSObject + +@property (nonatomic, strong) FTupleStringNode* from; +@property (nonatomic, strong) FTupleStringNode* to; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.m new file mode 100644 index 0000000..348c319 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTSN.m @@ -0,0 +1,24 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleTSN.h" + +@implementation FTupleTSN + +@synthesize from; +@synthesize to; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.h new file mode 100644 index 0000000..c9dcf4b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.h @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FPath.h" +#import "FTypedefs_Private.h" +#import "FTypedefs.h" + +@interface FTupleTransaction : NSObject + +@property (nonatomic, strong) FPath* path; +@property (nonatomic, copy) fbt_transactionresult_mutabledata update; +@property (nonatomic, copy) fbt_void_nserror_bool_datasnapshot onComplete; +@property (nonatomic) FTransactionStatus status; + +/** +* Used when combining transaction at different locations to figure out which one goes first. +*/ +@property (nonatomic, strong) NSNumber* order; +/** +* Whether to raise local events for this transaction +*/ +@property (nonatomic) BOOL applyLocally; + +/** +* Count how many times we've retried the transaction +*/ +@property (nonatomic) int retryCount; + +/** +* Function to call to clean up our listener +*/ +@property (nonatomic, copy) fbt_void_void unwatcher; + +/** +* Stores why a transaction was aborted +*/ +@property (nonatomic, strong, readonly) NSString* abortStatus; +@property (nonatomic, strong, readonly) NSString* abortReason; + +- (void)setAbortStatus:(NSString *)abortStatus reason:(NSString *)reason; +- (NSError *)abortError; + +@property (nonatomic, strong) NSNumber *currentWriteId; + +/** +* Stores the input snapshot, before the update +*/ +@property (nonatomic, strong) id currentInputSnapshot; + +/** +* Stores the unresolved (for server values) output snapshot, after the update +*/ +@property (nonatomic, strong) id currentOutputSnapshotRaw; + +/** + * Stores the resolved (for server values) output snapshot, after the update + */ +@property (nonatomic, strong) id currentOutputSnapshotResolved; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.m new file mode 100644 index 0000000..bcff54e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleTransaction.m @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleTransaction.h" +#import "FUtilities.h" + +@interface FTupleTransaction () + +@property (nonatomic, strong) NSString *abortStatus; +@property (nonatomic, strong) NSString *abortReason; + +@end + +@implementation FTupleTransaction + +- (void)setAbortStatus:(NSString *)abortStatus reason:(NSString *)reason { + self.abortStatus = abortStatus; + self.abortReason = reason; +} + +- (NSError *)abortError { + return (self.abortStatus != nil) ? [FUtilities errorForStatus:self.abortStatus andReason:self.abortReason] : nil; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.h new file mode 100644 index 0000000..d598217 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.h @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "FTypedefs.h" +#import "FQueryParams.h" + +@interface FTupleUserCallback : NSObject + +- (id) initWithHandle:(NSUInteger)handle; + +@property (nonatomic, copy) fbt_void_datasnapshot_nsstring datasnapshotPrevnameCallback; +@property (nonatomic, copy) fbt_void_datasnapshot datasnapshotCallback; +@property (nonatomic, copy) fbt_void_nserror cancelCallback; +@property (nonatomic, copy) FQueryParams* queryParams; +@property (nonatomic) NSUInteger handle; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.m new file mode 100644 index 0000000..dc33bbd --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/Utilities/Tuples/FTupleUserCallback.m @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FTupleUserCallback.h" + +@implementation FTupleUserCallback + +@synthesize datasnapshotCallback; +@synthesize datasnapshotPrevnameCallback; +@synthesize cancelCallback; +@synthesize queryParams; +@synthesize handle; + +- (id) initWithHandle:(NSUInteger)theHandle { + self = [super init]; + if (self) { + self.handle = theHandle; + } + return self; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.h new file mode 100644 index 0000000..3ab7476 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.h @@ -0,0 +1,21 @@ +#import +#import "FImmutableSortedDictionary.h" + +/** + * This is an array backed implementation of FImmutableSortedDictionary. It uses arrays and linear lookups to achieve + * good memory efficiency while maintaining good performance for small collections. It also uses less allocations than + * a comparable red black tree. To avoid degrading performance with increasing collection size it will automatically + * convert to a FTreeSortedDictionary after an insert call above a certain threshold. + */ +@interface FArraySortedDictionary : FImmutableSortedDictionary + ++ (FArraySortedDictionary *)fromDictionary:(NSDictionary *)dictionary withComparator:(NSComparator)comparator; + +- (id)initWithComparator:(NSComparator)comparator; + +#pragma mark - +#pragma mark Properties + +@property (nonatomic, copy, readonly) NSComparator comparator; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.m new file mode 100644 index 0000000..15d2d8b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.m @@ -0,0 +1,266 @@ +#import "FArraySortedDictionary.h" +#import "FTreeSortedDictionary.h" + +@interface FArraySortedDictionaryEnumerator : NSEnumerator + +- (id)initWithKeys:(NSArray *)keys startPos:(NSInteger)pos isReverse:(BOOL)reverse; +- (id)nextObject; + +@property (nonatomic) NSInteger pos; +@property (nonatomic) BOOL reverse; +@property (nonatomic, strong) NSArray *keys; + +@end + +@implementation FArraySortedDictionaryEnumerator + +- (id)initWithKeys:(NSArray *)keys startPos:(NSInteger)pos isReverse:(BOOL)reverse +{ + self = [super init]; + if (self != nil) { + self->_pos = pos; + self->_reverse = reverse; + self->_keys = keys; + } + return self; +} + +- (id)nextObject +{ + NSInteger pos = self->_pos; + if (pos >= 0 && pos < self.keys.count) { + if (self.reverse) { + self->_pos--; + } else { + self->_pos++; + } + return self.keys[pos]; + } else { + return nil; + } +} + +@end + +@interface FArraySortedDictionary () + +- (id)initWithComparator:(NSComparator)comparator; + +@property (nonatomic, copy, readwrite) NSComparator comparator; +@property (nonatomic, strong) NSArray *keys; +@property (nonatomic, strong) NSArray *values; + +@end + +@implementation FArraySortedDictionary + ++ (FArraySortedDictionary *)fromDictionary:(NSDictionary *)dictionary withComparator:(NSComparator)comparator +{ + NSMutableArray *keys = [NSMutableArray arrayWithCapacity:dictionary.count]; + [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [keys addObject:key]; + }]; + [keys sortUsingComparator:comparator]; + + [keys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (idx > 0) { + if (comparator(keys[idx - 1], obj) != NSOrderedAscending) { + [NSException raise:NSInvalidArgumentException format:@"Can't create FImmutableSortedDictionary with keys with same ordering!"]; + } + } + }]; + + NSMutableArray *values = [NSMutableArray arrayWithCapacity:keys.count]; + NSInteger pos = 0; + for (id key in keys) { + values[pos++] = dictionary[key]; + } + NSAssert(values.count == keys.count, @"We added as many keys as values"); + return [[FArraySortedDictionary alloc] initWithComparator:comparator keys:keys values:values]; +} + +- (id)initWithComparator:(NSComparator)comparator +{ + self = [super init]; + if (self != nil) { + self->_comparator = comparator; + self->_keys = [NSArray array]; + self->_values = [NSArray array]; + } + return self; +} + +- (id)initWithComparator:(NSComparator)comparator keys:(NSArray *)keys values:(NSArray *)values +{ + self = [super init]; + if (self != nil) { + self->_comparator = comparator; + self->_keys = keys; + self->_values = values; + } + return self; +} + +- (NSInteger) findInsertPositionForKey:(id)key +{ + NSInteger newPos = 0; + while (newPos < self.keys.count && self.comparator(self.keys[newPos], key) < NSOrderedSame) { + newPos++; + } + return newPos; +} + +- (NSInteger) findKey:(id)key +{ + if (key == nil) { + return NSNotFound; + } + for (NSInteger pos = 0; pos < self.keys.count; pos++) { + NSComparisonResult result = self.comparator(key, self.keys[pos]); + if (result == NSOrderedSame) { + return pos; + } else if (result == NSOrderedAscending) { + return NSNotFound; + } + } + return NSNotFound; +} + +- (FImmutableSortedDictionary *) insertKey:(id)key withValue:(id)value +{ + NSInteger pos = [self findKey:key]; + + if (pos == NSNotFound) { + /* + * If we're above the threshold we want to convert it to a tree backed implementation to not have + * degrading performance + */ + if (self.count >= SORTED_DICTIONARY_ARRAY_TO_RB_TREE_SIZE_THRESHOLD) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:self.count]; + for (NSInteger i = 0; i < self.keys.count; i++) { + dict[self.keys[i]] = self.values[i]; + } + dict[key] = value; + return [FTreeSortedDictionary fromDictionary:dict withComparator:self.comparator]; + } else { + NSMutableArray *newKeys = [NSMutableArray arrayWithArray:self.keys]; + NSMutableArray *newValues = [NSMutableArray arrayWithArray:self.values]; + NSInteger newPos = [self findInsertPositionForKey:key]; + [newKeys insertObject:key atIndex:newPos]; + [newValues insertObject:value atIndex:newPos]; + return [[FArraySortedDictionary alloc] initWithComparator:self.comparator keys:newKeys values:newValues]; + } + } else { + NSMutableArray *newKeys = [NSMutableArray arrayWithArray:self.keys]; + NSMutableArray *newValues = [NSMutableArray arrayWithArray:self.values]; + newKeys[pos] = key; + newValues[pos] = value; + return [[FArraySortedDictionary alloc] initWithComparator:self.comparator keys:newKeys values:newValues]; + } +} + +- (FImmutableSortedDictionary *) removeKey:(id)key +{ + NSInteger pos = [self findKey:key]; + if (pos == NSNotFound) { + return self; + } else { + NSMutableArray *newKeys = [NSMutableArray arrayWithArray:self.keys]; + NSMutableArray *newValues = [NSMutableArray arrayWithArray:self.values]; + [newKeys removeObjectAtIndex:pos]; + [newValues removeObjectAtIndex:pos]; + return [[FArraySortedDictionary alloc] initWithComparator:self.comparator keys:newKeys values:newValues]; + } +} + +- (id) get:(id)key +{ + NSInteger pos = [self findKey:key]; + if (pos == NSNotFound) { + return nil; + } else { + return self.values[pos]; + } +} + +- (id) getPredecessorKey:(id) key { + NSInteger pos = [self findKey:key]; + if (pos == NSNotFound) { + [NSException raise:NSInternalInconsistencyException format:@"Can't get predecessor key for non-existent key"]; + return nil; + } else if (pos == 0) { + return nil; + } else { + return self.keys[pos - 1]; + } +} + +- (BOOL) isEmpty { + return self.keys.count == 0; +} + +- (int) count +{ + return (int)self.keys.count; +} + +- (id) minKey +{ + return [self.keys firstObject]; +} + +- (id) maxKey +{ + return [self.keys lastObject]; +} + +- (void) enumerateKeysAndObjectsUsingBlock:(void (^)(id, id, BOOL *))block +{ + [self enumerateKeysAndObjectsReverse:NO usingBlock:block]; +} + +- (void) enumerateKeysAndObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id, id, BOOL *))block +{ + if (reverse) { + BOOL stop = NO; + for (NSInteger i = self.keys.count - 1; i >= 0; i--) { + block(self.keys[i], self.values[i], &stop); + if (stop) return; + } + } else { + BOOL stop = NO; + for (NSInteger i = 0; i < self.keys.count; i++) { + block(self.keys[i], self.values[i], &stop); + if (stop) return; + } + } +} + +- (BOOL) contains:(id)key { + return [self findKey:key] != NSNotFound; +} + +- (NSEnumerator *) keyEnumerator { + return [self.keys objectEnumerator]; +} + +- (NSEnumerator *) keyEnumeratorFrom:(id)startKey { + NSInteger startPos = [self findInsertPositionForKey:startKey]; + return [[FArraySortedDictionaryEnumerator alloc] initWithKeys:self.keys startPos:startPos isReverse:NO]; +} + +- (NSEnumerator *) reverseKeyEnumerator { + return [self.keys reverseObjectEnumerator]; +} + +- (NSEnumerator *) reverseKeyEnumeratorFrom:(id)startKey { + NSInteger startPos = [self findInsertPositionForKey:startKey]; + // if there's no exact match, findKeyOrInsertPosition will return the index *after* the closest match, but + // since this is a reverse iterator, we want to start just *before* the closest match. + if (startPos >= self.keys.count || self.comparator(self.keys[startPos], startKey) != NSOrderedSame) { + startPos -= 1; + } + return [[FArraySortedDictionaryEnumerator alloc] initWithKeys:self.keys startPos:startPos isReverse:YES]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.h new file mode 100644 index 0000000..d6687d8 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.h @@ -0,0 +1,54 @@ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ + +#import + +/** + * The size threshold where we use a tree backed sorted map instead of an array backed sorted map. + * This is a more or less arbitrary chosen value, that was chosen to be large enough to fit most of object kind + * of Firebase data, but small enough to not notice degradation in performance for inserting and lookups. + * Feel free to empirically determine this constant, but don't expect much gain in real world performance. + */ +#define SORTED_DICTIONARY_ARRAY_TO_RB_TREE_SIZE_THRESHOLD 25 + +@interface FImmutableSortedDictionary : NSObject + ++ (FImmutableSortedDictionary *)dictionaryWithComparator:(NSComparator)comparator; ++ (FImmutableSortedDictionary *)fromDictionary:(NSDictionary *)dictionary withComparator:(NSComparator)comparator; + +- (FImmutableSortedDictionary *) insertKey:(id)aKey withValue:(id)aValue; +- (FImmutableSortedDictionary *) removeKey:(id)aKey; +- (id) get:(id) key; +- (id) getPredecessorKey:(id) key; +- (BOOL) isEmpty; +- (int) count; +- (id) minKey; +- (id) maxKey; +- (void) enumerateKeysAndObjectsUsingBlock:(void(^)(id key, id value, BOOL *stop))block; +- (void) enumerateKeysAndObjectsReverse:(BOOL)reverse usingBlock:(void(^)(id key, id value, BOOL *stop))block; +- (BOOL) contains:(id)key; +- (NSEnumerator *) keyEnumerator; +- (NSEnumerator *) keyEnumeratorFrom:(id)startKey; +- (NSEnumerator *) reverseKeyEnumerator; +- (NSEnumerator *) reverseKeyEnumeratorFrom:(id)startKey; + +#pragma mark - +#pragma mark Methods similar to NSMutableDictionary + +- (FImmutableSortedDictionary *) setObject:(id)anObject forKey:(id)aKey; +- (id) objectForKey:(id)key; +- (FImmutableSortedDictionary *) removeObjectForKey:(id)aKey; + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.m new file mode 100644 index 0000000..659c63b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.m @@ -0,0 +1,142 @@ +#import "FImmutableSortedDictionary.h" +#import "FArraySortedDictionary.h" +#import "FTreeSortedDictionary.h" + +#define THROW_ABSTRACT_METHOD_EXCEPTION(sel) do { \ + @throw [NSException exceptionWithName:NSInternalInconsistencyException \ + reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(sel)] \ + userInfo:nil]; \ +} while(0) + +@implementation FImmutableSortedDictionary + ++ (FImmutableSortedDictionary *)dictionaryWithComparator:(NSComparator)comparator +{ + return [[FArraySortedDictionary alloc] initWithComparator:comparator]; +} + ++ (FImmutableSortedDictionary *)fromDictionary:(NSDictionary *)dictionary withComparator:(NSComparator)comparator +{ + if (dictionary.count <= SORTED_DICTIONARY_ARRAY_TO_RB_TREE_SIZE_THRESHOLD) { + return [FArraySortedDictionary fromDictionary:dictionary withComparator:comparator]; + } else { + return [FTreeSortedDictionary fromDictionary:dictionary withComparator:comparator]; + } +} + +- (FImmutableSortedDictionary *) insertKey:(id)aKey withValue:(id)aValue { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(insertKey:withValue:)); +} + +- (FImmutableSortedDictionary *) removeKey:(id)aKey { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(removeKey:)); +} + +- (id) get:(id) key { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(get:)); +} + +- (id) getPredecessorKey:(id) key { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(getPredecessorKey:)); +} + +- (BOOL) isEmpty { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(isEmpty)); +} + +- (int) count { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector((count))); +} + +- (id) minKey { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(minKey)); +} + +- (id) maxKey { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(maxKey)); +} + +- (void) enumerateKeysAndObjectsUsingBlock:(void (^)(id, id, BOOL *))block { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(enumerateKeysAndObjectsUsingBlock:)); +} + +- (void) enumerateKeysAndObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id, id, BOOL *))block { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(enumerateKeysAndObjectsReverse:usingBlock:)); +} + +- (BOOL) contains:(id)key { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(contains:)); +} + +- (NSEnumerator *) keyEnumerator { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(keyEnumerator)); +} + +- (NSEnumerator *) keyEnumeratorFrom:(id)startKey { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(keyEnumeratorFrom:)); +} + +- (NSEnumerator *) reverseKeyEnumerator { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(reverseKeyEnumerator)); +} + +- (NSEnumerator *) reverseKeyEnumeratorFrom:(id)startKey { + THROW_ABSTRACT_METHOD_EXCEPTION(@selector(reverseKeyEnumeratorFrom:)); +} + +- (BOOL)isEqual:(id)object { + if (![object isKindOfClass:[FImmutableSortedDictionary class]]) { + return NO; + } + FImmutableSortedDictionary *other = (FImmutableSortedDictionary *)object; + if (self.count != other.count) { + return NO; + } + __block BOOL isEqual = YES; + [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { + id otherValue = [other objectForKey:key]; + isEqual = isEqual && (value == otherValue || [value isEqual:otherValue]); + *stop = !isEqual; + }]; + return isEqual; +} + +- (NSUInteger)hash { + __block NSUInteger hash = 0; + [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { + hash = (hash * 31 + [key hash]) * 17 + [value hash]; + }]; + return hash; +} + +- (NSString *)description { + NSMutableString *str = [[NSMutableString alloc] init]; + __block BOOL first = YES; + [str appendString:@"{ "]; + [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { + if (!first) { + [str appendString:@", "]; + } + first = NO; + [str appendString:[NSString stringWithFormat:@"%@: %@", key, value]]; + }]; + [str appendString:@" }"]; + return str; +} + +#pragma mark - +#pragma mark Methods similar to NSMutableDictionary + +- (FImmutableSortedDictionary *) setObject:(__unsafe_unretained id)anObject forKey:(__unsafe_unretained id)aKey { + return [self insertKey:aKey withValue:anObject]; +} + +- (FImmutableSortedDictionary *) removeObjectForKey:(__unsafe_unretained id)aKey { + return [self removeKey:aKey]; +} + +- (id) objectForKey:(__unsafe_unretained id)key { + return [self get:key]; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.h new file mode 100644 index 0000000..ac15c2f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.h @@ -0,0 +1,22 @@ +#import + +@interface FImmutableSortedSet : NSObject + ++ (FImmutableSortedSet *)setWithKeysFromDictionary:(NSDictionary *)array comparator:(NSComparator)comparator; + +- (BOOL)containsObject:(id)object; +- (FImmutableSortedSet *)addObject:(id)object; +- (FImmutableSortedSet *)removeObject:(id)object; +- (id)firstObject; +- (id)lastObject; +- (NSUInteger)count; +- (BOOL)isEmpty; + +- (id)predecessorEntry:(id)entry; + +- (void)enumerateObjectsUsingBlock:(void (^)(id obj, BOOL *stop))block; +- (void)enumerateObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id obj, BOOL *stop))block; + +- (NSEnumerator *)objectEnumerator; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.m new file mode 100644 index 0000000..1953af1 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.m @@ -0,0 +1,115 @@ +#import "FImmutableSortedSet.h" +#import "FImmutableSortedDictionary.h" + +@interface FImmutableSortedSet () + +@property (nonatomic, strong) FImmutableSortedDictionary *dictionary; + +@end + +@implementation FImmutableSortedSet + ++ (FImmutableSortedSet *)setWithKeysFromDictionary:(NSDictionary *)dictionary comparator:(NSComparator)comparator +{ + FImmutableSortedDictionary *setDict = [FImmutableSortedDictionary fromDictionary:dictionary withComparator:comparator]; + return [[FImmutableSortedSet alloc] initWithDictionary:setDict]; +} + +- (id)initWithDictionary:(FImmutableSortedDictionary *)dictionary +{ + self = [super init]; + if (self != nil) { + self->_dictionary = dictionary; + } + return self; +} + +- (BOOL)contains:(id)object +{ + return [self.dictionary contains:object]; +} + +- (FImmutableSortedSet *)addObject:(id)object +{ + FImmutableSortedDictionary *newDictionary = [self.dictionary insertKey:object withValue:[NSNull null]]; + if (newDictionary != self.dictionary) { + return [[FImmutableSortedSet alloc] initWithDictionary:newDictionary]; + } else { + return self; + } +} + +- (FImmutableSortedSet *)removeObject:(id)object +{ + FImmutableSortedDictionary *newDictionary = [self.dictionary removeObjectForKey:object]; + if (newDictionary != self.dictionary) { + return [[FImmutableSortedSet alloc] initWithDictionary:newDictionary]; + } else { + return self; + } +} + +- (BOOL)containsObject:(id)object +{ + return [self.dictionary contains:object]; +} + +- (id)firstObject +{ + return [self.dictionary minKey]; +} + +- (id)lastObject +{ + return [self.dictionary maxKey]; +} + +- (id)predecessorEntry:(id)entry +{ + return [self.dictionary getPredecessorKey:entry]; +} + +- (NSUInteger)count +{ + return [self.dictionary count]; +} + +- (BOOL)isEmpty +{ + return [self.dictionary isEmpty]; +} + +- (void)enumerateObjectsUsingBlock:(void (^)(id, BOOL *))block +{ + [self enumerateObjectsReverse:NO usingBlock:block]; +} + +- (void)enumerateObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id, BOOL *))block +{ + [self.dictionary enumerateKeysAndObjectsReverse:reverse usingBlock:^(id key, id value, BOOL *stop) { + block(key, stop); + }]; +} + +- (NSEnumerator *)objectEnumerator +{ + return [self.dictionary keyEnumerator]; +} + +- (NSString *)description +{ + NSMutableString *str = [[NSMutableString alloc] init]; + __block BOOL first = YES; + [str appendString:@"FImmutableSortedSet ( "]; + [self enumerateObjectsUsingBlock:^(id obj, BOOL *stop) { + if (!first) { + [str appendString:@", "]; + } + first = NO; + [str appendString:[NSString stringWithFormat:@"%@", obj]]; + }]; + [str appendString:@" )"]; + return str; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.h new file mode 100644 index 0000000..833f2a5 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.h @@ -0,0 +1,27 @@ +#import +#import "FLLRBNode.h" + +@interface FLLRBEmptyNode : NSObject + ++ (id)emptyNode; + +- (id)copyWith:(id) aKey withValue:(id) aValue withColor:(FLLRBColor*) aColor withLeft:(id)aLeft withRight:(id)aRight; +- (id) insertKey:(id) aKey forValue:(id)aValue withComparator:(NSComparator)aComparator; +- (id) remove:(id) aKey withComparator:(NSComparator)aComparator; +- (int) count; +- (BOOL) isEmpty; +- (BOOL) inorderTraversal:(BOOL (^)(id key, id value))action; +- (BOOL) reverseTraversal:(BOOL (^)(id key, id value))action; +- (id) min; +- (id) minKey; +- (id) maxKey; +- (BOOL) isRed; +- (int) check; + +@property (nonatomic, strong) id key; +@property (nonatomic, strong) id value; +@property (nonatomic, strong) FLLRBColor* color; +@property (nonatomic, strong) id left; +@property (nonatomic, strong) id right; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.m new file mode 100644 index 0000000..3ca6f06 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.m @@ -0,0 +1,72 @@ +#import "FLLRBEmptyNode.h" +#import "FLLRBValueNode.h" + +@implementation FLLRBEmptyNode + +@synthesize key, value, color, left, right; + +- (NSString *) description { + return [NSString stringWithFormat:@"[key=%@ val=%@ color=%@]", key, value, + (color != nil ? @"true" : @"false")]; +} + ++ (id)emptyNode +{ + static dispatch_once_t pred = 0; + __strong static id _sharedObject = nil; + dispatch_once(&pred, ^{ + _sharedObject = [[self alloc] init]; // or some other init method + }); + return _sharedObject; +} + +- (id)copyWith:(id) aKey withValue:(id) aValue withColor:(FLLRBColor*) aColor withLeft:(id)aLeft withRight:(id)aRight { + return self; +} + +- (id) insertKey:(id) aKey forValue:(id)aValue withComparator:(NSComparator)aComparator { + FLLRBValueNode* result = [[FLLRBValueNode alloc] initWithKey:aKey withValue:aValue withColor:nil withLeft:nil withRight:nil]; + return result; +} + +- (id) remove:(id) key withComparator:(NSComparator)aComparator { + return self; +} + +- (int) count { + return 0; +} + +- (BOOL) isEmpty { + return YES; +} + +- (BOOL) inorderTraversal:(BOOL (^)(id key, id value))action { + return NO; +} + +- (BOOL) reverseTraversal:(BOOL (^)(id key, id value))action { + return NO; +} + +- (id) min { + return self; +} + +- (id) minKey { + return nil; +} + +- (id) maxKey { + return nil; +} + +- (BOOL) isRed { + return NO; +} + +- (int) check { + return 0; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBNode.h new file mode 100644 index 0000000..09b234c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBNode.h @@ -0,0 +1,29 @@ +#import + +#define RED @true +#define BLACK @false + +typedef NSNumber FLLRBColor; + +@protocol FLLRBNode + +- (id)copyWith:(id) aKey withValue:(id) aValue withColor:(FLLRBColor*) aColor withLeft:(id)aLeft withRight:(id)aRight; +- (id) insertKey:(id) aKey forValue:(id)aValue withComparator:(NSComparator)aComparator; +- (id) remove:(id) key withComparator:(NSComparator)aComparator; +- (int) count; +- (BOOL) isEmpty; +- (BOOL) inorderTraversal:(BOOL (^)(id key, id value))action; +- (BOOL) reverseTraversal:(BOOL (^)(id key, id value))action; +- (id) min; +- (id) minKey; +- (id) maxKey; +- (BOOL) isRed; +- (int) check; + +@property (nonatomic, strong) id key; +@property (nonatomic, strong) id value; +@property (nonatomic, strong) FLLRBColor* color; +@property (nonatomic, strong) id left; +@property (nonatomic, strong) id right; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.h new file mode 100644 index 0000000..50438bb --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.h @@ -0,0 +1,29 @@ +#import +#import "FLLRBNode.h" + +@interface FLLRBValueNode : NSObject + + +- (id)initWithKey:(id) key withValue:(id) value withColor:(FLLRBColor*) color withLeft:(id)left withRight:(id)right; +- (id)copyWith:(id) aKey withValue:(id) aValue withColor:(FLLRBColor*) aColor withLeft:(id)aLeft withRight:(id)aRight; +- (id) insertKey:(id) aKey forValue:(id)aValue withComparator:(NSComparator)aComparator; +- (id) remove:(id) aKey withComparator:(NSComparator)aComparator; +- (int) count; +- (BOOL) isEmpty; +- (BOOL) inorderTraversal:(BOOL (^)(id key, id value))action; +- (BOOL) reverseTraversal:(BOOL (^)(id key, id value))action; +- (id) min; +- (id) minKey; +- (id) maxKey; +- (BOOL) isRed; +- (int) check; + +- (BOOL) checkMaxDepth; + +@property (nonatomic, strong) id key; +@property (nonatomic, strong) id value; +@property (nonatomic, strong) FLLRBColor* color; +@property (nonatomic, strong) id left; +@property (nonatomic, strong) id right; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.m new file mode 100644 index 0000000..831b97f --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.m @@ -0,0 +1,230 @@ +#import "FLLRBValueNode.h" +#import "FLLRBEmptyNode.h" + +@implementation FLLRBValueNode + +@synthesize key, value, color, left, right; + +- (NSString *) description { + return [NSString stringWithFormat:@"[key=%@ val=%@ color=%@]", key, value, + (color != nil ? @"true" : @"false")]; +} + +- (id)initWithKey:(__unsafe_unretained id) aKey withValue:(__unsafe_unretained id) aValue withColor:(__unsafe_unretained FLLRBColor*) aColor withLeft:(__unsafe_unretained id)aLeft withRight:(__unsafe_unretained id)aRight +{ + self = [super init]; + if (self) { + self.key = aKey; + self.value = aValue; + self.color = aColor != nil ? aColor : RED; + self.left = aLeft != nil ? aLeft : [FLLRBEmptyNode emptyNode]; + self.right = aRight != nil ? aRight : [FLLRBEmptyNode emptyNode]; + } + return self; +} + +- (id)copyWith:(__unsafe_unretained id) aKey withValue:(__unsafe_unretained id) aValue withColor:(__unsafe_unretained FLLRBColor*) aColor withLeft:(__unsafe_unretained id)aLeft withRight:(__unsafe_unretained id)aRight { + return [[FLLRBValueNode alloc] initWithKey:(aKey != nil) ? aKey : self.key + withValue:(aValue != nil) ? aValue : self.value + withColor:(aColor != nil) ? aColor : self.color + withLeft:(aLeft != nil) ? aLeft : self.left + withRight:(aRight != nil) ? aRight : self.right]; +} + +- (int) count { + return [self.left count] + 1 + [self.right count]; +} + +- (BOOL) isEmpty { + return NO; +} + +/** +* Early terminates if aciton returns YES. +* @return The first truthy value returned by action, or the last falsey value returned by action. +*/ +- (BOOL) inorderTraversal:(BOOL (^)(id key, id value))action { + return [self.left inorderTraversal:action] || + action(self.key, self.value) || + [self.right inorderTraversal:action]; +} + +- (BOOL) reverseTraversal:(BOOL (^)(id key, id value))action { + return [self.right reverseTraversal:action] || + action(self.key, self.value) || + [self.left reverseTraversal:action]; +} + +- (id) min { + if([self.left isEmpty]) { + return self; + } + else { + return [self.left min]; + } +} + +- (id) minKey { + return [[self min] key]; +} + +- (id) maxKey { + if([self.right isEmpty]) { + return self.key; + } + else { + return [self.right maxKey]; + } +} + +- (id) insertKey:(__unsafe_unretained id) aKey forValue:(__unsafe_unretained id)aValue withComparator:(NSComparator)aComparator { + NSComparisonResult cmp = aComparator(aKey, self.key); + FLLRBValueNode* n = self; + + if(cmp == NSOrderedAscending) { + n = [n copyWith:nil withValue:nil withColor:nil withLeft:[n.left insertKey:aKey forValue:aValue withComparator:aComparator] withRight:nil]; + } + else if(cmp == NSOrderedSame) { + n = [n copyWith:nil withValue:aValue withColor:nil withLeft:nil withRight:nil]; + } + else { + n = [n copyWith:nil withValue:nil withColor:nil withLeft:nil withRight:[n.right insertKey:aKey forValue:aValue withComparator:aComparator]]; + } + + return [n fixUp]; +} + +- (id) removeMin { + + if([self.left isEmpty]) { + return [FLLRBEmptyNode emptyNode]; + } + + FLLRBValueNode* n = self; + if(! [n.left isRed] && ! [n.left.left isRed]) { + n = [n moveRedLeft]; + } + + n = [n copyWith:nil withValue:nil withColor:nil withLeft:[(FLLRBValueNode*)n.left removeMin] withRight:nil]; + return [n fixUp]; +} + + +- (id) fixUp { + FLLRBValueNode* n = self; + if([n.right isRed] && ! [n.left isRed]) n = [n rotateLeft]; + if([n.left isRed] && [n.left.left isRed]) n = [n rotateRight]; + if([n.left isRed] && [n.right isRed]) n = [n colorFlip]; + return n; +} + +- (FLLRBValueNode*) moveRedLeft { + FLLRBValueNode* n = [self colorFlip]; + if([n.right.left isRed]) { + n = [n copyWith:nil withValue:nil withColor:nil withLeft:nil withRight:[(FLLRBValueNode*)n.right rotateRight]]; + n = [n rotateLeft]; + n = [n colorFlip]; + } + return n; +} + +- (FLLRBValueNode*) moveRedRight { + FLLRBValueNode* n = [self colorFlip]; + if([n.left.left isRed]) { + n = [n rotateRight]; + n = [n colorFlip]; + } + return n; +} + +- (id) rotateLeft { + id nl = [self copyWith:nil withValue:nil withColor:RED withLeft:nil withRight:self.right.left]; + return [self.right copyWith:nil withValue:nil withColor:self.color withLeft:nl withRight:nil];; +} + +- (id) rotateRight { + id nr = [self copyWith:nil withValue:nil withColor:RED withLeft:self.left.right withRight:nil]; + return [self.left copyWith:nil withValue:nil withColor:self.color withLeft:nil withRight:nr]; +} + +- (id) colorFlip { + id nleft = [self.left copyWith:nil withValue:nil withColor:[NSNumber numberWithBool:![self.left.color boolValue]] withLeft:nil withRight:nil]; + id nright = [self.right copyWith:nil withValue:nil withColor:[NSNumber numberWithBool:![self.right.color boolValue]] withLeft:nil withRight:nil]; + + return [self copyWith:nil withValue:nil withColor:[NSNumber numberWithBool:![self.color boolValue]] withLeft:nleft withRight:nright]; +} + +- (id) remove:(__unsafe_unretained id) aKey withComparator:(NSComparator)comparator { + id smallest; + FLLRBValueNode* n = self; + + if(comparator(aKey, n.key) == NSOrderedAscending) { + if(![n.left isEmpty] && ![n.left isRed] && ![n.left.left isRed]) { + n = [n moveRedLeft]; + } + n = [n copyWith:nil withValue:nil withColor:nil withLeft:[n.left remove:aKey withComparator:comparator] withRight:nil]; + } + else { + if([n.left isRed]) { + n = [n rotateRight]; + } + + if(![n.right isEmpty] && ![n.right isRed] && ![n.right.left isRed]) { + n = [n moveRedRight]; + } + + if(comparator(aKey, n.key) == NSOrderedSame) { + if([n.right isEmpty]) { + return [FLLRBEmptyNode emptyNode]; + } + else { + smallest = [n.right min]; + n = [n copyWith:smallest.key withValue:smallest.value withColor:nil withLeft:nil withRight:[(FLLRBValueNode*)n.right removeMin]]; + } + } + n = [n copyWith:nil withValue:nil withColor:nil withLeft:nil withRight:[n.right remove:aKey withComparator:comparator]]; + } + return [n fixUp]; +} + +- (BOOL) isRed { + return [self.color boolValue]; +} + +- (BOOL) checkMaxDepth { + int blackDepth = [self check]; + if(pow(2.0, blackDepth) <= ([self count] + 1)) { + return YES; + } + else { + return NO; + } +} + +- (int) check { + int blackDepth = 0; + + if([self isRed] && [self.left isRed]) { + @throw [[NSException alloc] initWithName:@"check" reason:@"Red node has a red child" userInfo:nil]; + } + + if([self.right isRed]) { + @throw [[NSException alloc] initWithName:@"check" reason:@"Right child is red" userInfo:nil]; + } + + blackDepth = [self.left check]; +// NSLog(err); + if(blackDepth != [self.right check]) { + NSString* err = [NSString stringWithFormat:@"(%@ -> %@)blackDepth: %d ; self.right check: %d", self.value, [self.color boolValue] ? @"red" : @"black", blackDepth, [self.right check]]; +// return 10; + @throw [[NSException alloc] initWithName:@"check" reason:err userInfo:nil]; + } + else { + int ret = blackDepth + ([self isRed] ? 0 : 1); +// NSLog(@"black depth is: %d; other is: %d, ret is: %d", blackDepth, ([self isRed] ? 0 : 1), ret); + return ret; + } +} + + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.h new file mode 100644 index 0000000..934ca8b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.h @@ -0,0 +1,30 @@ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ + +#import +#import "FImmutableSortedDictionary.h" +#import "FLLRBNode.h" + +@interface FTreeSortedDictionary : FImmutableSortedDictionary + +@property (nonatomic, copy, readonly) NSComparator comparator; +@property (nonatomic, strong, readonly) id root; + +- (id)initWithComparator:(NSComparator)aComparator; + +// Override methods to return subtype +- (FTreeSortedDictionary *) insertKey:(id)aKey withValue:(id)aValue; +- (FTreeSortedDictionary *) removeKey:(id)aKey; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.m new file mode 100644 index 0000000..e9f0683 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.m @@ -0,0 +1,326 @@ +#import "FTreeSortedDictionary.h" +#import "FLLRBEmptyNode.h" +#import "FLLRBValueNode.h" +#import "FTreeSortedDictionaryEnumerator.h" + +typedef void (^fbt_void_nsnumber_int)(NSNumber* color, NSUInteger chunkSize); + +@interface FTreeSortedDictionary () + +@property (nonatomic, strong) id root; +@property (nonatomic, copy, readwrite) NSComparator comparator; + +@end + +@implementation FTreeSortedDictionary + +- (id)initWithComparator:(NSComparator)aComparator { + self = [super init]; + if (self) { + self.root = [FLLRBEmptyNode emptyNode]; + self.comparator = aComparator; + } + return self; +} + +- (id)initWithComparator:(NSComparator)aComparator withRoot:(__unsafe_unretained id)aRoot { + self = [super init]; + if (self) { + self.root = aRoot; + self.comparator = aComparator; + } + return self; +} + +/** + * Returns a copy of the map, with the specified key/value added or replaced. + */ +- (FTreeSortedDictionary *) insertKey:(__unsafe_unretained id)aKey withValue:(__unsafe_unretained id)aValue { + return [[FTreeSortedDictionary alloc] initWithComparator:self.comparator + withRoot:[[self.root insertKey:aKey forValue:aValue withComparator:self.comparator] + copyWith:nil + withValue:nil + withColor:BLACK + withLeft:nil + withRight:nil]]; +} + + +- (FTreeSortedDictionary *) removeKey:(__unsafe_unretained id)aKey { + // Remove is somewhat expensive even if the key doesn't exist (the tree does rebalancing and stuff). So avoid it. + if (![self contains:aKey]) { + return self; + } else { + return [[FTreeSortedDictionary alloc] + initWithComparator:self.comparator + withRoot:[[self.root remove:aKey withComparator:self.comparator] + copyWith:nil + withValue:nil + withColor:BLACK + withLeft:nil + withRight:nil]]; + } +} + +- (id) get:(__unsafe_unretained id) key { + if (key == nil) { + return nil; + } + NSComparisonResult cmp; + id node = self.root; + while(![node isEmpty]) { + cmp = self.comparator(key, node.key); + if(cmp == NSOrderedSame) { + return node.value; + } + else if (cmp == NSOrderedAscending) { + node = node.left; + } + else { + node = node.right; + } + } + return nil; +} + +- (id) getPredecessorKey:(__unsafe_unretained id) key { + NSComparisonResult cmp; + id node = self.root; + id rightParent = nil; + while(![node isEmpty]) { + cmp = self.comparator(key, node.key); + if(cmp == NSOrderedSame) { + if(![node.left isEmpty]) { + node = node.left; + while(! [node.right isEmpty]) { + node = node.right; + } + return node.key; + } + else if (rightParent != nil) { + return rightParent.key; + } + else { + return nil; + } + } + else if (cmp == NSOrderedAscending) { + node = node.left; + } + else if (cmp == NSOrderedDescending) { + rightParent = node; + node = node.right; + } + } + @throw [NSException exceptionWithName:@"NonexistentKey" reason:@"getPredecessorKey called with nonexistent key." userInfo:@{@"key": [key description] }]; +} + +- (BOOL) isEmpty { + return [self.root isEmpty]; +} + +- (int) count { + return [self.root count]; +} + +- (id) minKey { + return [self.root minKey]; +} + +- (id) maxKey { + return [self.root maxKey]; +} + +- (void) enumerateKeysAndObjectsUsingBlock:(void (^)(id, id, BOOL *))block +{ + [self enumerateKeysAndObjectsReverse:NO usingBlock:block]; +} + +- (void) enumerateKeysAndObjectsReverse:(BOOL)reverse usingBlock:(void (^)(id, id, BOOL *))block +{ + if (reverse) { + __block BOOL stop = NO; + [self.root reverseTraversal:^BOOL(id key, id value) { + block(key, value, &stop); + return stop; + }]; + } else { + __block BOOL stop = NO; + [self.root inorderTraversal:^BOOL(id key, id value) { + block(key, value, &stop); + return stop; + }]; + } +} + +- (BOOL) contains:(__unsafe_unretained id)key { + return ([self objectForKey:key] != nil); +} + +- (NSEnumerator *) keyEnumerator { + return [[FTreeSortedDictionaryEnumerator alloc] + initWithImmutableSortedDictionary:self startKey:nil isReverse:NO]; +} + +- (NSEnumerator *) keyEnumeratorFrom:(id)startKey { + return [[FTreeSortedDictionaryEnumerator alloc] + initWithImmutableSortedDictionary:self startKey:startKey isReverse:NO]; +} + +- (NSEnumerator *) reverseKeyEnumerator { + return [[FTreeSortedDictionaryEnumerator alloc] + initWithImmutableSortedDictionary:self startKey:nil isReverse:YES]; +} + +- (NSEnumerator *) reverseKeyEnumeratorFrom:(id)startKey { + return [[FTreeSortedDictionaryEnumerator alloc] + initWithImmutableSortedDictionary:self startKey:startKey isReverse:YES]; +} + + +#pragma mark - +#pragma mark Tree Builder + +// Code to efficiently build a RB Tree +typedef struct _base1_2list { + unsigned int bits; + unsigned short count; + unsigned short current; +} Base1_2List; + +Base1_2List *base1_2List_new(unsigned int length); +void base1_2List_free(Base1_2List* list); +unsigned int log_base2(unsigned int num); +BOOL base1_2List_next(Base1_2List* list); + +unsigned int log_base2(unsigned int num) { + return (unsigned int)(log(num) / log(2)); +} + +/** + * Works like an iterator, so it moves to the next bit. Do not call more than list->count times. + * @return whether or not the next bit is a 1 in base {1,2}. + */ +BOOL base1_2List_next(Base1_2List* list) { + BOOL result = !(list->bits & (0x1 << list->current)); + list->current--; + return result; +} + +static inline unsigned bit_mask(int x) { + return (x >= sizeof(unsigned) * CHAR_BIT) ? (unsigned) -1 : (1U << x) - 1; +} + +/** + * We represent the base{1,2} number as the combination of a binary number and a number of bits that we care about + * We iterate backwards, from most significant bit to least, to build up the llrb nodes. 0 base 2 => 1 base {1,2}, 1 base 2 => 2 base {1,2} + */ +Base1_2List *base1_2List_new(unsigned int length) { + size_t sz = sizeof(Base1_2List); + Base1_2List* list = calloc(1, sz); + // Calculate the number of bits that we care about + list->count = (unsigned short)log_base2(length + 1); + unsigned int mask = bit_mask(list->count); + list->bits = (length + 1) & mask; + list->current = list->count - 1; + return list; +} + + +void base1_2List_free(Base1_2List* list) { + free(list); +} + ++ (id) buildBalancedTree:(NSArray *)keys dictionary:(NSDictionary *)dictionary subArrayStartIndex:(NSUInteger)startIndex length:(NSUInteger)length { + length = MIN(keys.count - startIndex, length); // Bound length by the actual length of the array + if (length == 0) { + return nil; + } else if (length == 1) { + id key = keys[startIndex]; + return [[FLLRBValueNode alloc] initWithKey:key withValue:dictionary[key] withColor:BLACK withLeft:nil withRight:nil]; + } else { + NSUInteger middle = length / 2; + id left = [FTreeSortedDictionary buildBalancedTree:keys dictionary:dictionary subArrayStartIndex:startIndex length:middle]; + id right = [FTreeSortedDictionary buildBalancedTree:keys dictionary:dictionary subArrayStartIndex:(startIndex+middle+1) length:middle]; + id key = keys[startIndex + middle]; + return [[FLLRBValueNode alloc] initWithKey:key withValue:dictionary[key] withColor:BLACK withLeft:left withRight:right]; + } +} + ++ (id) rootFrom12List:(Base1_2List *)base1_2List keyList:(NSArray *)keyList dictionary:(NSDictionary *)dictionary { + __block id root = nil; + __block id node = nil; + __block NSUInteger index = keyList.count; + + fbt_void_nsnumber_int buildPennant = ^(NSNumber* color, NSUInteger chunkSize) { + NSUInteger startIndex = index - chunkSize + 1; + index -= chunkSize; + id key = keyList[index]; + id childTree = [self buildBalancedTree:keyList dictionary:dictionary subArrayStartIndex:startIndex length:(chunkSize - 1)]; + id pennant = [[FLLRBValueNode alloc] initWithKey:key withValue:dictionary[key] withColor:color withLeft:nil withRight:childTree]; + //attachPennant(pennant); + if (node) { + node.left = pennant; + node = pennant; + } else { + root = pennant; + node = pennant; + } + }; + + for (int i = 0; i < base1_2List->count; ++i) { + BOOL isOne = base1_2List_next(base1_2List); + NSUInteger chunkSize = (NSUInteger)pow(2.0, base1_2List->count - (i + 1)); + if (isOne) { + buildPennant(BLACK, chunkSize); + } else { + buildPennant(BLACK, chunkSize); + buildPennant(RED, chunkSize); + } + } + return root; +} + +/** + * Uses the algorithm linked here: + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 + */ + ++ (FImmutableSortedDictionary *)fromDictionary:(NSDictionary *)dictionary withComparator:(NSComparator)comparator +{ + // Steps: + // 0. Sort the array + // 1. Calculate the 1-2 number + // 2. Build From 1-2 number + // 0. for each digit in 1-2 number + // 0. calculate chunk size + // 1. build 1 or 2 pennants of that size + // 2. attach pennants and update node pointer + // 1. return root + NSMutableArray *sortedKeyList = [NSMutableArray arrayWithCapacity:dictionary.count]; + [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [sortedKeyList addObject:key]; + }]; + [sortedKeyList sortUsingComparator:comparator]; + + [sortedKeyList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (idx > 0) { + if (comparator(sortedKeyList[idx - 1], obj) != NSOrderedAscending) { + [NSException raise:NSInvalidArgumentException format:@"Can't create FImmutableSortedDictionary with keys with same ordering!"]; + } + } + }]; + + Base1_2List* list = base1_2List_new((unsigned int)sortedKeyList.count); + id root = [self rootFrom12List:list keyList:sortedKeyList dictionary:dictionary]; + base1_2List_free(list); + + if (root != nil) { + return [[FTreeSortedDictionary alloc] initWithComparator:comparator withRoot:root]; + } else { + return [[FTreeSortedDictionary alloc] initWithComparator:comparator]; + } +} + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.h new file mode 100644 index 0000000..d79fe8e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.h @@ -0,0 +1,9 @@ +#import +#import "FTreeSortedDictionary.h" + +@interface FTreeSortedDictionaryEnumerator : NSEnumerator + +- (id)initWithImmutableSortedDictionary:(FTreeSortedDictionary *)aDict startKey:(id)startKey isReverse:(BOOL)reverse; +- (id)nextObject; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.m new file mode 100644 index 0000000..2aca86e --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.m @@ -0,0 +1,83 @@ +#import "FTreeSortedDictionaryEnumerator.h" + +@interface FTreeSortedDictionaryEnumerator() +@property (nonatomic, strong) FTreeSortedDictionary* immutableSortedDictionary; +@property (nonatomic, strong) NSMutableArray* stack; +@property (nonatomic) BOOL isReverse; + +@end + +@implementation FTreeSortedDictionaryEnumerator + +- (id)initWithImmutableSortedDictionary:(FTreeSortedDictionary *)aDict + startKey:(id)startKey isReverse:(BOOL)reverse { + self = [super init]; + if (self) { + self.immutableSortedDictionary = aDict; + self.stack = [[NSMutableArray alloc] init]; + self.isReverse = reverse; + + NSComparator comparator = aDict.comparator; + id node = self.immutableSortedDictionary.root; + + NSInteger cmp; + while(![node isEmpty]) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (self.isReverse) cmp *= -1; + + if (cmp < 0) { + // This node is less than our start key. Ignore it. + if (self.isReverse) { + node = node.left; + } else { + node = node.right; + } + } else if (cmp == 0) { + // This node is exactly equal to our start key. Push it on the stack, but stop iterating: + [self.stack addObject:node]; + break; + } else { + // This node is greater than our start key, add it to the stack and move on to the next one. + [self.stack addObject:node]; + if (self.isReverse) { + node = node.right; + } else { + node = node.left; + } + } + } + } + return self; +} + +- (id)nextObject { + if([self.stack count] == 0) { + return nil; + } + + id node = nil; + @synchronized(self.stack) { + node = [self.stack lastObject]; + [self.stack removeLastObject]; + } + id result = node.key; + + if (self.isReverse) { + node = node.left; + while (![node isEmpty]) { + [self.stack addObject:node]; + node = node.right; + } + } else { + node = node.right; + while (![node isEmpty]) { + [self.stack addObject:node]; + node = node.left; + } + } + + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.h new file mode 100644 index 0000000..1ca1815 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.h @@ -0,0 +1,107 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 + +typedef enum { + SR_CONNECTING = 0, + SR_OPEN = 1, + SR_CLOSING = 2, + SR_CLOSED = 3, + +} FSRReadyState; + +@class FSRWebSocket; + +extern NSString *const FSRWebSocketErrorDomain; + +@protocol FSRWebSocketDelegate; + +@interface FSRWebSocket : NSObject + +@property (nonatomic, weak) id delegate; + +@property (nonatomic, readonly) FSRReadyState readyState; +@property (nonatomic, readonly, retain) NSURL *url; + +// This returns the negotiated protocol. +// It will be niluntil after the handshake completes. +@property (nonatomic, readonly, copy) NSString *protocol; + +// Protocols should be an array of strings that turn into Sec-WebSocket-Protocol +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent; +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols; +- (id)initWithURLRequest:(NSURLRequest *)request queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent; +- (id)initWithURLRequest:(NSURLRequest *)request; + +// Some helper constructors +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols; +- (id)initWithURL:(NSURL *)url; + +// Delegate queue will be dispatch_main_queue by default. +// You cannot set both OperationQueue and dispatch_queue. +- (void)setDelegateOperationQueue:(NSOperationQueue*) queue; +- (void)setDelegateDispatchQueue:(dispatch_queue_t)queue; + +// By default, it will schedule itself on +[NSRunLoop SR_networkRunLoop] using defaultModes. +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; + +// SRWebSockets are intended one-time-use only. Open should be called once and only once +- (void)open; + +- (void)close; +- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason; + +// Send a UTF8 String or Data +- (void)send:(id)data; + +@end + +@protocol FSRWebSocketDelegate + +// message will either be an NSString if the server is using text +// or NSData if the server is using binary +- (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message; + +@optional + +- (void)webSocketDidOpen:(FSRWebSocket *)webSocket; +- (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error; +- (void)webSocket:(FSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; + +@end + + +@interface NSURLRequest (FCertificateAdditions) + +@property (nonatomic, retain, readonly) NSArray *FSR_SSLPinnedCertificates; + +@end + + +@interface NSMutableURLRequest (FCertificateAdditions) + +@property (nonatomic, retain) NSArray *FSR_SSLPinnedCertificates; + +@end + +@interface NSRunLoop (FSRWebSocket) + ++ (NSRunLoop *)FSR_networkRunLoop; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.m new file mode 100644 index 0000000..4cd481b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/FSRWebSocket.m @@ -0,0 +1,1852 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "FSRWebSocket.h" + +#if TARGET_OS_IOS || TARGET_OS_TV +#define HAS_ICU +#endif + +#import + +#ifdef HAS_ICU +#import +#endif + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_OSX +#import +#endif + +#import +#import +#import "fbase64.h" +#import "NSData+SRB64Additions.h" + +#if OS_OBJECT_USE_OBJC_RETAIN_RELEASE +#define sr_dispatch_retain(x) +#define sr_dispatch_release(x) +#define maybe_bridge(x) ((__bridge void *) x) +#else +#define sr_dispatch_retain(x) dispatch_retain(x) +#define sr_dispatch_release(x) dispatch_release(x) +#define maybe_bridge(x) (x) +#endif + +typedef enum { + SROpCodeTextFrame = 0x1, + SROpCodeBinaryFrame = 0x2, + //3-7Reserved + SROpCodeConnectionClose = 0x8, + SROpCodePing = 0x9, + SROpCodePong = 0xA, + //B-F reserved +} FSROpCode; + +typedef enum { + SRStatusCodeNormal = 1000, + SRStatusCodeGoingAway = 1001, + SRStatusCodeProtocolError = 1002, + SRStatusCodeUnhandledType = 1003, + // 1004 reserved + SRStatusNoStatusReceived = 1005, + // 1004-1006 reserved + SRStatusCodeInvalidUTF8 = 1007, + SRStatusCodePolicyViolated = 1008, + SRStatusCodeMessageTooBig = 1009, +} FSRStatusCode; + +typedef struct { + BOOL fin; +// BOOL rsv1; +// BOOL rsv2; +// BOOL rsv3; + uint8_t opcode; + BOOL masked; + uint64_t payload_length; +} frame_header; + +static NSString *const SRWebSocketAppendToSecKeyString = @"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +static inline int32_t validate_dispatch_data_partial_string(NSData *data); +static inline void SRFastLog(NSString *format, ...); + +@interface NSData (FSRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; + +@end + + +@interface NSString (FSRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; + +@end + + +@interface NSURL (FSRWebSocket) + +// The origin isn't really applicable for a native application +// So instead, just map ws -> http and wss -> https +- (NSString *)SR_origin; + +@end + +@interface _FSRRunLoopThread : NSThread + +@property (nonatomic, readonly) NSRunLoop *runLoop; + +@end + +static NSString *newSHA1String(const char *bytes, size_t length) { + uint8_t md[CC_SHA1_DIGEST_LENGTH]; + + CC_SHA1(bytes, (int)length, md); + + size_t buffer_size = ((sizeof(md) * 3 + 2) / 2); + + char *buffer = (char *)malloc(buffer_size); + + int len = f_b64_ntop(md, CC_SHA1_DIGEST_LENGTH, buffer, buffer_size); + if (len == -1) { + free(buffer); + return nil; + } else{ + return [[NSString alloc] initWithBytesNoCopy:buffer length:len encoding:NSASCIIStringEncoding freeWhenDone:YES]; + } +} + +@implementation NSData (FSRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; +{ + return newSHA1String(self.bytes, self.length); +} + +@end + + +@implementation NSString (FSRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; +{ + return newSHA1String(self.UTF8String, self.length); +} + +@end + +NSString *const FSRWebSocketErrorDomain = @"FSRWebSocketErrorDomain"; + +// Returns number of bytes consumed. returning 0 means you didn't match. +// Sends bytes to callback handler; +typedef size_t (^stream_scanner)(NSData *collected_data); + +typedef void (^data_callback)(FSRWebSocket *webSocket, NSData *data); + +@interface FSRIOConsumer : NSObject { + stream_scanner _scanner; + data_callback _handler; + size_t _bytesNeeded; + BOOL _readToCurrentFrame; + BOOL _unmaskBytes; +} +@property (nonatomic, copy, readonly) stream_scanner consumer; +@property (nonatomic, copy, readonly) data_callback handler; +@property (nonatomic, assign) size_t bytesNeeded; +@property (nonatomic, assign, readonly) BOOL readToCurrentFrame; +@property (nonatomic, assign, readonly) BOOL unmaskBytes; + +@end + +// This class is not thread-safe, and is expected to always be run on the same queue. +@interface FSRIOConsumerPool : NSObject + +- (id)initWithBufferCapacity:(NSUInteger)poolSize; + +- (FSRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +- (void)returnConsumer:(FSRIOConsumer *)consumer; + +@end + +@interface FSRWebSocket () + +- (void)_writeData:(NSData *)data; +- (void)_closeWithProtocolError:(NSString *)message; +- (void)_failWithError:(NSError *)error; + +- (void)_disconnect; + +- (void)_readFrameNew; +- (void)_readFrameContinue; + +- (void)_pumpScanner; + +- (void)_pumpWriting; + +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback; +- (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength; +- (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler; +- (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler; + +- (void)_sendFrameWithOpcode:(FSROpCode)opcode data:(id)data; + +- (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage; +- (void)_SR_commonInit; + +- (void)_initializeStreams; +- (void)_connect; + +@property (nonatomic) FSRReadyState readyState; + +@property (nonatomic) NSOperationQueue *delegateOperationQueue; +@property (nonatomic) dispatch_queue_t delegateDispatchQueue; + +@end + + +@implementation FSRWebSocket { + NSInteger _webSocketVersion; + + NSOperationQueue *_delegateOperationQueue; + dispatch_queue_t _delegateDispatchQueue; + dispatch_queue_t _workQueue; + NSMutableArray *_consumers; + + NSInputStream *_inputStream; + NSOutputStream *_outputStream; + + NSMutableData *_readBuffer; + NSInteger _readBufferOffset; + + NSMutableData *_outputBuffer; + NSInteger _outputBufferOffset; + + uint8_t _currentFrameOpcode; + size_t _currentFrameCount; + size_t _readOpCount; + uint32_t _currentStringScanPosition; + NSMutableData *_currentFrameData; + + NSString *_closeReason; + + NSString *_secKey; + + BOOL _pinnedCertFound; + + uint8_t _currentReadMaskKey[4]; + size_t _currentReadMaskOffset; + + BOOL _consumerStopped; + + BOOL _closeWhenFinishedWriting; + BOOL _failed; + + BOOL _secure; + NSURLRequest *_urlRequest; + NSString *_userAgent; + + CFHTTPMessageRef _receivedHTTPHeaders; + + BOOL _sentClose; + BOOL _didFail; + BOOL _cleanupScheduled; + int _closeCode; + + BOOL _isPumping; + + NSMutableSet *_scheduledRunloops; + + // We use this to retain ourselves. + __strong FSRWebSocket *_selfRetain; + + NSArray *_requestedProtocols; + FSRIOConsumerPool *_consumerPool; +} + +@synthesize delegate = _delegate; +@synthesize url = _url; +@synthesize readyState = _readyState; +@synthesize protocol = _protocol; + +static __strong NSData *CRLFCRLF; + ++ (void)initialize; +{ + CRLFCRLF = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4]; +} + +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent; +{ + self = [super init]; + if (self) { + assert(request.URL); + _url = request.URL; + NSString *scheme = [_url scheme]; + + _requestedProtocols = [protocols copy]; + _userAgent = userAgent; + + assert([scheme isEqualToString:@"ws"] || [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]); + _urlRequest = request; + + if ([scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]) { + _secure = YES; + } + + if (!queue) { + _delegateDispatchQueue = dispatch_get_main_queue(); + } else { + _delegateDispatchQueue = queue; + } + + [self _SR_commonInit]; + } + + return self; +} + +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols; +{ + return [self initWithURLRequest:request protocols:nil queue:nil andUserAgent:nil]; +} + +- (id)initWithURLRequest:(NSURLRequest *)request queue:(dispatch_queue_t)queue andUserAgent:(NSString *)userAgent; +{ + return [self initWithURLRequest:request protocols:nil queue:queue andUserAgent:userAgent]; +} + +- (id)initWithURLRequest:(NSURLRequest *)request; +{ + return [self initWithURLRequest:request protocols:nil]; +} + +- (id)initWithURL:(NSURL *)url; +{ + return [self initWithURL:url protocols:nil]; +} + +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols; +{ + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; + return [self initWithURLRequest:request protocols:protocols]; +} + +- (void)_SR_commonInit; +{ + _readyState = SR_CONNECTING; + + _consumerStopped = YES; + + _webSocketVersion = 13; + + _workQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + + // Going to set a specific on the queue so we can validate we're on the work queue + dispatch_queue_set_specific(_workQueue, (__bridge void *)self, maybe_bridge(_workQueue), NULL); + + sr_dispatch_retain(_delegateDispatchQueue); + + _readBuffer = [[NSMutableData alloc] init]; + _outputBuffer = [[NSMutableData alloc] init]; + + _currentFrameData = [[NSMutableData alloc] init]; + + _consumers = [[NSMutableArray alloc] init]; + + _consumerPool = [[FSRIOConsumerPool alloc] init]; + + _scheduledRunloops = [[NSMutableSet alloc] init]; + + [self _initializeStreams]; + + // default handlers +} + +- (void)assertOnWorkQueue; +{ + assert(dispatch_get_specific((__bridge void *)self) == maybe_bridge(_workQueue)); +} + +- (void)dealloc +{ + _inputStream.delegate = nil; + _outputStream.delegate = nil; + + [_inputStream close]; + [_outputStream close]; + + sr_dispatch_release(_workQueue); + _workQueue = NULL; + + if (_receivedHTTPHeaders) { + CFRelease(_receivedHTTPHeaders); + _receivedHTTPHeaders = NULL; + } + + if (_delegateDispatchQueue) { + sr_dispatch_release(_delegateDispatchQueue); + _delegateDispatchQueue = NULL; + } +} + +#ifndef NDEBUG + +- (void)setReadyState:(FSRReadyState)aReadyState; +{ + [self willChangeValueForKey:@"readyState"]; + assert(aReadyState > _readyState); + _readyState = aReadyState; + [self didChangeValueForKey:@"readyState"]; +} + +#endif + +- (void)open; +{ + assert(_url); + NSAssert(_readyState == SR_CONNECTING, @"Cannot call -(void)open on SRWebSocket more than once"); + + _selfRetain = self; + + [self _connect]; +} + +// Calls block on delegate queue +- (void)_performDelegateBlock:(dispatch_block_t)block; +{ + if (_delegateOperationQueue) { + [_delegateOperationQueue addOperationWithBlock:block]; + } else { + assert(_delegateDispatchQueue); + dispatch_async(_delegateDispatchQueue, block); + } +} + +- (void)setDelegateDispatchQueue:(dispatch_queue_t)queue; +{ + if (queue) { + sr_dispatch_retain(queue); + } + + if (_delegateDispatchQueue) { + sr_dispatch_release(_delegateDispatchQueue); + } + + _delegateDispatchQueue = queue; +} + +- (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage; +{ + NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept"))); + + if (acceptHeader == nil) { + return NO; + } + + NSString *concattedString = [_secKey stringByAppendingString:SRWebSocketAppendToSecKeyString]; + NSString *expectedAccept = [concattedString stringBySHA1ThenBase64Encoding]; + + return [acceptHeader isEqualToString:expectedAccept]; +} + +- (void)_HTTPHeadersDidFinish; +{ + NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders); + + if (responseCode >= 400) { + SRFastLog(@"Request failed with response code %d", responseCode); + [self _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:2132 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"received bad response code from server %u", (int)responseCode] forKey:NSLocalizedDescriptionKey]]]; + return; + + } + + if(![self _checkHandshake:_receivedHTTPHeaders]) { + [self _failWithError:[NSError errorWithDomain:FSRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Invalid Sec-WebSocket-Accept response"] forKey:NSLocalizedDescriptionKey]]]; + return; + } + + NSString *negotiatedProtocol = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(_receivedHTTPHeaders, CFSTR("Sec-WebSocket-Protocol"))); + if (negotiatedProtocol) { + // Make sure we requested the protocol + if ([_requestedProtocols indexOfObject:negotiatedProtocol] == NSNotFound) { + [self _failWithError:[NSError errorWithDomain:FSRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Server specified Sec-WebSocket-Protocol that wasn't requested"] forKey:NSLocalizedDescriptionKey]]]; + return; + } + + _protocol = negotiatedProtocol; + } + + self.readyState = SR_OPEN; + + if (!_didFail) { + [self _readFrameNew]; + } + + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocketDidOpen:)]) { + [self.delegate webSocketDidOpen:self]; + }; + }]; +} + + +- (void)_readHTTPHeader; +{ + if (_receivedHTTPHeaders == NULL) { + _receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO); + } + + [self _readUntilHeaderCompleteWithCallback:^(FSRWebSocket *self, NSData *data) { + CFHTTPMessageAppendBytes(self->_receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length); + + if (CFHTTPMessageIsHeaderComplete(self->_receivedHTTPHeaders)) { + SRFastLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(self->_receivedHTTPHeaders))); + [self _HTTPHeadersDidFinish]; + } else { + [self _readHTTPHeader]; + } + }]; +} + +- (void)didConnect +{ + SRFastLog(@"Connected"); + CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1); + + // Set host first so it defaults + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Host"), (__bridge CFStringRef) + (_url.port != nil ? [NSString stringWithFormat:@"%@:%@", + _url.host, _url.port] : _url.host)); + + NSMutableData *keyBytes = [[NSMutableData alloc] initWithLength:16]; + int result = SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes); + assert(result == 0); + _secKey = [FSRUtilities base64EncodedStringFromData:keyBytes]; + assert([_secKey length] == 24); + + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Upgrade"), CFSTR("websocket")); + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Upgrade")); + if (_userAgent) { + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), (__bridge CFStringRef)_userAgent); + } + + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)_secKey); + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)[NSString stringWithFormat:@"%u", (int)_webSocketVersion]); + + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.SR_origin); + + if (_requestedProtocols) { + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Protocol"), (__bridge CFStringRef)[_requestedProtocols componentsJoinedByString:@", "]); + } + + [_urlRequest.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)key, (__bridge CFStringRef)obj); + }]; + + NSData *message = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(request)); + + CFRelease(request); + + [self _writeData:message]; + [self _readHTTPHeader]; +} + +//- (void)_connectToHost:(NSString *)host port:(NSInteger)port; +- (void)_initializeStreams; +{ + NSInteger port = _url.port.integerValue; + if (port == 0) { + if (!_secure) { + port = 80; + } else { + port = 443; + } + } + NSString *host = _url.host; + + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + + CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, (int)port, &readStream, &writeStream); + + // XXX + CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground); + CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeBackground); + + _outputStream = CFBridgingRelease(writeStream); + _inputStream = CFBridgingRelease(readStream); + + + if (_secure) { + NSMutableDictionary *SSLOptions = [[NSMutableDictionary alloc] init]; + + [_outputStream setProperty:(__bridge id)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel]; + + // If we're using pinned certs, don't validate the certificate chain + if ([_urlRequest FSR_SSLPinnedCertificates].count) { + [SSLOptions setValue:[NSNumber numberWithBool:NO] forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain]; + } + + [_outputStream setProperty:SSLOptions + forKey:(__bridge id)kCFStreamPropertySSLSettings]; + } + + _inputStream.delegate = self; + _outputStream.delegate = self; + + [_outputStream open]; + [_inputStream open]; +} + +- (void)_connect; +{ + if (!_scheduledRunloops.count) { + [self scheduleInRunLoop:[NSRunLoop FSR_networkRunLoop] forMode:NSDefaultRunLoopMode]; + } + + + [_outputStream open]; + [_inputStream open]; +} + +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +{ + [_outputStream scheduleInRunLoop:aRunLoop forMode:mode]; + [_inputStream scheduleInRunLoop:aRunLoop forMode:mode]; + + [_scheduledRunloops addObject:@[aRunLoop, mode]]; +} + +- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +{ + [_outputStream removeFromRunLoop:aRunLoop forMode:mode]; + [_inputStream removeFromRunLoop:aRunLoop forMode:mode]; + + [_scheduledRunloops removeObject:@[aRunLoop, mode]]; +} + +- (void)close; +{ + [self closeWithCode:-1 reason:nil]; +} + +- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason; +{ + assert(code); + dispatch_async(_workQueue, ^{ + if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) { + return; + } + + BOOL wasConnecting = self.readyState == SR_CONNECTING; + + self.readyState = SR_CLOSING; + + SRFastLog(@"Closing with code %d reason %@", code, reason); + + if (wasConnecting) { + [self _disconnect]; + return; + } + + size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize]; + NSData *payload = mutablePayload; + + ((uint16_t *)mutablePayload.mutableBytes)[0] = EndianU16_BtoN(code); + + if (reason) { + NSRange remainingRange = {0}; + + NSUInteger usedLength = 0; + + BOOL success = [reason getBytes:(char *)mutablePayload.mutableBytes + sizeof(uint16_t) maxLength:payload.length - sizeof(uint16_t) usedLength:&usedLength encoding:NSUTF8StringEncoding options:NSStringEncodingConversionExternalRepresentation range:NSMakeRange(0, reason.length) remainingRange:&remainingRange]; + + assert(success); + assert(remainingRange.length == 0); + + if (usedLength != maxMsgSize) { + payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))]; + } + } + + + [self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload]; + }); +} + +- (void)_closeWithProtocolError:(NSString *)message; +{ + // Need to shunt this on the _callbackQueue first to see if they received any messages + [self _performDelegateBlock:^{ + [self closeWithCode:SRStatusCodeProtocolError reason:message]; + dispatch_async(self->_workQueue, ^{ + [self _disconnect]; + }); + }]; +} + +- (void)_failWithError:(NSError *)error; +{ + dispatch_async(_workQueue, ^{ + if (self.readyState != SR_CLOSED) { + self->_failed = YES; + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) { + [self.delegate webSocket:self didFailWithError:error]; + } + }]; + + self.readyState = SR_CLOSED; + + SRFastLog(@"Failing with error %@", error.localizedDescription); + + [self _disconnect]; + [self _scheduleCleanup]; + } + }); +} + +- (void)_writeData:(NSData *)data; +{ + [self assertOnWorkQueue]; + + if (_closeWhenFinishedWriting) { + return; + } + [_outputBuffer appendData:data]; + [self _pumpWriting]; +} +- (void)send:(id)data; +{ + SRFastLog(@"Sending data %@", data); + NSAssert(self.readyState != SR_CONNECTING, @"Invalid State: Cannot call send: until connection is open"); + // TODO: maybe not copy this for performance + data = [data copy]; + dispatch_async(_workQueue, ^{ + if ([data isKindOfClass:[NSString class]]) { + [self _sendFrameWithOpcode:SROpCodeTextFrame data:[(NSString *)data dataUsingEncoding:NSUTF8StringEncoding]]; + } else if ([data isKindOfClass:[NSData class]]) { + [self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data]; + } else if (data == nil) { + [self _sendFrameWithOpcode:SROpCodeTextFrame data:data]; + } else { + assert(NO); + } + }); +} + +- (void)handlePing:(NSData *)pingData; +{ + // Need to pingpong this off _callbackQueue first to make sure messages happen in order + [self _performDelegateBlock:^{ + dispatch_async(self->_workQueue, ^{ + [self _sendFrameWithOpcode:SROpCodePong data:pingData]; + }); + }]; +} + +- (void)handlePong; +{ + // NOOP +} + +- (void)_handleMessage:(id)message +{ + SRFastLog(@"Received message"); + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)]) { + [self.delegate webSocket:self didReceiveMessage:message]; + } + }]; +} + + +static inline BOOL closeCodeIsValid(int closeCode) { + if (closeCode < 1000) { + return NO; + } + + if (closeCode >= 1000 && closeCode <= 1011) { + if (closeCode == 1004 || + closeCode == 1005 || + closeCode == 1006) { + return NO; + } + return YES; + } + + if (closeCode >= 3000 && closeCode <= 3999) { + return YES; + } + + if (closeCode >= 4000 && closeCode <= 4999) { + return YES; + } + + return NO; +} + +// Note from RFC: +// +// If there is a body, the first two +// bytes of the body MUST be a 2-byte unsigned integer (in network byte +// order) representing a status code with value /code/ defined in +// Section 7.4. Following the 2-byte integer the body MAY contain UTF-8 +// encoded data with value /reason/, the interpretation of which is not +// defined by this specification. + +- (void)handleCloseWithData:(NSData *)data; +{ + size_t dataSize = data.length; + __block uint16_t closeCode = 0; + + SRFastLog(@"Received close frame"); + + if (dataSize == 1) { + // TODO handle error + [self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"]; + return; + } else if (dataSize >= 2) { + [data getBytes:&closeCode length:sizeof(closeCode)]; + _closeCode = EndianU16_BtoN(closeCode); + if (!closeCodeIsValid(_closeCode)) { + [self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]]; + return; + } + if (dataSize > 2) { + _closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding]; + if (!_closeReason) { + [self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"]; + return; + } + } + } else { + _closeCode = SRStatusNoStatusReceived; + } + + [self assertOnWorkQueue]; + + if (self.readyState == SR_OPEN) { + [self closeWithCode:1000 reason:nil]; + } + dispatch_async(_workQueue, ^{ + [self _disconnect]; + }); +} + +- (void)_disconnect; +{ + [self assertOnWorkQueue]; + SRFastLog(@"Trying to disconnect"); + _closeWhenFinishedWriting = YES; + [self _pumpWriting]; +} + +- (void)_handleFrameWithData:(NSData *)frameData opCode:(NSInteger)opcode; +{ + // Check that the current data is valid UTF8 + + BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose); + if (!isControlFrame) { + [self _readFrameNew]; + } else { + dispatch_async(_workQueue, ^{ + [self _readFrameContinue]; + }); + } + + switch (opcode) { + case SROpCodeTextFrame: { + NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding]; + if (str == nil && frameData) { + [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"]; + dispatch_async(_workQueue, ^{ + [self _disconnect]; + }); + + return; + } + [self _handleMessage:str]; + break; + } + case SROpCodeBinaryFrame: + [self _handleMessage:[frameData copy]]; + break; + case SROpCodeConnectionClose: + [self handleCloseWithData:frameData]; + break; + case SROpCodePing: + [self handlePing:frameData]; + break; + case SROpCodePong: + [self handlePong]; + break; + default: + [self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %u", (int)opcode]]; + // TODO: Handle invalid opcode + break; + } +} + +- (void)_handleFrameHeader:(frame_header)frame_header curData:(NSData *)curData; +{ + assert(frame_header.opcode != 0); + + if (self.readyState != SR_OPEN) { + return; + } + + + BOOL isControlFrame = (frame_header.opcode == SROpCodePing || frame_header.opcode == SROpCodePong || frame_header.opcode == SROpCodeConnectionClose); + + if (isControlFrame && !frame_header.fin) { + [self _closeWithProtocolError:@"Fragmented control frames not allowed"]; + return; + } + + if (isControlFrame && frame_header.payload_length >= 126) { + [self _closeWithProtocolError:@"Control frames cannot have payloads larger than 126 bytes"]; + return; + } + + if (!isControlFrame) { + _currentFrameOpcode = frame_header.opcode; + _currentFrameCount += 1; + } + + if (frame_header.payload_length == 0) { + if (isControlFrame) { + [self _handleFrameWithData:curData opCode:frame_header.opcode]; + } else { + if (frame_header.fin) { + [self _handleFrameWithData:_currentFrameData opCode:frame_header.opcode]; + } else { + // TODO add assert that opcode is not a control; + [self _readFrameContinue]; + } + } + } else { + [self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(FSRWebSocket *self, NSData *newData) { + if (isControlFrame) { + [self _handleFrameWithData:newData opCode:frame_header.opcode]; + } else { + if (frame_header.fin) { + [self _handleFrameWithData:self->_currentFrameData opCode:frame_header.opcode]; + } else { + // TODO add assert that opcode is not a control; + [self _readFrameContinue]; + } + + } + } readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked]; + } +} + +/* From RFC: + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ + */ + +static const uint8_t SRFinMask = 0x80; +static const uint8_t SROpCodeMask = 0x0F; +static const uint8_t SRRsvMask = 0x70; +static const uint8_t SRMaskMask = 0x80; +static const uint8_t SRPayloadLenMask = 0x7F; + + +- (void)_readFrameContinue; +{ + assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0)); + + [self _addConsumerWithDataLength:2 callback:^(FSRWebSocket *self, NSData *data) { + __block frame_header header = {0}; + + const uint8_t *headerBuffer = data.bytes; + assert(data.length >= 2); + + if (headerBuffer[0] & SRRsvMask) { + [self _closeWithProtocolError:@"Server used RSV bits"]; + return; + } + + uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]); + + BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose); + + if (!isControlFrame && receivedOpcode != 0 && self->_currentFrameCount > 0) { + [self _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"]; + return; + } + + if (receivedOpcode == 0 && self->_currentFrameCount == 0) { + [self _closeWithProtocolError:@"cannot continue a message"]; + return; + } + + header.opcode = receivedOpcode == 0 ? self->_currentFrameOpcode : receivedOpcode; + + header.fin = !!(SRFinMask & headerBuffer[0]); + + + header.masked = !!(SRMaskMask & headerBuffer[1]); + header.payload_length = SRPayloadLenMask & headerBuffer[1]; + + headerBuffer = NULL; + + if (header.masked) { + [self _closeWithProtocolError:@"Client must receive unmasked data"]; + } + + size_t extra_bytes_needed = header.masked ? sizeof(self->_currentReadMaskKey) : 0; + + if (header.payload_length == 126) { + extra_bytes_needed += sizeof(uint16_t); + } else if (header.payload_length == 127) { + extra_bytes_needed += sizeof(uint64_t); + } + + if (extra_bytes_needed == 0) { + [self _handleFrameHeader:header curData:self->_currentFrameData]; + } else { + [self _addConsumerWithDataLength:extra_bytes_needed callback:^(FSRWebSocket *self, NSData *data) { + size_t mapped_size = data.length; + const void *mapped_buffer = data.bytes; + size_t offset = 0; + + if (header.payload_length == 126) { + assert(mapped_size >= sizeof(uint16_t)); + uint16_t newLen = EndianU16_BtoN(*(uint16_t *)(mapped_buffer)); + header.payload_length = newLen; + offset += sizeof(uint16_t); + } else if (header.payload_length == 127) { + assert(mapped_size >= sizeof(uint64_t)); + header.payload_length = EndianU64_BtoN(*(uint64_t *)(mapped_buffer)); + offset += sizeof(uint64_t); + } else { + assert(header.payload_length < 126 && header.payload_length >= 0); + } + + + if (header.masked) { + assert(mapped_size >= sizeof(self->_currentReadMaskOffset) + offset); + memcpy(self->_currentReadMaskKey, ((uint8_t *)mapped_buffer) + offset, sizeof(self->_currentReadMaskKey)); + } + + [self _handleFrameHeader:header curData:self->_currentFrameData]; + } readToCurrentFrame:NO unmaskBytes:NO]; + } + } readToCurrentFrame:NO unmaskBytes:NO]; +} + +- (void)_readFrameNew; +{ + dispatch_async(_workQueue, ^{ + [self->_currentFrameData setLength:0]; + + self->_currentFrameOpcode = 0; + self->_currentFrameCount = 0; + self->_readOpCount = 0; + self->_currentStringScanPosition = 0; + + [self _readFrameContinue]; + }); +} + +- (void)_pumpWriting; +{ + [self assertOnWorkQueue]; + + NSUInteger dataLength = _outputBuffer.length; + if (dataLength - _outputBufferOffset > 0 && _outputStream.hasSpaceAvailable) { + NSUInteger bytesWritten = [_outputStream write:_outputBuffer.bytes + _outputBufferOffset maxLength:dataLength - _outputBufferOffset]; + if (bytesWritten == -1) { + [self _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:2145 userInfo:[NSDictionary dictionaryWithObject:@"Error writing to stream" forKey:NSLocalizedDescriptionKey]]]; + return; + } + + _outputBufferOffset += bytesWritten; + + if (_outputBufferOffset > 4096 && _outputBufferOffset > (_outputBuffer.length >> 1)) { + _outputBuffer = [[NSMutableData alloc] initWithBytes:(char *)_outputBuffer.bytes + _outputBufferOffset length:_outputBuffer.length - _outputBufferOffset]; + _outputBufferOffset = 0; + } + } + + if (_closeWhenFinishedWriting && + _outputBuffer.length - _outputBufferOffset == 0 && + (_inputStream.streamStatus != NSStreamStatusNotOpen && + _inputStream.streamStatus != NSStreamStatusClosed) && + !_sentClose) { + _sentClose = YES; + + @synchronized (self) { + [_outputStream close]; + [_inputStream close]; + + // TODO: Why are we missing the SocketRocket code to call unscheduleFromRunLoop??? + } + + if (!_failed) { + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) { + [self.delegate webSocket:self didCloseWithCode:self->_closeCode reason:self->_closeReason wasClean:YES]; + } + }]; + } + [self _scheduleCleanup]; + } +} + +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback; +{ + [self assertOnWorkQueue]; + [self _addConsumerWithScanner:consumer callback:callback dataLength:0]; +} + +- (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + [self assertOnWorkQueue]; + assert(dataLength); + + [_consumers addObject:[_consumerPool consumerWithScanner:nil handler:callback bytesNeeded:dataLength readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]]; + [self _pumpScanner]; +} + +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength; +{ + [self assertOnWorkQueue]; + [_consumers addObject:[_consumerPool consumerWithScanner:consumer handler:callback bytesNeeded:dataLength readToCurrentFrame:NO unmaskBytes:NO]]; + [self _pumpScanner]; +} + + +- (void)_scheduleCleanup +{ + @synchronized(self) { + if (_cleanupScheduled) { + return; + } + + _cleanupScheduled = YES; + + // Cleanup NSStream delegate's in the same RunLoop used by the streams themselves: + // This way we'll prevent race conditions between handleEvent and SRWebsocket's dealloc + NSTimer *timer = [NSTimer timerWithTimeInterval:(0.0f) target:self selector:@selector(_cleanupSelfReference:) userInfo:nil repeats:NO]; + [[NSRunLoop FSR_networkRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; + } +} + +- (void)_cleanupSelfReference:(NSTimer *)timer +{ + @synchronized(self) { + // Nuke NSStream delegate's + _inputStream.delegate = nil; + _outputStream.delegate = nil; + + // Remove the streams, right now, from the networkRunLoop + [_inputStream close]; + [_outputStream close]; + } + + // Cleanup selfRetain in the same GCD queue as usual + dispatch_async(_workQueue, ^{ + self->_selfRetain = nil; + }); +} + + +static const char CRLFCRLFBytes[] = {'\r', '\n', '\r', '\n'}; + +- (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler; +{ + [self _readUntilBytes:CRLFCRLFBytes length:sizeof(CRLFCRLFBytes) callback:dataHandler]; +} + +- (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler; +{ + // TODO optimize so this can continue from where we last searched + stream_scanner consumer = ^size_t(NSData *data) { + __block size_t found_size = 0; + __block size_t match_count = 0; + + size_t size = data.length; + const unsigned char *buffer = data.bytes; + for (int i = 0; i < size; i++ ) { + if (((const unsigned char *)buffer)[i] == ((const unsigned char *)bytes)[match_count]) { + match_count += 1; + if (match_count == length) { + found_size = i + 1; + break; + } + } else { + match_count = 0; + } + } + return found_size; + }; + [self _addConsumerWithScanner:consumer callback:dataHandler]; +} + + +// Returns true if did work +- (BOOL)_innerPumpScanner { + + BOOL didWork = NO; + + if (self.readyState >= SR_CLOSING) { + return didWork; + } + + if (!_consumers.count) { + return didWork; + } + + size_t curSize = _readBuffer.length - _readBufferOffset; + if (!curSize) { + return didWork; + } + + FSRIOConsumer *consumer = [_consumers objectAtIndex:0]; + + size_t bytesNeeded = consumer.bytesNeeded; + + size_t foundSize = 0; + if (consumer.consumer) { + NSData *tempView = [NSData dataWithBytesNoCopy:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset freeWhenDone:NO]; + foundSize = consumer.consumer(tempView); + } else { + assert(consumer.bytesNeeded); + if (curSize >= bytesNeeded) { + foundSize = bytesNeeded; + } else if (consumer.readToCurrentFrame) { + foundSize = curSize; + } + } + + NSData *slice = nil; + if (consumer.readToCurrentFrame || foundSize) { + NSRange sliceRange = NSMakeRange(_readBufferOffset, foundSize); + slice = [_readBuffer subdataWithRange:sliceRange]; + + _readBufferOffset += foundSize; + + if (_readBufferOffset > 4096 && _readBufferOffset > (_readBuffer.length >> 1)) { + _readBuffer = [[NSMutableData alloc] initWithBytes:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset]; _readBufferOffset = 0; + } + + if (consumer.unmaskBytes) { + NSMutableData *mutableSlice = [slice mutableCopy]; + + NSUInteger len = mutableSlice.length; + uint8_t *bytes = mutableSlice.mutableBytes; + + for (int i = 0; i < len; i++) { + bytes[i] = bytes[i] ^ _currentReadMaskKey[_currentReadMaskOffset % sizeof(_currentReadMaskKey)]; + _currentReadMaskOffset += 1; + } + + slice = mutableSlice; + } + + if (consumer.readToCurrentFrame) { + [_currentFrameData appendData:slice]; + + _readOpCount += 1; + + if (_currentFrameOpcode == SROpCodeTextFrame) { + // Validate UTF8 stuff. + size_t currentDataSize = _currentFrameData.length; + if (_currentFrameOpcode == SROpCodeTextFrame && currentDataSize > 0) { + // TODO: Optimize the crap out of this. Don't really have to copy all the data each time + + size_t scanSize = currentDataSize - _currentStringScanPosition; + + NSData *scan_data = [_currentFrameData subdataWithRange:NSMakeRange(_currentStringScanPosition, scanSize)]; + int32_t valid_utf8_size = validate_dispatch_data_partial_string(scan_data); + + if (valid_utf8_size == -1) { + [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"]; + dispatch_async(_workQueue, ^{ + [self _disconnect]; + }); + return didWork; + } else { + _currentStringScanPosition += valid_utf8_size; + } + } + + } + + consumer.bytesNeeded -= foundSize; + + if (consumer.bytesNeeded == 0) { + [_consumers removeObjectAtIndex:0]; + consumer.handler(self, nil); + didWork = YES; + } + } else if (foundSize) { + [_consumers removeObjectAtIndex:0]; + consumer.handler(self, slice); + didWork = YES; + } + } + return didWork; +} + +-(void)_pumpScanner; +{ + [self assertOnWorkQueue]; + + if (!_isPumping) { + _isPumping = YES; + } else { + return; + } + + while ([self _innerPumpScanner]) { + + } + + _isPumping = NO; +} + +//#define NOMASK + +static const size_t SRFrameHeaderOverhead = 32; + +- (void)_sendFrameWithOpcode:(FSROpCode)opcode data:(id)data; +{ + [self assertOnWorkQueue]; + + NSAssert(data == nil || [data isKindOfClass:[NSData class]] || [data isKindOfClass:[NSString class]], @"Function expects nil, NSString or NSData"); + + size_t payloadLength = [data isKindOfClass:[NSString class]] ? [(NSString *)data lengthOfBytesUsingEncoding:NSUTF8StringEncoding] : [data length]; + + NSMutableData *frame = [[NSMutableData alloc] initWithLength:payloadLength + SRFrameHeaderOverhead]; + if (!frame) { + [self closeWithCode:SRStatusCodeMessageTooBig reason:@"Message too big"]; + return; + } + uint8_t *frame_buffer = (uint8_t *)[frame mutableBytes]; + + // set fin + frame_buffer[0] = SRFinMask | opcode; + + BOOL useMask = YES; +#ifdef NOMASK + useMask = NO; +#endif + + if (useMask) { + // set the mask and header + frame_buffer[1] |= SRMaskMask; + } + + size_t frame_buffer_size = 2; + + const uint8_t *unmasked_payload = NULL; + if ([data isKindOfClass:[NSData class]]) { + unmasked_payload = (uint8_t *)[data bytes]; + } else if ([data isKindOfClass:[NSString class]]) { + unmasked_payload = (const uint8_t *)[data UTF8String]; + } else { + assert(NO); + } + + if (payloadLength < 126) { + frame_buffer[1] |= payloadLength; + } else if (payloadLength <= UINT16_MAX) { + frame_buffer[1] |= 126; + *((uint16_t *)(frame_buffer + frame_buffer_size)) = EndianU16_BtoN((uint16_t)payloadLength); + frame_buffer_size += sizeof(uint16_t); + } else { + frame_buffer[1] |= 127; + *((uint64_t *)(frame_buffer + frame_buffer_size)) = EndianU64_BtoN((uint64_t)payloadLength); + frame_buffer_size += sizeof(uint64_t); + } + + if (!useMask) { + for (int i = 0; i < payloadLength; i++) { + frame_buffer[frame_buffer_size] = unmasked_payload[i]; + frame_buffer_size += 1; + } + } else { + uint8_t *mask_key = frame_buffer + frame_buffer_size; + int result = SecRandomCopyBytes(kSecRandomDefault, sizeof(uint32_t), (uint8_t *)mask_key); + assert(result == 0); + frame_buffer_size += sizeof(uint32_t); + + // TODO: could probably optimize this with SIMD + for (int i = 0; i < payloadLength; i++) { + frame_buffer[frame_buffer_size] = unmasked_payload[i] ^ mask_key[i % sizeof(uint32_t)]; + frame_buffer_size += 1; + } + } + + assert(frame_buffer_size <= [frame length]); + frame.length = frame_buffer_size; + + [self _writeData:frame]; +} + +- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode; +{ + __weak __typeof__(self) weakSelf = self; + + // turn on keep-alive for the output stream. + if (eventCode == NSStreamEventOpenCompleted && aStream == _outputStream) { + CFDataRef socketData = CFWriteStreamCopyProperty((CFWriteStreamRef)_outputStream, kCFStreamPropertySocketNativeHandle); + // In rare cases socketData might be nil (there are crash reports out there), in which case we'll have to just + // live without keep-alive :( + if (socketData != nil) { + CFSocketNativeHandle socket; + CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&socket); + CFRelease(socketData); + + int keepAliveOn = 1; + if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &keepAliveOn, sizeof(keepAliveOn)) == -1) { + SRFastLog(@"Failed to turn on TCP keepalive for websocket"); + } + } + } + + if (_secure && !_pinnedCertFound && (eventCode == NSStreamEventHasBytesAvailable || eventCode == NSStreamEventHasSpaceAvailable)) { + + NSArray *sslCerts = [_urlRequest FSR_SSLPinnedCertificates]; + if (sslCerts) { + SecTrustRef secTrust = (__bridge SecTrustRef)[aStream propertyForKey:(__bridge id)kCFStreamPropertySSLPeerTrust]; + if (secTrust) { + NSInteger numCerts = SecTrustGetCertificateCount(secTrust); + for (NSInteger i = 0; i < numCerts && !_pinnedCertFound; i++) { + SecCertificateRef cert = SecTrustGetCertificateAtIndex(secTrust, i); + NSData *certData = CFBridgingRelease(SecCertificateCopyData(cert)); + + for (id ref in sslCerts) { + SecCertificateRef trustedCert = (__bridge SecCertificateRef)ref; + NSData *trustedCertData = CFBridgingRelease(SecCertificateCopyData(trustedCert)); + + if ([trustedCertData isEqualToData:certData]) { + _pinnedCertFound = YES; + break; + } + } + } + } + + if (!_pinnedCertFound) { + dispatch_async(_workQueue, ^{ + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"Invalid server cert" }; + [weakSelf _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:23556 userInfo:userInfo]]; + }); + return; + } + } + } + + // SRFastLog(@"%@ Got stream event %d", aStream, eventCode); + dispatch_async(_workQueue, ^{ + [weakSelf safeHandleEvent:eventCode stream:aStream]; + }); +} + +- (void)safeHandleEvent:(NSStreamEvent)eventCode stream:(NSStream *)aStream +{ + switch (eventCode) { + case NSStreamEventOpenCompleted: { + SRFastLog(@"NSStreamEventOpenCompleted %@", aStream); + if (self.readyState >= SR_CLOSING) { + return; + } + + + assert(_readBuffer); + + if (self.readyState == SR_CONNECTING && aStream == _inputStream) { + [self didConnect]; + } + [self _pumpWriting]; + [self _pumpScanner]; + break; + } + + case NSStreamEventErrorOccurred: { + SRFastLog(@"NSStreamEventErrorOccurred %@ %@", aStream, [[aStream streamError] copy]); + /// TODO specify error better! + [self _failWithError:aStream.streamError]; + _readBufferOffset = 0; + [_readBuffer setLength:0]; + break; + + } + + case NSStreamEventEndEncountered: { + [self _pumpScanner]; + SRFastLog(@"NSStreamEventEndEncountered %@", aStream); + if (aStream.streamError) { + [self _failWithError:aStream.streamError]; + } else { + dispatch_async(_workQueue, ^{ + if (self.readyState != SR_CLOSED) { + self.readyState = SR_CLOSED; + [self _scheduleCleanup]; + } + + if (!self->_sentClose && !self->_failed) { + self->_sentClose = YES; + // If we get closed in this state it's probably not clean because we should be sending this when we send messages + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) { + [self.delegate webSocket:self didCloseWithCode:0 reason:@"Stream end encountered" wasClean:NO]; + } + }]; + } + }); + } + + break; + } + + case NSStreamEventHasBytesAvailable: { + SRFastLog(@"NSStreamEventHasBytesAvailable %@", aStream); + const NSUInteger bufferSize = 2048; + uint8_t buffer[bufferSize]; + + while (_inputStream.hasBytesAvailable) { + NSInteger bytes_read = [_inputStream read:buffer maxLength:bufferSize]; + + if (bytes_read > 0) { + [_readBuffer appendBytes:buffer length:bytes_read]; + } else if (bytes_read < 0) { + [self _failWithError:_inputStream.streamError]; + } + + if (bytes_read != bufferSize) { + break; + } + }; + [self _pumpScanner]; + break; + } + + case NSStreamEventHasSpaceAvailable: { + SRFastLog(@"NSStreamEventHasSpaceAvailable %@", aStream); + [self _pumpWriting]; + break; + } + + default: + SRFastLog(@"(default) %@", aStream); + break; + } +} + +@end + + +@implementation FSRIOConsumer + +@synthesize bytesNeeded = _bytesNeeded; +@synthesize consumer = _scanner; +@synthesize handler = _handler; +@synthesize readToCurrentFrame = _readToCurrentFrame; +@synthesize unmaskBytes = _unmaskBytes; + +- (void)setupWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + _scanner = [scanner copy]; + _handler = [handler copy]; + _bytesNeeded = bytesNeeded; + _readToCurrentFrame = readToCurrentFrame; + _unmaskBytes = unmaskBytes; + assert(_scanner || _bytesNeeded); +} + +@end + +@implementation FSRIOConsumerPool { + NSUInteger _poolSize; + NSMutableArray *_bufferedConsumers; +} + +- (id)initWithBufferCapacity:(NSUInteger)poolSize; +{ + self = [super init]; + if (self) { + _poolSize = poolSize; + _bufferedConsumers = [[NSMutableArray alloc] initWithCapacity:poolSize]; + } + return self; +} + +- (id)init +{ + return [self initWithBufferCapacity:8]; +} + +- (FSRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + FSRIOConsumer *consumer = nil; + if (_bufferedConsumers.count) { + consumer = [_bufferedConsumers lastObject]; + [_bufferedConsumers removeLastObject]; + } else { + consumer = [[FSRIOConsumer alloc] init]; + } + + [consumer setupWithScanner:scanner handler:handler bytesNeeded:bytesNeeded readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]; + + return consumer; +} + +- (void)returnConsumer:(FSRIOConsumer *)consumer; +{ + if (_bufferedConsumers.count < _poolSize) { + [_bufferedConsumers addObject:consumer]; + } +} + +@end + +@implementation NSURLRequest (FCertificateAdditions) + +- (NSArray *)FSR_SSLPinnedCertificates; +{ + return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self]; +} + +@end + +@implementation NSMutableURLRequest (FCertificateAdditions) + +- (NSArray *)FSR_SSLPinnedCertificates; +{ + return [NSURLProtocol propertyForKey:@"FSR_SSLPinnedCertificates" inRequest:self]; +} + +- (void)setFSR_SSLPinnedCertificates:(NSArray *)FSR_SSLPinnedCertificates; +{ + [NSURLProtocol setProperty:FSR_SSLPinnedCertificates forKey:@"FSR_SSLPinnedCertificates" inRequest:self]; +} + +@end + +@implementation NSURL (FSRWebSocket) + +- (NSString *)SR_origin; +{ + NSString *scheme = [self.scheme lowercaseString]; + + if ([scheme isEqualToString:@"wss"]) { + scheme = @"https"; + } else if ([scheme isEqualToString:@"ws"]) { + scheme = @"http"; + } + + if (self.port != nil) { + return [NSString stringWithFormat:@"%@://%@:%@/", scheme, self.host, self.port]; + } else { + return [NSString stringWithFormat:@"%@://%@/", scheme, self.host]; + } +} + +@end + +// #define SR_ENABLE_LOG + +static inline void SRFastLog(NSString *format, ...) { +#ifdef SR_ENABLE_LOG + __block va_list arg_list; + va_start (arg_list, format); + + NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arg_list]; + + va_end(arg_list); + + NSLog(@"[SR] %@", formattedString); +#endif +} + + +#ifdef HAS_ICU + +static inline int32_t validate_dispatch_data_partial_string(NSData *data) { + + const void * contents = [data bytes]; + long size = [data length]; + + const uint8_t *str = (const uint8_t *)contents; + + + UChar32 codepoint = 1; + int32_t offset = 0; + int32_t lastOffset = 0; + while(offset < size && codepoint > 0) { + lastOffset = offset; + U8_NEXT(str, offset, size, codepoint); + } + + if (codepoint == -1) { + // Check to see if the last byte is valid or whether it was just continuing + if (!U8_IS_LEAD(str[lastOffset]) || U8_COUNT_TRAIL_BYTES(str[lastOffset]) + lastOffset < (int32_t)size) { + + size = -1; + } else { + uint8_t leadByte = str[lastOffset]; + U8_MASK_LEAD_BYTE(leadByte, U8_COUNT_TRAIL_BYTES(leadByte)); + + for (int i = lastOffset + 1; i < offset; i++) { + + if (U8_IS_SINGLE(str[i]) || U8_IS_LEAD(str[i]) || !U8_IS_TRAIL(str[i])) { + size = -1; + } + } + + if (size != -1) { + size = lastOffset; + } + } + } + + if (size != -1 && ![[NSString alloc] initWithBytesNoCopy:(char *)[data bytes] length:size encoding:NSUTF8StringEncoding freeWhenDone:NO]) { + size = -1; + } + + return (int32_t)size; +} + +#else + +// This is a hack, and probably not optimal +static inline int32_t validate_dispatch_data_partial_string(NSData *data) { + static const int maxCodepointSize = 3; + + for (int i = 0; i < maxCodepointSize; i++) { + NSString *str = [[NSString alloc] initWithBytesNoCopy:(char *)data.bytes length:data.length - i encoding:NSUTF8StringEncoding freeWhenDone:NO]; + if (str) { + return (int)(data.length - i); + } + } + + return -1; +} + +#endif + +static _FSRRunLoopThread *networkThread = nil; +static NSRunLoop *networkRunLoop = nil; + +@implementation NSRunLoop (FSRWebSocket) + ++ (NSRunLoop *)FSR_networkRunLoop { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + networkThread = [[_FSRRunLoopThread alloc] init]; + networkThread.name = @"com.squareup.SocketRocket.NetworkThread"; + [networkThread start]; + networkRunLoop = networkThread.runLoop; + }); + + return networkRunLoop; +} + +@end + + +@implementation _FSRRunLoopThread { + dispatch_group_t _waitGroup; +} + +@synthesize runLoop = _runLoop; + +- (void)dealloc +{ + sr_dispatch_release(_waitGroup); +} + +- (id)init +{ + self = [super init]; + if (self) { + _waitGroup = dispatch_group_create(); + dispatch_group_enter(_waitGroup); + } + return self; +} + + +/** + * This is the main method of the thread on which the socket events are scheduled in a run loop. + */ +- (void)main; +{ + @autoreleasepool { + _runLoop = [NSRunLoop currentRunLoop]; + dispatch_group_leave(_waitGroup); + + // Add an empty run loop source to prevent runloop from spinning. + CFRunLoopSourceContext sourceCtx = { + .version = 0, + .info = NULL, + .retain = NULL, + .release = NULL, + .copyDescription = NULL, + .equal = NULL, + .hash = NULL, + .schedule = NULL, + .cancel = NULL, + .perform = NULL + }; + CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx); + CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); + CFRelease(source); + + while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { + + } + assert(NO); + } +} + +- (NSRunLoop *)runLoop; +{ + dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER); + return _runLoop; +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.h new file mode 100644 index 0000000..bac393b --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.h @@ -0,0 +1,23 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 + +@interface FSRUtilities : NSObject + ++ (NSString *)base64EncodedStringFromData:(NSData *)data; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.m b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.m new file mode 100644 index 0000000..2be1d84 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.m @@ -0,0 +1,37 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "NSData+SRB64Additions.h" +#import "fbase64.h" + +@implementation FSRUtilities + ++ (NSString *)base64EncodedStringFromData:(NSData *)data { + size_t buffer_size = ((data.length * 3 + 2) / 2); + + char *buffer = (char *)malloc(buffer_size); + + int len = f_b64_ntop(data.bytes, data.length, buffer, buffer_size); + + if (len == -1) { + free(buffer); + return nil; + } else{ + return [[NSString alloc] initWithBytesNoCopy:buffer length:len encoding:NSUTF8StringEncoding freeWhenDone:YES]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.c b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.c new file mode 100644 index 0000000..238c23c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.c @@ -0,0 +1,318 @@ +/* $OpenBSD: base64.c,v 1.5 2006/10/21 09:55:03 otto Exp $ */ + +/* + * Copyright (c) 1996 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Portions Copyright (c) 1995 by International Business Machines, Inc. + * + * International Business Machines, Inc. (hereinafter called IBM) grants + * permission under its copyrights to use, copy, modify, and distribute this + * Software with or without fee, provided that the above copyright notice and + * all paragraphs of this notice appear in all copies, and that the name of IBM + * not be used in connection with the marketing of any product incorporating + * the Software or modifications thereof, without specific, written prior + * permission. + * + * To the extent it has a right to do so, IBM grants an immunity from suit + * under its patents, if any, for the use, sale or manufacture of products to + * the extent that such products are used for performing Domain Name System + * dynamic updates in TCP/IP networks by means of the Software. No immunity is + * granted for any product per se or for any other function of any product. + * + * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, + * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING + * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN + * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. + */ + +/* OPENBSD ORIGINAL: lib/libc/net/base64.c */ + + +// +// Distributed with modifications by Firebase ( https://www.firebase.com ) +// + +#if (!defined(HAVE_B64_NTOP) && !defined(HAVE___B64_NTOP)) || (!defined(HAVE_B64_PTON) && !defined(HAVE___B64_PTON)) + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "fbase64.h" + +static const char Base64[] = +"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char Pad64 = '='; + +/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) + The following encoding technique is taken from RFC 1521 by Borenstein + and Freed. It is reproduced here in a slightly edited form for + convenience. + + A 65-character subset of US-ASCII is used, enabling 6 bits to be + represented per printable character. (The extra 65th character, "=", + is used to signify a special processing function.) + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8-bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + + Each 6-bit group is used as an index into an array of 64 printable + characters. The character referenced by the index is placed in the + output string. + + Table 1: The Base64 Alphabet + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a quantity. When fewer than 24 input + bits are available in an input group, zero bits are added (on the + right) to form an integral number of 6-bit groups. Padding at the + end of the data is performed using the '=' character. + + Since all base64 input is an integral number of octets, only the + ------------------------------------------------- + following cases can arise: + + (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded + output will be an integral multiple of 4 characters + with no "=" padding, + (2) the final quantum of encoding input is exactly 8 bits; + here, the final unit of encoded output will be two + characters followed by two "=" padding characters, or + (3) the final quantum of encoding input is exactly 16 bits; + here, the final unit of encoded output will be three + characters followed by one "=" padding character. + */ + +#if !defined(HAVE_B64_NTOP) && !defined(HAVE___B64_NTOP) +int +f_b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize) +{ + size_t datalength = 0; + u_char input[3]; + u_char output[4]; + u_int i; + + while (2 < srclength) { + input[0] = *src++; + input[1] = *src++; + input[2] = *src++; + srclength -= 3; + + output[0] = input[0] >> 2; + output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); + output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); + output[3] = input[2] & 0x3f; + + if (datalength + 4 > targsize) + return (-1); + target[datalength++] = Base64[output[0]]; + target[datalength++] = Base64[output[1]]; + target[datalength++] = Base64[output[2]]; + target[datalength++] = Base64[output[3]]; + } + + /* Now we worry about padding. */ + if (0 != srclength) { + /* Get what's left. */ + input[0] = input[1] = input[2] = '\0'; + for (i = 0; i < srclength; i++) + input[i] = *src++; + + output[0] = input[0] >> 2; + output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); + output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); + + if (datalength + 4 > targsize) + return (-1); + target[datalength++] = Base64[output[0]]; + target[datalength++] = Base64[output[1]]; + if (srclength == 1) + target[datalength++] = Pad64; + else + target[datalength++] = Base64[output[2]]; + target[datalength++] = Pad64; + } + if (datalength >= targsize) + return (-1); + target[datalength] = '\0'; /* Returned value doesn't count \0. */ + return (int)(datalength); +} +#endif /* !defined(HAVE_B64_NTOP) && !defined(HAVE___B64_NTOP) */ + +#if !defined(HAVE_B64_PTON) && !defined(HAVE___B64_PTON) + +/* skips all whitespace anywhere. + converts characters, four at a time, starting at (or after) + src from base - 64 numbers into three 8 bit bytes in the target area. + it returns the number of data bytes stored at the target, or -1 on error. + */ + +int +f_b64_pton(char const *src, u_char *target, size_t targsize) +{ + u_int tarindex, state; + int ch; + char *pos; + + state = 0; + tarindex = 0; + + while ((ch = *src++) != '\0') { + if (isspace(ch)) /* Skip whitespace anywhere. */ + continue; + + if (ch == Pad64) + break; + + pos = strchr(Base64, ch); + if (pos == 0) /* A non-base64 character. */ + return (-1); + + switch (state) { + case 0: + if (target) { + if (tarindex >= targsize) + return (-1); + target[tarindex] = (pos - Base64) << 2; + } + state = 1; + break; + case 1: + if (target) { + if (tarindex + 1 >= targsize) + return (-1); + target[tarindex] |= (pos - Base64) >> 4; + target[tarindex+1] = ((pos - Base64) & 0x0f) + << 4 ; + } + tarindex++; + state = 2; + break; + case 2: + if (target) { + if (tarindex + 1 >= targsize) + return (-1); + target[tarindex] |= (pos - Base64) >> 2; + target[tarindex+1] = ((pos - Base64) & 0x03) + << 6; + } + tarindex++; + state = 3; + break; + case 3: + if (target) { + if (tarindex >= targsize) + return (-1); + target[tarindex] |= (pos - Base64); + } + tarindex++; + state = 0; + break; + } + } + + /* + * We are done decoding Base-64 chars. Let's see if we ended + * on a byte boundary, and/or with erroneous trailing characters. + */ + + if (ch == Pad64) { /* We got a pad char. */ + ch = *src++; /* Skip it, get next. */ + switch (state) { + case 0: /* Invalid = in first position */ + case 1: /* Invalid = in second position */ + return (-1); + + case 2: /* Valid, means one byte of info */ + /* Skip any number of spaces. */ + for (; ch != '\0'; ch = *src++) + if (!isspace(ch)) + break; + /* Make sure there is another trailing = sign. */ + if (ch != Pad64) + return (-1); + ch = *src++; /* Skip the = */ + /* Fall through to "single trailing =" case. */ + /* FALLTHROUGH */ + + case 3: /* Valid, means two bytes of info */ + /* + * We know this char is an =. Is there anything but + * whitespace after it? + */ + for (; ch != '\0'; ch = *src++) + if (!isspace(ch)) + return (-1); + + /* + * Now make sure for cases 2 and 3 that the "extra" + * bits that slopped past the last full byte were + * zeros. If we don't check them, they become a + * subliminal channel. + */ + if (target && target[tarindex] != 0) + return (-1); + } + } else { + /* + * We ended by seeing the end of the string. Make sure we + * have no partial bytes lying around. + */ + if (state != 0) + return (-1); + } + + return (tarindex); +} + +#endif /* !defined(HAVE_B64_PTON) && !defined(HAVE___B64_PTON) */ +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.h new file mode 100644 index 0000000..a9bf142 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/SocketRocket/fbase64.h @@ -0,0 +1,33 @@ +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FSocketRocket_base64_h +#define FSocketRocket_base64_h + +#include + +extern int +f_b64_ntop(u_char const *src, + size_t srclength, + char *target, + size_t targsize); + +extern int +f_b64_pton(char const *src, + u_char *target, + size_t targsize); + + +#endif diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.h b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.h new file mode 100644 index 0000000..c0baa22 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.h @@ -0,0 +1,105 @@ +// +// APLevelDB.h +// +// Created by Adam Preble on 1/23/12. +// Copyright (c) 2012 Adam Preble. 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 + +extern NSString * const APLevelDBErrorDomain; + +@class APLevelDBIterator; +@protocol APLevelDBWriteBatch; + +@interface APLevelDB : NSObject + +@property (nonatomic, readonly, strong) NSString *path; + ++ (APLevelDB *)levelDBWithPath:(NSString *)path error:(NSError *__autoreleasing*)errorOut; +- (void)close; + +- (BOOL)setData:(NSData *)data forKey:(NSString *)key; +- (BOOL)setString:(NSString *)str forKey:(NSString *)key; + +- (NSData *)dataForKey:(NSString *)key; +- (NSString *)stringForKey:(NSString *)key; + +- (BOOL)removeKey:(NSString *)key; + +- (NSArray *)allKeys; + +- (void)enumerateKeys:(void (^)(NSString *key, BOOL *stop))block; +- (void)enumerateKeysWithPrefix:(NSString *)prefix usingBlock:(void (^)(NSString *key, BOOL *stop))block; + +- (void)enumerateKeysAndValuesAsStrings:(void (^)(NSString *key, NSString *value, BOOL *stop))block; +- (void)enumerateKeysWithPrefix:(NSString *)prefix asStrings:(void (^)(NSString *key, NSString *value, BOOL *stop))block; + +- (void)enumerateKeysAndValuesAsData:(void (^)(NSString *key, NSData *value, BOOL *stop))block; +- (void)enumerateKeysWithPrefix:(NSString *)prefix asData:(void (^)(NSString *key, NSData *value, BOOL *stop))block; + +- (NSUInteger)approximateSizeFrom:(NSString *)from to:(NSString *)to; +- (NSUInteger)exactSizeFrom:(NSString *)from to:(NSString *)to; + +// Objective-C Subscripting Support: +// The database object supports subscripting for string-string and string-data key-value access and assignment. +// Examples: +// db[@"key"] = @"value"; +// db[@"key"] = [NSData data]; +// NSString *s = db[@"key"]; +// An NSInvalidArgumentException is raised if the key is not an NSString, or if the assigned object is not an +// instance of NSString or NSData. +- (id)objectForKeyedSubscript:(id)key; +- (void)setObject:(id)object forKeyedSubscript:(id)key; + +// Batch write/atomic update support: +- (id)beginWriteBatch; + +@end + + +@interface APLevelDBIterator : NSObject + ++ (id)iteratorWithLevelDB:(APLevelDB *)db; + +// Designated initializer: +- (id)initWithLevelDB:(APLevelDB *)db; + +- (BOOL)seekToKey:(NSString *)key; +- (NSString *)nextKey; +- (NSString *)key; +- (NSString *)valueAsString; +- (NSData *)valueAsData; + +@end + + +@protocol APLevelDBWriteBatch + +- (void)setData:(NSData *)data forKey:(NSString *)key; +- (void)setString:(NSString *)str forKey:(NSString *)key; + +- (void)removeKey:(NSString *)key; + +// Remove all of the buffered sets and removes: +- (void)clear; +- (BOOL)commit; + +@end diff --git a/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.mm b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.mm new file mode 100644 index 0000000..cdecce6 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/Firebase/Database/third_party/Wrap-leveldb/APLevelDB.mm @@ -0,0 +1,500 @@ +// +// APLevelDB.m +// +// Created by Adam Preble on 1/23/12. +// Copyright (c) 2012 Adam Preble. 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. + +// +// Portions of APLevelDB are based on LevelDB-ObjC: +// https://github.com/hoisie/LevelDB-ObjC +// Specifically the SliceFromString/StringFromSlice macros, and the structure of +// the enumeration methods. License for those potions follows: +// +// Copyright (c) 2011 Pave Labs +// +// 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 "APLevelDB.h" + +#import "leveldb/db.h" +#import "leveldb/options.h" +#import "leveldb/write_batch.h" + +NSString * const APLevelDBErrorDomain = @"APLevelDBErrorDomain"; + +#define SliceFromString(_string_) (leveldb::Slice((char *)[_string_ UTF8String], [_string_ lengthOfBytesUsingEncoding:NSUTF8StringEncoding])) +#define StringFromSlice(_slice_) ([[NSString alloc] initWithBytes:_slice_.data() length:_slice_.size() encoding:NSUTF8StringEncoding]) + + +@interface APLevelDBWriteBatch : NSObject { + @package + leveldb::WriteBatch _batch; +} + +@property (nonatomic, strong) APLevelDB *levelDB; + +- (id)initWithLevelDB:(APLevelDB *)levelDB; +@end + + +#pragma mark - APLevelDB + +@interface APLevelDB () { + leveldb::DB *_db; + leveldb::ReadOptions _readOptions; + leveldb::WriteOptions _writeOptions; +} +- (id)initWithPath:(NSString *)path error:(NSError **)errorOut; ++ (leveldb::Options)defaultCreateOptions; +@property (nonatomic, readonly) leveldb::DB *db; +@end + + +@implementation APLevelDB + +@synthesize path = _path; +@synthesize db = _db; + ++ (APLevelDB *)levelDBWithPath:(NSString *)path error:(NSError *__autoreleasing *)errorOut +{ + return [[APLevelDB alloc] initWithPath:path error:errorOut]; +} + +- (id)initWithPath:(NSString *)path error:(NSError *__autoreleasing *)errorOut +{ + if ((self = [super init])) + { + _path = path; + + leveldb::Options options = [[self class] defaultCreateOptions]; + + leveldb::Status status = leveldb::DB::Open(options, [_path UTF8String], &_db); + + if (!status.ok()) + { + if (errorOut) + { + NSString *statusString = [[NSString alloc] initWithCString:status.ToString().c_str() encoding:NSUTF8StringEncoding]; + *errorOut = [NSError errorWithDomain:APLevelDBErrorDomain + code:0 + userInfo:[NSDictionary dictionaryWithObjectsAndKeys:statusString, NSLocalizedDescriptionKey, nil]]; + } + return nil; + } + + _writeOptions.sync = false; + } + return self; +} + +- (void)close { + if (_db != NULL) { + delete _db; + _db = NULL; + } +} + +- (void)dealloc +{ + if (_db != NULL) { + delete _db; + _db = NULL; + } +} + ++ (leveldb::Options)defaultCreateOptions +{ + leveldb::Options options; + options.create_if_missing = true; + return options; +} + +- (BOOL)setData:(NSData *)data forKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + leveldb::Slice valueSlice = leveldb::Slice((const char *)[data bytes], (size_t)[data length]); + leveldb::Status status = _db->Put(_writeOptions, keySlice, valueSlice); + return (status.ok() == true); +} + +- (BOOL)setString:(NSString *)str forKey:(NSString *)key +{ + // This could have been based on + leveldb::Slice keySlice = SliceFromString(key); + leveldb::Slice valueSlice = SliceFromString(str); + leveldb::Status status = _db->Put(_writeOptions, keySlice, valueSlice); + return (status.ok() == true); +} + +- (NSData *)dataForKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + std::string valueCPPString; + leveldb::Status status = _db->Get(_readOptions, keySlice, &valueCPPString); + + if (!status.ok()) + return nil; + else + return [NSData dataWithBytes:valueCPPString.data() length:valueCPPString.size()]; +} + +- (NSString *)stringForKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + std::string valueCPPString; + leveldb::Status status = _db->Get(_readOptions, keySlice, &valueCPPString); + + // We assume (dangerously?) UTF-8 string encoding: + if (!status.ok()) + return nil; + else + return [[NSString alloc] initWithBytes:valueCPPString.data() length:valueCPPString.size() encoding:NSUTF8StringEncoding]; +} + +- (BOOL)removeKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + leveldb::Status status = _db->Delete(_writeOptions, keySlice); + return (status.ok() == true); +} + +- (NSArray *)allKeys +{ + NSMutableArray *keys = [NSMutableArray array]; + [self enumerateKeys:^(NSString *key, BOOL *stop) { + [keys addObject:key]; + }]; + return keys; +} + +- (void)enumerateKeysAndValuesAsStrings:(void (^)(NSString *key, NSString *value, BOOL *stop))block +{ + [self enumerateKeysWithPrefix:@"" asStrings:block]; +} + +- (void)enumerateKeysWithPrefix:(NSString *)prefixString asStrings:(void (^)(NSString *, NSString *, BOOL *))block +{ + @autoreleasepool { + BOOL stop = NO; + leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions()); + leveldb::Slice prefix = SliceFromString(prefixString); + for (iter->Seek(prefix); iter->Valid(); iter->Next()) { + leveldb::Slice key = iter->key(), value = iter->value(); + if (key.starts_with(prefix)) { + NSString *k = StringFromSlice(key); + NSString *v = [[NSString alloc] initWithBytes:value.data() length:value.size() encoding:NSUTF8StringEncoding]; + block(k, v, &stop); + if (stop) + break; + } else { + break; + } + } + + delete iter; + } +} + +- (void)enumerateKeys:(void (^)(NSString *key, BOOL *stop))block +{ + [self enumerateKeysWithPrefix:@"" usingBlock:block]; +} + +- (void)enumerateKeysWithPrefix:(NSString *)prefixString usingBlock:(void (^)(NSString *key, BOOL *stop))block; +{ + @autoreleasepool { + BOOL stop = NO; + leveldb::Slice prefix = SliceFromString(prefixString); + leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions()); + for (iter->Seek(prefix); iter->Valid(); iter->Next()) { + leveldb::Slice key = iter->key(); + if (key.starts_with(prefix)) { + NSString *k = StringFromSlice(key); + block(k, &stop); + if (stop) + break; + } else { + break; + } + } + + delete iter; + } +} + +- (void)enumerateKeysAndValuesAsData:(void (^)(NSString *key, NSData *data, BOOL *stop))block +{ + [self enumerateKeysWithPrefix:@"" asData:block]; +} + +- (void)enumerateKeysWithPrefix:(NSString *)prefixString asData:(void (^)(NSString *, NSData *, BOOL *))block +{ + @autoreleasepool { + BOOL stop = NO; + leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions()); + leveldb::Slice prefix = SliceFromString(prefixString); + for (iter->Seek(prefix); iter->Valid(); iter->Next()) { + leveldb::Slice key = iter->key(), value = iter->value(); + if (key.starts_with(prefix)) { + NSString *k = StringFromSlice(key); + NSData *data = [NSData dataWithBytes:value.data() length:value.size()]; + block(k, data, &stop); + if (stop) + break; + } else { + break; + } + } + + delete iter; + } +} + +- (NSUInteger)exactSizeFrom:(NSString *)from to:(NSString *)to { + NSUInteger size = 0; + leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions()); + leveldb::Slice fromSlice = SliceFromString(from); + leveldb::Slice toSlice = SliceFromString(to); + iter->Seek(fromSlice); + while (iter->Valid() && iter->key().compare(toSlice) <= 0) { + size += iter->value().size(); + iter->Next(); + } + delete iter; + return size; +} + + +- (NSUInteger)approximateSizeFrom:(NSString *)from to:(NSString *)to { + leveldb::Range ranges[1]; + leveldb::Slice fromSlice = SliceFromString(from); + leveldb::Slice toSlice = SliceFromString(to); + ranges[0] = leveldb::Range(fromSlice, toSlice); + uint64_t sizes[1]; + _db->GetApproximateSizes(ranges, 1, sizes); + return (NSUInteger)sizes[0]; +} + +#pragma mark - Subscripting Support + +- (id)objectForKeyedSubscript:(id)key +{ + if (![key respondsToSelector: @selector(componentsSeparatedByString:)]) + { + [NSException raise:NSInvalidArgumentException format:@"key must be an NSString"]; + } + return [self stringForKey:key]; +} +- (void)setObject:(id)thing forKeyedSubscript:(id)key +{ + id idKey = (id) key; + if (![idKey respondsToSelector: @selector(componentsSeparatedByString:)]) + { + [NSException raise:NSInvalidArgumentException format:@"key must be NSString or NSData"]; + } + + if ([thing respondsToSelector:@selector(componentsSeparatedByString:)]) + [self setString:thing forKey:(NSString *)key]; + else if ([thing respondsToSelector:@selector(subdataWithRange:)]) + [self setData:thing forKey:(NSString *)key]; + else + [NSException raise:NSInvalidArgumentException format:@"object must be NSString or NSData"]; +} + +#pragma mark - Atomic Updates + +- (id)beginWriteBatch +{ + APLevelDBWriteBatch *batch = [[APLevelDBWriteBatch alloc] initWithLevelDB:self]; + return batch; +} + +- (BOOL)commitWriteBatch:(id)theBatch +{ + if (!theBatch) + return NO; + + APLevelDBWriteBatch *batch = theBatch; + + leveldb::Status status; + status = _db->Write(_writeOptions, &batch->_batch); + return (status.ok() == true); +} + +@end + + +#pragma mark - APLevelDBIterator + +@interface APLevelDBIterator () { + leveldb::Iterator *_iter; +} + +@property (nonatomic, strong) APLevelDB *levelDB; +@end + + + +@implementation APLevelDBIterator + ++ (id)iteratorWithLevelDB:(APLevelDB *)db +{ + APLevelDBIterator *iter = [[[self class] alloc] initWithLevelDB:db]; + return iter; +} + +- (id)initWithLevelDB:(APLevelDB *)db +{ + if ((self = [super init])) + { + // Hold on to the database so it doesn't get deallocated before the iterator is deallocated + self->_levelDB = db; + _iter = db.db->NewIterator(leveldb::ReadOptions()); + _iter->SeekToFirst(); + if (!_iter->Valid()) + return nil; + } + return self; +} + +- (id)init +{ + [NSException raise:@"BadInitializer" format:@"Use the designated initializer, -initWithLevelDB:, instead."]; + return nil; +} + +- (void)dealloc +{ + self->_levelDB = nil; + delete _iter; + _iter = NULL; +} + +- (BOOL)seekToKey:(NSString *)key +{ + leveldb::Slice target = SliceFromString(key); + _iter->Seek(target); + return _iter->Valid() == true; +} + +- (void)seekToFirst +{ + _iter->SeekToFirst(); +} + +- (void)seekToLast +{ + _iter->SeekToLast(); +} + +- (NSString *)nextKey +{ + _iter->Next(); + return [self key]; +} + +- (NSString *)key +{ + if (_iter->Valid() == false) + return nil; + leveldb::Slice value = _iter->key(); + return StringFromSlice(value); +} + +- (NSString *)valueAsString +{ + if (_iter->Valid() == false) + return nil; + leveldb::Slice value = _iter->value(); + return StringFromSlice(value); +} + +- (NSData *)valueAsData +{ + if (_iter->Valid() == false) + return nil; + leveldb::Slice value = _iter->value(); + return [NSData dataWithBytes:value.data() length:value.size()]; +} + +@end + + + +#pragma mark - APLevelDBWriteBatch + +@implementation APLevelDBWriteBatch + +- (id)initWithLevelDB:(APLevelDB *)levelDB { + self = [super init]; + if (self != nil) { + self->_levelDB = levelDB; + } + return self; +} + +- (void)setData:(NSData *)data forKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + leveldb::Slice valueSlice = leveldb::Slice((const char *)[data bytes], (size_t)[data length]); + _batch.Put(keySlice, valueSlice); +} +- (void)setString:(NSString *)str forKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + leveldb::Slice valueSlice = SliceFromString(str); + _batch.Put(keySlice, valueSlice); +} + +- (void)removeKey:(NSString *)key +{ + leveldb::Slice keySlice = SliceFromString(key); + _batch.Delete(keySlice); +} + +- (void)clear +{ + _batch.Clear(); +} + +- (BOOL)commit { + return [self.levelDB commitWriteBatch:self]; +} + +@end + diff --git a/My Mind/Pods/FirebaseDatabase/LICENSE b/My Mind/Pods/FirebaseDatabase/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseDatabase/README.md b/My Mind/Pods/FirebaseDatabase/README.md new file mode 100644 index 0000000..d414a4c --- /dev/null +++ b/My Mind/Pods/FirebaseDatabase/README.md @@ -0,0 +1,193 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Code Formatting + +Travis will verify that any code changes are done in a style compliant way. Install +`clang-format` and `swiftformat`. +This command will get the right `clang-format` version: + +`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/0743d748ba8b41eec074a0a787dc80219142c525/Formula/clang-format.rb` + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseInstanceID/CHANGELOG.md b/My Mind/Pods/FirebaseInstanceID/CHANGELOG.md new file mode 100755 index 0000000..b81d158 --- /dev/null +++ b/My Mind/Pods/FirebaseInstanceID/CHANGELOG.md @@ -0,0 +1,132 @@ +# 2018-10-25 -- v3.3.0 +- Fixed a crash caused by keychain operation when accessing default access group. (#1399, #1393) +- Remove internal APIs that are no longer used. + +# 2018-09-25 -- v3.2.2 +- Fixed a crash caused by NSUserDefaults being called on background thread. + +# 2018-08-14 -- v3.2.1 +- Fixed an issue that checkin is not cached properly when app first started. (#1561) + +# 2018-07-31 -- v3.2.0 +- Added support for global Firebase data collection flag. (#1219) +- Improved message tracking sent by server API. +- Fixed an issue that InstanceID doesn't compile in app extensions, allowing its +dependents like remote config to be working inside the app extensions. + +# 2018-06-19 -- v3.1.1 +- Ensure the checkin and tokens are refreshed if firebase project changed. +- Fixed an issue that checkin should be turned off when FCM's autoInitEnabled flag is off. + +# 2018-06-12 -- v3.1.0 +- Added a new API to fetch InstanceID and Token with a completion handler. The completion handler returns a FIRInstanceIDResult with a instanceID and a token properties. +- Deprecated the token method. +- Added support to log a new customized label provided by developer. + +# 2018-05-08 -- v3.0.0 +- Removed deprecated method `setAPNSToken:type` defined in FIRInstanceID, please use `setAPNSToken:type` defined in FIRMessaging instead. +- Removed deprecated enum `FIRInstanceIDAPNSTokenType` defined in FIRInstanceID, please use `FIRMessagingAPNSTokenType` defined in FIRMessaging instead. +- Fixed an issue that FCM scheduled messages were not tracked successfully. + +# 2018-03-06 -- v2.0.10 +- Improved documentation on InstanceID usage for GDPR. +- Improved the keypair handling during GCM to FCM migration. If you are migrating from GCM to FCM, we encourage you to update to this version and above. + +# 2018-02-06 -- v2.0.9 +- Improved support for language targeting for FCM service. Server updates happen more efficiently when language changes. +- Improved support for FCM token auto generation enable/disable functions. + +# 2017-12-11 -- v2.0.8 +- Fixed a crash caused by a reflection call during logging. +- Updating server with the latest parameters and deprecating old ones. + +# 2017-11-27 -- v2.0.7 +- Improve identity reset process, ensuring all information is reset during Identity deletion. + +# 2017-11-06 -- v2.0.6 +- Make token refresh weekly. +- Fixed a crash when performing token operation. + +# 2017-10-11 -- v2.0.5 +- Improved support for working in shared Keychain environments. + +# 2017-09-26 -- v2.0.4 +- Fixed an issue where the FCM token was not associating correctly with an APNs + device token, depending on when the APNs device token was made available. +- Fixed an issue where FCM tokens for different Sender IDs were not associating + correctly with an APNs device token. +- Fixed an issue that was preventing the FCM direct channel from being + established on the first start after 24 hours of being opened. + +# 2017-09-13 -- v2.0.3 +- Fixed a race condition where a token was not being generated on first start, + if Firebase Messaging was included and the app did not register for remote + notifications. + +# 2017-08-25 -- v2.0.2 +- Fixed a startup performance regression, removing a call which was blocking the + main thread. + +# 2017-08-07 -- v2.0.1 +- Fixed issues with token and app identifier being inaccessible when the device + is locked. +- Fixed a crash if bundle identifier is nil, which is possible in some testing + environments. +- Fixed a small memory leak fetching a new token. +- Moved to a new and simplified token storage system. +- Moved to a new queuing system for token fetches and deletes. +- Simplified logic and code around configuration and logging. +- Added clarification about the 'apns_sandbox' parameter, in header comments. + +# 2017-05-08 -- v2.0.0 +- Introduced an improved interface for Swift 3 developers +- Deprecated some methods and properties after moving their logic to the + Firebase Cloud Messaging SDK +- Fixed an intermittent stability issue when a debug build of an app was + replaced with a release build of the same version +- Removed swizzling logic that was sometimes resulting in developers receiving + a validation notice about enabling push notification capabilities, even though + they weren't using push notifications +- Fixed a notification that would sometimes fire twice in quick succession + during the first run of an app + +# 2017-03-31 -- v1.0.10 + +- Improvements to token-fetching logic +- Fixed some warnings in Instance ID +- Improved error messages if Instance ID couldn't be initialized properly +- Improvements to console logging + +# 2017-01-31 -- v1.0.9 + +- Removed an error being mistakenly logged to the console. + +# 2016-07-06 -- v1.0.8 + +- Don't store InstanceID plists in Documents folder. + +# 2016-06-19 -- v1.0.7 + +- Fix remote-notifications warning on app submission. + +# 2016-05-16 -- v1.0.6 + +- Fix CocoaPod linter issues for InstanceID pod. + +# 2016-05-13 -- v1.0.5 + +- Fix Authorization errors for InstanceID tokens. + +# 2016-05-11 -- v1.0.4 + +- Reduce wait for InstanceID token during parallel requests. + +# 2016-04-18 -- v1.0.3 + +- Change flag to disable swizzling to *FirebaseAppDelegateProxyEnabled*. +- Fix incessant Keychain errors while accessing InstanceID. +- Fix max retries for fetching IID token. + +# 2016-04-18 -- v1.0.2 + +- Register for remote notifications on iOS8+ in the SDK itself. diff --git a/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID new file mode 100755 index 0000000..46aff49 Binary files /dev/null and b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/FirebaseInstanceID differ diff --git a/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h new file mode 100755 index 0000000..97777e1 --- /dev/null +++ b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h @@ -0,0 +1,304 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FIRInstanceIDResult; +/** + * @memberof FIRInstanceID + * + * The scope to be used when fetching/deleting a token for Firebase Messaging. + */ +FOUNDATION_EXPORT NSString *const kFIRInstanceIDScopeFirebaseMessaging + NS_SWIFT_NAME(InstanceIDScopeFirebaseMessaging); + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +/** + * Called when the system determines that tokens need to be refreshed. + * This method is also called if Instance ID has been reset in which + * case, tokens and FCM topic subscriptions also need to be refreshed. + * + * Instance ID service will throttle the refresh event across all devices + * to control the rate of token updates on application servers. + */ +FOUNDATION_EXPORT const NSNotificationName kFIRInstanceIDTokenRefreshNotification + NS_SWIFT_NAME(InstanceIDTokenRefresh); +#else +/** + * Called when the system determines that tokens need to be refreshed. + * This method is also called if Instance ID has been reset in which + * case, tokens and FCM topic subscriptions also need to be refreshed. + * + * Instance ID service will throttle the refresh event across all devices + * to control the rate of token updates on application servers. + */ +FOUNDATION_EXPORT NSString *const kFIRInstanceIDTokenRefreshNotification + NS_SWIFT_NAME(InstanceIDTokenRefreshNotification); +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the InstanceID token returns. If + * the call fails we return the appropriate `error code` as described below. + * + * @param token The valid token as returned by InstanceID backend. + * + * @param error The error describing why generating a new token + * failed. See the error codes below for a more detailed + * description. + */ +typedef void (^FIRInstanceIDTokenHandler)(NSString *__nullable token, NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDTokenHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the InstanceID `deleteToken` returns. If + * the call fails we return the appropriate `error code` as described below + * + * @param error The error describing why deleting the token failed. + * See the error codes below for a more detailed description. + */ +typedef void (^FIRInstanceIDDeleteTokenHandler)(NSError *error) + NS_SWIFT_NAME(InstanceIDDeleteTokenHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity is created. If the + * identity wasn't created for some reason we return the appropriate error code. + * + * @param identity A valid identity for the app instance, nil if there was an error + * while creating an identity. + * @param error The error if fetching the identity fails else nil. + */ +typedef void (^FIRInstanceIDHandler)(NSString *__nullable identity, NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity and all the tokens associated + * with it are deleted. Returns a valid error object in case of failure else nil. + * + * @param error The error if deleting the identity and all the tokens associated with + * it fails else nil. + */ +typedef void (^FIRInstanceIDDeleteHandler)(NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDDeleteHandler); + +/** + * @related FIRInstanceID + * + * The completion handler invoked when the app identity and token are fetched. If the + * identity wasn't created for some reason we return the appropriate error code. + * + * @param result The result containing an identity for the app instance and a valid token, + * nil if there was an error while creating the result. + * @param error The error if fetching the identity or token fails else nil. + */ +typedef void (^FIRInstanceIDResultHandler)(FIRInstanceIDResult *__nullable result, + NSError *__nullable error) + NS_SWIFT_NAME(InstanceIDResultHandler); + +/** + * Public errors produced by InstanceID. + */ +typedef NS_ENUM(NSUInteger, FIRInstanceIDError) { + // Http related errors. + + /// Unknown error. + FIRInstanceIDErrorUnknown = 0, + + /// Auth Error -- GCM couldn't validate request from this client. + FIRInstanceIDErrorAuthentication = 1, + + /// NoAccess -- InstanceID service cannot be accessed. + FIRInstanceIDErrorNoAccess = 2, + + /// Timeout -- Request to InstanceID backend timed out. + FIRInstanceIDErrorTimeout = 3, + + /// Network -- No network available to reach the servers. + FIRInstanceIDErrorNetwork = 4, + + /// OperationInProgress -- Another similar operation in progress, + /// bailing this one. + FIRInstanceIDErrorOperationInProgress = 5, + + /// InvalidRequest -- Some parameters of the request were invalid. + FIRInstanceIDErrorInvalidRequest = 7, +} NS_SWIFT_NAME(InstanceIDError); + +/** + * A class contains the results of InstanceID and token query. + */ +NS_SWIFT_NAME(InstanceIDResult) +@interface FIRInstanceIDResult : NSObject + +/** + * An instanceID uniquely identifies the app instance. + */ +@property(nonatomic, readonly, copy) NSString *instanceID; + +/* + * Returns a Firebase Messaging scoped token for the firebase app. + */ +@property(nonatomic, readonly, copy) NSString *token; + +@end + +/** + * Instance ID provides a unique identifier for each app instance and a mechanism + * to authenticate and authorize actions (for example, sending an FCM message). + * + * Once an InstanceID is generated, the library periodically sends information about the + * application and the device where it's running to the Firebase backend. To stop this. see + * `[FIRInstanceID deleteIDWithHandler:]`. + * + * Instance ID is long lived but, may be reset if the device is not used for + * a long time or the Instance ID service detects a problem. + * If Instance ID is reset, the app will be notified via + * `kFIRInstanceIDTokenRefreshNotification`. + * + * If the Instance ID has become invalid, the app can request a new one and + * send it to the app server. + * To prove ownership of Instance ID and to allow servers to access data or + * services associated with the app, call + * `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. + */ +NS_SWIFT_NAME(InstanceID) +@interface FIRInstanceID : NSObject + +/** + * FIRInstanceID. + * + * @return A shared instance of FIRInstanceID. + */ ++ (instancetype)instanceID NS_SWIFT_NAME(instanceID()); + +/** + * Unavailable. Use +instanceID instead. + */ +- (instancetype)init __attribute__((unavailable("Use +instanceID instead."))); + +#pragma mark - Tokens + +/** + * Returns a result of app instance identifier InstanceID and a Firebase Messaging scoped token. + * param handler The callback handler invoked when an app instanceID and a default token + * are generated and returned. If instanceID and token fetching fail for some + * reason the callback is invoked with nil `result` and the appropriate error. + */ +- (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler; + +/** + * Returns a Firebase Messaging scoped token for the firebase app. + * + * @return Returns the stored token if the device has registered with Firebase Messaging, otherwise + * returns nil. + */ +- (nullable NSString *)token __deprecated_msg("Use instanceIDWithHandler: instead."); + +/** + * Returns a token that authorizes an Entity (example: cloud service) to perform + * an action on behalf of the application identified by Instance ID. + * + * This is similar to an OAuth2 token except, it applies to the + * application instance instead of a user. + * + * This is an asynchronous call. If the token fetching fails for some reason + * we invoke the completion callback with nil `token` and the appropriate + * error. + * + * This generates an Instance ID if it does not exist yet, which starts periodically sending + * information to the Firebase backend (see `[FIRInstanceID getIDWithHandler:]`). + * + * Note, you can only have one `token` or `deleteToken` call for a given + * authorizedEntity and scope at any point of time. Making another such call with the + * same authorizedEntity and scope before the last one finishes will result in an + * error with code `OperationInProgress`. + * + * @see FIRInstanceID deleteTokenWithAuthorizedEntity:scope:handler: + * + * @param authorizedEntity Entity authorized by the token. + * @param scope Action authorized for authorizedEntity. + * @param options The extra options to be sent with your token request. The + * value for the `apns_token` should be the NSData object + * passed to the UIApplicationDelegate's + * `didRegisterForRemoteNotificationsWithDeviceToken` method. + * The value for `apns_sandbox` should be a boolean (or an + * NSNumber representing a BOOL in Objective C) set to true if + * your app is a debug build, which means that the APNs + * device token is for the sandbox environment. It should be + * set to false otherwise. If the `apns_sandbox` key is not + * provided, an automatically-detected value shall be used. + * @param handler The callback handler which is invoked when the token is + * successfully fetched. In case of success a valid `token` and + * `nil` error are returned. In case of any error the `token` + * is nil and a valid `error` is returned. The valid error + * codes have been documented above. + */ +- (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity + scope:(NSString *)scope + options:(nullable NSDictionary *)options + handler:(FIRInstanceIDTokenHandler)handler; + +/** + * Revokes access to a scope (action) for an entity previously + * authorized by `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. + * + * This is an asynchronous call. Call this on the main thread since InstanceID lib + * is not thread safe. In case token deletion fails for some reason we invoke the + * `handler` callback passed in with the appropriate error code. + * + * Note, you can only have one `token` or `deleteToken` call for a given + * authorizedEntity and scope at a point of time. Making another such call with the + * same authorizedEntity and scope before the last one finishes will result in an error + * with code `OperationInProgress`. + * + * @param authorizedEntity Entity that must no longer have access. + * @param scope Action that entity is no longer authorized to perform. + * @param handler The handler that is invoked once the unsubscribe call ends. + * In case of error an appropriate error object is returned + * else error is nil. + */ +- (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity + scope:(NSString *)scope + handler:(FIRInstanceIDDeleteTokenHandler)handler; + +#pragma mark - Identity + +/** + * Asynchronously fetch a stable identifier that uniquely identifies the app + * instance. If the identifier has been revoked or has expired, this method will + * return a new identifier. + * + * Once an InstanceID is generated, the library periodically sends information about the + * application and the device where it's running to the Firebase backend. To stop this. see + * `[FIRInstanceID deleteIDWithHandler:]`. + * + * @param handler The handler to invoke once the identifier has been fetched. + * In case of error an appropriate error object is returned else + * a valid identifier is returned and a valid identifier for the + * application instance. + */ +- (void)getIDWithHandler:(FIRInstanceIDHandler)handler NS_SWIFT_NAME(getID(handler:)); + +/** + * Resets Instance ID and revokes all tokens. + * + * This method also triggers a request to fetch a new Instance ID and Firebase Messaging scope + * token. Please listen to kFIRInstanceIDTokenRefreshNotification when the new ID and token are + * ready. + * + * This stops the periodic sending of data to the Firebase backend that began when the Instance ID + * was generated. No more data is sent until another library calls Instance ID internally again + * (like FCM, RemoteConfig or Analytics) or user explicitly calls Instance ID APIs to get an + * Instance ID and token again. + */ +- (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler NS_SWIFT_NAME(deleteID(handler:)); + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h new file mode 100755 index 0000000..053ec2b --- /dev/null +++ b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h @@ -0,0 +1 @@ +#import "FIRInstanceID.h" diff --git a/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap new file mode 100755 index 0000000..2058956 --- /dev/null +++ b/My Mind/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseInstanceID { + umbrella header "FirebaseInstanceID.h" + export * + module * { export *} + link framework "Security" + link framework "SystemConfiguration"} diff --git a/My Mind/Pods/FirebaseInstanceID/README.md b/My Mind/Pods/FirebaseInstanceID/README.md new file mode 100755 index 0000000..25fe219 --- /dev/null +++ b/My Mind/Pods/FirebaseInstanceID/README.md @@ -0,0 +1,10 @@ +# InstanceID SDK for iOS + +Instance ID provides a unique ID per instance of your apps and also provides a +mechanism to authenticate and authorize actions, like sending messages via +Firebase Cloud Messaging (FCM). + + +Please visit [our developer +site](https://developers.google.com/instance-id/) for integration instructions, +documentation, support information, and terms of service. diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMMessageCode.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMMessageCode.h new file mode 100644 index 0000000..4b16189 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMMessageCode.h @@ -0,0 +1,191 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +typedef NS_ENUM(NSInteger, FIRMessagingMessageCode) { + // FIRMessaging+FIRApp.m + kFIRMessagingMessageCodeFIRApp000 = 1000, // I-FCM001000 + kFIRMessagingMessageCodeFIRApp001 = 1001, // I-FCM001001 + // FIRMessaging.m + kFIRMessagingMessageCodeMessagingPrintLibraryVersion = 2000, // I-FCM002000 + kFIRMessagingMessageCodeMessaging001 = 2001, // I-FCM002001 + kFIRMessagingMessageCodeMessaging002 = 2002, // I-FCM002002 - no longer used + kFIRMessagingMessageCodeMessaging003 = 2003, // I-FCM002003 + kFIRMessagingMessageCodeMessaging004 = 2004, // I-FCM002004 + kFIRMessagingMessageCodeMessaging005 = 2005, // I-FCM002005 + kFIRMessagingMessageCodeMessaging006 = 2006, // I-FCM002006 - no longer used + kFIRMessagingMessageCodeMessaging007 = 2007, // I-FCM002007 - no longer used + kFIRMessagingMessageCodeMessaging008 = 2008, // I-FCM002008 - no longer used + kFIRMessagingMessageCodeMessaging009 = 2009, // I-FCM002009 + kFIRMessagingMessageCodeMessaging010 = 2010, // I-FCM002010 + kFIRMessagingMessageCodeMessaging011 = 2011, // I-FCM002011 + kFIRMessagingMessageCodeMessaging012 = 2012, // I-FCM002012 + kFIRMessagingMessageCodeMessaging013 = 2013, // I-FCM002013 + kFIRMessagingMessageCodeMessaging014 = 2014, // I-FCM002014 + kFIRMessagingMessageCodeMessaging015 = 2015, // I-FCM002015 + kFIRMessagingMessageCodeMessaging016 = 2016, // I-FCM002016 - no longer used + kFIRMessagingMessageCodeMessaging017 = 2017, // I-FCM002017 + kFIRMessagingMessageCodeMessaging018 = 2018, // I-FCM002018 + kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented = 2019, // I-FCM002019 + kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch = 2020, // I-FCM002020 + kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete = 2021, // I-FCM002021 + kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch = 2022, // I-FCM002022 + kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented = 2023, // I-FCM002023 + kFIRMessagingMessageCodeTopicFormatIsDeprecated = 2024, + // FIRMessagingClient.m + kFIRMessagingMessageCodeClient000 = 4000, // I-FCM004000 + kFIRMessagingMessageCodeClient001 = 4001, // I-FCM004001 + kFIRMessagingMessageCodeClient002 = 4002, // I-FCM004002 + kFIRMessagingMessageCodeClient003 = 4003, // I-FCM004003 + kFIRMessagingMessageCodeClient004 = 4004, // I-FCM004004 + kFIRMessagingMessageCodeClient005 = 4005, // I-FCM004005 + kFIRMessagingMessageCodeClient006 = 4006, // I-FCM004006 + kFIRMessagingMessageCodeClient007 = 4007, // I-FCM004007 + kFIRMessagingMessageCodeClient008 = 4008, // I-FCM004008 + kFIRMessagingMessageCodeClient009 = 4009, // I-FCM004009 + kFIRMessagingMessageCodeClient010 = 4010, // I-FCM004010 + kFIRMessagingMessageCodeClient011 = 4011, // I-FCM004011 + // FIRMessagingConnection.m + kFIRMessagingMessageCodeConnection000 = 5000, // I-FCM005000 + kFIRMessagingMessageCodeConnection001 = 5001, // I-FCM005001 + kFIRMessagingMessageCodeConnection002 = 5002, // I-FCM005002 + kFIRMessagingMessageCodeConnection003 = 5003, // I-FCM005003 + kFIRMessagingMessageCodeConnection004 = 5004, // I-FCM005004 + kFIRMessagingMessageCodeConnection005 = 5005, // I-FCM005005 + kFIRMessagingMessageCodeConnection006 = 5006, // I-FCM005006 + kFIRMessagingMessageCodeConnection007 = 5007, // I-FCM005007 + kFIRMessagingMessageCodeConnection008 = 5008, // I-FCM005008 + kFIRMessagingMessageCodeConnection009 = 5009, // I-FCM005009 + kFIRMessagingMessageCodeConnection010 = 5010, // I-FCM005010 + kFIRMessagingMessageCodeConnection011 = 5011, // I-FCM005011 + kFIRMessagingMessageCodeConnection012 = 5012, // I-FCM005012 + kFIRMessagingMessageCodeConnection013 = 5013, // I-FCM005013 + kFIRMessagingMessageCodeConnection014 = 5014, // I-FCM005014 + kFIRMessagingMessageCodeConnection015 = 5015, // I-FCM005015 + kFIRMessagingMessageCodeConnection016 = 5016, // I-FCM005016 + kFIRMessagingMessageCodeConnection017 = 5017, // I-FCM005017 + kFIRMessagingMessageCodeConnection018 = 5018, // I-FCM005018 + kFIRMessagingMessageCodeConnection019 = 5019, // I-FCM005019 + kFIRMessagingMessageCodeConnection020 = 5020, // I-FCM005020 + kFIRMessagingMessageCodeConnection021 = 5021, // I-FCM005021 + kFIRMessagingMessageCodeConnection022 = 5022, // I-FCM005022 + kFIRMessagingMessageCodeConnection023 = 5023, // I-FCM005023 + // FIRMessagingContextManagerService.m + kFIRMessagingMessageCodeContextManagerService000 = 6000, // I-FCM006000 + kFIRMessagingMessageCodeContextManagerService001 = 6001, // I-FCM006001 + kFIRMessagingMessageCodeContextManagerService002 = 6002, // I-FCM006002 + kFIRMessagingMessageCodeContextManagerService003 = 6003, // I-FCM006003 + kFIRMessagingMessageCodeContextManagerService004 = 6004, // I-FCM006004 + kFIRMessagingMessageCodeContextManagerService005 = 6005, // I-FCM006005 + // FIRMessagingDataMessageManager.m + kFIRMessagingMessageCodeDataMessageManager000 = 7000, // I-FCM007000 + kFIRMessagingMessageCodeDataMessageManager001 = 7001, // I-FCM007001 + kFIRMessagingMessageCodeDataMessageManager002 = 7002, // I-FCM007002 + kFIRMessagingMessageCodeDataMessageManager003 = 7003, // I-FCM007003 + kFIRMessagingMessageCodeDataMessageManager004 = 7004, // I-FCM007004 + kFIRMessagingMessageCodeDataMessageManager005 = 7005, // I-FCM007005 + kFIRMessagingMessageCodeDataMessageManager006 = 7006, // I-FCM007006 + kFIRMessagingMessageCodeDataMessageManager007 = 7007, // I-FCM007007 + kFIRMessagingMessageCodeDataMessageManager008 = 7008, // I-FCM007008 + kFIRMessagingMessageCodeDataMessageManager009 = 7009, // I-FCM007009 + kFIRMessagingMessageCodeDataMessageManager010 = 7010, // I-FCM007010 + kFIRMessagingMessageCodeDataMessageManager011 = 7011, // I-FCM007011 + kFIRMessagingMessageCodeDataMessageManager012 = 7012, // I-FCM007012 + // FIRMessagingPendingTopicsList.m + kFIRMessagingMessageCodePendingTopicsList000 = 8000, // I-FCM008000 + // FIRMessagingPubSub.m + kFIRMessagingMessageCodePubSub000 = 9000, // I-FCM009000 + kFIRMessagingMessageCodePubSub001 = 9001, // I-FCM009001 + kFIRMessagingMessageCodePubSub002 = 9002, // I-FCM009002 + kFIRMessagingMessageCodePubSub003 = 9003, // I-FCM009003 + // FIRMessagingReceiver.m + kFIRMessagingMessageCodeReceiver000 = 10000, // I-FCM010000 + kFIRMessagingMessageCodeReceiver001 = 10001, // I-FCM010001 + kFIRMessagingMessageCodeReceiver002 = 10002, // I-FCM010002 + kFIRMessagingMessageCodeReceiver003 = 10003, // I-FCM010003 + kFIRMessagingMessageCodeReceiver004 = 10004, // I-FCM010004 - no longer used + kFIRMessagingMessageCodeReceiver005 = 10005, // I-FCM010005 + // FIRMessagingRegistrar.m + kFIRMessagingMessageCodeRegistrar000 = 11000, // I-FCM011000 + // FIRMessagingRemoteNotificationsProxy.m + kFIRMessagingMessageCodeRemoteNotificationsProxy000 = 12000, // I-FCM012000 + kFIRMessagingMessageCodeRemoteNotificationsProxy001 = 12001, // I-FCM012001 + kFIRMessagingMessageCodeRemoteNotificationsProxyAPNSFailed = 12002, // I-FCM012002 + kFIRMessagingMessageCodeRemoteNotificationsProxyMethodNotAdded = 12003, // I-FCM012003 + // FIRMessagingRmq2PersistentStore.m + kFIRMessagingMessageCodeRmq2PersistentStore000 = 13000, // I-FCM013000 + kFIRMessagingMessageCodeRmq2PersistentStore001 = 13001, // I-FCM013001 + kFIRMessagingMessageCodeRmq2PersistentStore002 = 13002, // I-FCM013002 + kFIRMessagingMessageCodeRmq2PersistentStore003 = 13003, // I-FCM013003 + kFIRMessagingMessageCodeRmq2PersistentStore004 = 13004, // I-FCM013004 + kFIRMessagingMessageCodeRmq2PersistentStore005 = 13005, // I-FCM013005 + kFIRMessagingMessageCodeRmq2PersistentStore006 = 13006, // I-FCM013006 + kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingDatabase = 13007, // I-FCM013007 + kFIRMessagingMessageCodeRmq2PersistentStoreErrorOpeningDatabase = 13008, // I-FCM013008 + kFIRMessagingMessageCodeRmq2PersistentStoreInvalidRmqDirectory = 13009, // I-FCM013009 + kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingTable = 13010, // I-FCM013010 + // FIRMessagingRmqManager.m + kFIRMessagingMessageCodeRmqManager000 = 14000, // I-FCM014000 + // FIRMessagingSecureSocket.m + kFIRMessagingMessageCodeSecureSocket000 = 15000, // I-FCM015000 + kFIRMessagingMessageCodeSecureSocket001 = 15001, // I-FCM015001 + kFIRMessagingMessageCodeSecureSocket002 = 15002, // I-FCM015002 + kFIRMessagingMessageCodeSecureSocket003 = 15003, // I-FCM015003 + kFIRMessagingMessageCodeSecureSocket004 = 15004, // I-FCM015004 + kFIRMessagingMessageCodeSecureSocket005 = 15005, // I-FCM015005 + kFIRMessagingMessageCodeSecureSocket006 = 15006, // I-FCM015006 + kFIRMessagingMessageCodeSecureSocket007 = 15007, // I-FCM015007 + kFIRMessagingMessageCodeSecureSocket008 = 15008, // I-FCM015008 + kFIRMessagingMessageCodeSecureSocket009 = 15009, // I-FCM015009 + kFIRMessagingMessageCodeSecureSocket010 = 15010, // I-FCM015010 + kFIRMessagingMessageCodeSecureSocket011 = 15011, // I-FCM015011 + kFIRMessagingMessageCodeSecureSocket012 = 15012, // I-FCM015012 + kFIRMessagingMessageCodeSecureSocket013 = 15013, // I-FCM015013 + kFIRMessagingMessageCodeSecureSocket014 = 15014, // I-FCM015014 + kFIRMessagingMessageCodeSecureSocket015 = 15015, // I-FCM015015 + kFIRMessagingMessageCodeSecureSocket016 = 15016, // I-FCM015016 + // FIRMessagingSyncMessageManager.m + kFIRMessagingMessageCodeSyncMessageManager000 = 16000, // I-FCM016000 + kFIRMessagingMessageCodeSyncMessageManager001 = 16001, // I-FCM016001 + kFIRMessagingMessageCodeSyncMessageManager002 = 16002, // I-FCM016002 + kFIRMessagingMessageCodeSyncMessageManager003 = 16003, // I-FCM016003 + kFIRMessagingMessageCodeSyncMessageManager004 = 16004, // I-FCM016004 + kFIRMessagingMessageCodeSyncMessageManager005 = 16005, // I-FCM016005 + kFIRMessagingMessageCodeSyncMessageManager006 = 16006, // I-FCM016006 + kFIRMessagingMessageCodeSyncMessageManager007 = 16007, // I-FCM016007 + kFIRMessagingMessageCodeSyncMessageManager008 = 16008, // I-FCM016008 + // FIRMessagingTopicOperation.m + kFIRMessagingMessageCodeTopicOption000 = 17000, // I-FCM017000 + kFIRMessagingMessageCodeTopicOption001 = 17001, // I-FCM017001 + kFIRMessagingMessageCodeTopicOption002 = 17002, // I-FCM017002 + kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed = 17003, // I-FCM017003 + kFIRMessagingMessageCodeTopicOperationEmptyResponse = 17004, // I-FCM017004 + // FIRMessagingUtilities.m + kFIRMessagingMessageCodeUtilities000 = 18000, // I-FCM018000 + kFIRMessagingMessageCodeUtilities001 = 18001, // I-FCM018001 + kFIRMessagingMessageCodeUtilities002 = 18002, // I-FCM018002 + // FIRMessagingAnalytics.m + kFIRMessagingMessageCodeAnalytics000 = 19000, // I-FCM019000 + kFIRMessagingMessageCodeAnalytics001 = 19001, // I-FCM019001 + kFIRMessagingMessageCodeAnalytics002 = 19002, // I-FCM019002 + kFIRMessagingMessageCodeAnalytics003 = 19003, // I-FCM019003 + kFIRMessagingMessageCodeAnalytics004 = 19004, // I-FCM019004 + kFIRMessagingMessageCodeAnalytics005 = 19005, // I-FCM019005 + kFIRMessagingMessageCodeAnalyticsInvalidEvent = 19006, // I-FCM019006 + kFIRMessagingMessageCodeAnalytics007 = 19007, // I-FCM019007 + kFIRMessagingMessageCodeAnalyticsCouldNotInvokeAnalyticsLog = 19008, // I-FCM019008 +}; diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging.m new file mode 100644 index 0000000..eb6f71b --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging.m @@ -0,0 +1,1233 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !__has_feature(objc_arc) +#error FIRMessagingLib should be compiled with ARC. +#endif + +#import "FIRMessaging.h" +#import "FIRMessaging_Private.h" + +#import + +#import "FIRMessagingAnalytics.h" +#import "FIRMessagingClient.h" +#import "FIRMessagingConstants.h" +#import "FIRMessagingContextManagerService.h" +#import "FIRMessagingDataMessageManager.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPubSub.h" +#import "FIRMessagingReceiver.h" +#import "FIRMessagingRemoteNotificationsProxy.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessagingSyncMessageManager.h" +#import "FIRMessagingUtilities.h" +#import "FIRMessagingVersionUtilities.h" +#import "FIRMessaging_Private.h" + +#import +#import +#import +#import +#import +#import +#import +#import +#import + +#import "NSError+FIRMessaging.h" + +static NSString *const kFIRMessagingMessageViaAPNSRootKey = @"aps"; +static NSString *const kFIRMessagingReachabilityHostname = @"www.google.com"; +static NSString *const kFIRMessagingDefaultTokenScope = @"*"; +static NSString *const kFIRMessagingFCMTokenFetchAPNSOption = @"apns_token"; + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +const NSNotificationName FIRMessagingSendSuccessNotification = + @"com.firebase.messaging.notif.send-success"; +const NSNotificationName FIRMessagingSendErrorNotification = + @"com.firebase.messaging.notif.send-error"; +const NSNotificationName FIRMessagingMessagesDeletedNotification = + @"com.firebase.messaging.notif.messages-deleted"; +const NSNotificationName FIRMessagingConnectionStateChangedNotification = + @"com.firebase.messaging.notif.connection-state-changed"; +const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification = + @"com.firebase.messaging.notif.fcm-token-refreshed"; +#else +NSString *const FIRMessagingSendSuccessNotification = + @"com.firebase.messaging.notif.send-success"; +NSString *const FIRMessagingSendErrorNotification = + @"com.firebase.messaging.notif.send-error"; +NSString * const FIRMessagingMessagesDeletedNotification = + @"com.firebase.messaging.notif.messages-deleted"; +NSString * const FIRMessagingConnectionStateChangedNotification = + @"com.firebase.messaging.notif.connection-state-changed"; +NSString * const FIRMessagingRegistrationTokenRefreshedNotification = + @"com.firebase.messaging.notif.fcm-token-refreshed"; +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled = + @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults + +NSString *const kFIRMessagingAPNSTokenType = @"APNSTokenType"; // APNS Token type key stored in user info. + +NSString *const kFIRMessagingPlistAutoInitEnabled = + @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist + +@interface FIRMessagingMessageInfo () + +@property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status; + +@end + +@implementation FIRMessagingMessageInfo + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithStatus:(FIRMessagingMessageStatus)status { + self = [super init]; + if (self) { + _status = status; + } + return self; +} + +@end + +#pragma mark - for iOS 10 compatibility +@implementation FIRMessagingRemoteMessage + +- (instancetype)init { + self = [super init]; + if (self) { + _appData = [[NSMutableDictionary alloc] init]; + } + + return self; +} + +@end + +@interface FIRMessaging () + +// FIRApp properties +@property(nonatomic, readwrite, strong) NSData *apnsTokenData; +@property(nonatomic, readwrite, strong) NSString *defaultFcmToken; + +@property(nonatomic, readwrite, strong) FIRInstanceID *instanceID; + +@property(nonatomic, readwrite, assign) BOOL isClientSetup; + +@property(nonatomic, readwrite, strong) FIRMessagingClient *client; +@property(nonatomic, readwrite, strong) GULReachabilityChecker *reachability; +@property(nonatomic, readwrite, strong) FIRMessagingDataMessageManager *dataMessageManager; +@property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub; +@property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager; +@property(nonatomic, readwrite, strong) FIRMessagingReceiver *receiver; +@property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager; +@property(nonatomic, readwrite, strong) NSUserDefaults *messagingUserDefaults; + +/// Message ID's logged for analytics. This prevents us from logging the same message twice +/// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us +/// calling it implicitly during swizzling. +@property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs; +@property(nonatomic, readwrite, strong) id _Nullable analytics; + +@end + +// Messaging doesn't provide any functionality to other components, +// so it provides a private, empty protocol that it conforms to and use it for registration. + +@protocol FIRMessagingInstanceProvider +@end + +@interface FIRMessaging () +@end + +@implementation FIRMessaging + +// File static to support InstanceID tests that call [FIRMessaging messaging] after +// [FIRMessaging messagingForTests]. +static FIRMessaging *sMessaging; + ++ (FIRMessaging *)messaging { + if (sMessaging != nil) { + return sMessaging; + } + FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here. + id messaging = + FIR_COMPONENT(FIRMessagingInstanceProvider, defaultApp.container); + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + [(FIRMessaging *)messaging start]; + }); + sMessaging = (FIRMessaging *)messaging; + return sMessaging; +} + ++ (FIRMessaging *)messagingForTests { + sMessaging = [[FIRMessaging alloc] initWithAnalytics:nil + withInstanceID:[FIRInstanceID instanceID] + withUserDefaults:[NSUserDefaults standardUserDefaults]]; + [sMessaging start]; + return sMessaging; +} + +- (instancetype)initWithAnalytics:(nullable id)analytics + withInstanceID:(FIRInstanceID *)instanceID + withUserDefaults:(NSUserDefaults *)defaults { + self = [super init]; + if (self != nil) { + _loggedMessageIDs = [NSMutableSet set]; + _instanceID = instanceID; + _messagingUserDefaults = defaults; + _analytics = analytics; + } + return self; +} + +- (void)dealloc { + [self.reachability stop]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [self teardown]; +} + +#pragma mark - Config + ++ (void)load { + [FIRApp registerAsConfigurable:self]; + [FIRComponentContainer registerAsComponentRegistrant:self]; +} + ++ (nonnull NSArray *)componentsToRegister { + FIRDependency *analyticsDep = + [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop) isRequired:NO]; + FIRComponentCreationBlock creationBlock = + ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) { + // Ensure it's cached so it returns the same instance every time messaging is called. + *isCacheable = YES; + id analytics = FIR_COMPONENT(FIRAnalyticsInterop, container); + return [[FIRMessaging alloc] initWithAnalytics:analytics + withInstanceID:[FIRInstanceID instanceID] + withUserDefaults:[NSUserDefaults standardUserDefaults]]; + }; + FIRComponent *messagingProvider = + [FIRComponent componentWithProtocol:@protocol(FIRMessagingInstanceProvider) + instantiationTiming:FIRInstantiationTimingLazy + dependencies:@[ analyticsDep ] + creationBlock:creationBlock]; + + return @[ messagingProvider ]; +} + ++ (void)configureWithApp:(FIRApp *)app { + if (!app.isDefaultApp) { + // Only configure for the default FIRApp. + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeFIRApp001, + @"Firebase Messaging only works with the default app."); + return; + } + [[FIRMessaging messaging] configureMessaging:app]; +} + +- (void)configureMessaging:(FIRApp *)app { + // Swizzle remote-notification-related methods (app delegate and UNUserNotificationCenter) + if ([FIRMessagingRemoteNotificationsProxy canSwizzleMethods]) { + NSString *docsURLString = @"https://firebase.google.com/docs/cloud-messaging/ios/client" + @"#method_swizzling_in_firebase_messaging"; + FIRMessagingLoggerNotice(kFIRMessagingMessageCodeFIRApp000, + @"FIRMessaging Remote Notifications proxy enabled, will swizzle " + @"remote notification receiver handlers. If you'd prefer to manually " + @"integrate Firebase Messaging, add \"%@\" to your Info.plist, " + @"and set it to NO. Follow the instructions at:\n%@\nto ensure " + @"proper integration.", + kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey, + docsURLString); + [FIRMessagingRemoteNotificationsProxy swizzleMethods]; + } +} + +- (void)start { + // Print the library version for logging. + NSString *currentLibraryVersion = FIRMessagingCurrentLibraryVersion(); + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion, + @"FIRMessaging library version %@", + currentLibraryVersion); + + [self setupReceiver]; + + NSString *hostname = kFIRMessagingReachabilityHostname; + self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self + withHost:hostname]; + [self.reachability start]; + + [self setupApplicationSupportSubDirectory]; + // setup FIRMessaging objects + [self setupRmqManager]; + [self setupClient]; + [self setupSyncMessageManager]; + [self setupDataMessageManager]; + [self setupTopics]; + + self.isClientSetup = YES; + [self setupNotificationListeners]; +} + +- (void)setupApplicationSupportSubDirectory { + NSString *messagingSubDirectory = kFIRMessagingApplicationSupportSubDirectory; + if (![[self class] hasApplicationSupportSubDirectory:messagingSubDirectory]) { + [[self class] createApplicationSupportSubDirectory:messagingSubDirectory]; + } +} + +- (void)setupNotificationListeners { + // To prevent multiple notifications remove self as observer for all events. + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + [center removeObserver:self]; + + [center addObserver:self + selector:@selector(didReceiveDefaultInstanceIDToken:) + name:kFIRMessagingFCMTokenNotification + object:nil]; + [center addObserver:self + selector:@selector(defaultInstanceIDTokenWasRefreshed:) + name:kFIRMessagingRegistrationTokenRefreshNotification + object:nil]; + [center addObserver:self + selector:@selector(applicationStateChanged) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + [center addObserver:self + selector:@selector(applicationStateChanged) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +} + +- (void)setupReceiver { + self.receiver = [[FIRMessagingReceiver alloc] init]; + self.receiver.delegate = self; +} + +- (void)setupClient { + self.client = [[FIRMessagingClient alloc] initWithDelegate:self + reachability:self.reachability + rmq2Manager:self.rmq2Manager]; +} + +- (void)setupDataMessageManager { + self.dataMessageManager = + [[FIRMessagingDataMessageManager alloc] initWithDelegate:self.receiver + client:self.client + rmq2Manager:self.rmq2Manager + syncMessageManager:self.syncMessageManager]; + + [self.dataMessageManager refreshDelayedMessages]; + [self.client setDataMessageManager:self.dataMessageManager]; +} + +- (void)setupRmqManager { + self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"]; + [self.rmq2Manager loadRmqId]; +} + +- (void)setupTopics { + _FIRMessagingDevAssert(self.client, @"Invalid nil client before init pubsub."); + self.pubsub = [[FIRMessagingPubSub alloc] initWithClient:self.client]; +} + +- (void)setupSyncMessageManager { + self.syncMessageManager = + [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager]; + + // Delete the expired messages with a delay. We don't want to block startup with a somewhat + // expensive db call. + FIRMessaging_WEAKIFY(self); + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)); + dispatch_after(time, dispatch_get_main_queue(), ^{ + FIRMessaging_STRONGIFY(self); + [self.syncMessageManager removeExpiredSyncMessages]; + }); +} + +- (void)teardown { + _FIRMessagingDevAssert([NSThread isMainThread], + @"FIRMessaging should be called from main thread only."); + [self.client teardown]; + self.pubsub = nil; + self.syncMessageManager = nil; + self.rmq2Manager = nil; + self.dataMessageManager = nil; + self.client = nil; + self.isClientSetup = NO; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown"); +} + +#pragma mark - Messages + +- (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message { + if (!message.count) { + return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown]; + } + + // For downstream messages that go via MCS we should strip out this key before sending + // the message to the device. + BOOL isOldMessage = NO; + NSString *messageID = message[kFIRMessagingMessageIDKey]; + if ([messageID length]) { + [self.rmq2Manager saveS2dMessageWithRmqId:messageID]; + + BOOL isSyncMessage = [[self class] isAPNSSyncMessage:message]; + if (isSyncMessage) { + isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message]; + } + } + // Prevent duplicates by keeping a cache of all the logged messages during each session. + // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with + // us swizzling their implementation to call the same method implicitly. + if (!isOldMessage && messageID.length) { + isOldMessage = [self.loggedMessageIDs containsObject:messageID]; + if (!isOldMessage) { + [self.loggedMessageIDs addObject:messageID]; + } + } + + if (!isOldMessage) { + [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics]; + [self handleContextManagerMessage:message]; + [self handleIncomingLinkIfNeededFromMessage:message]; + } + return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew]; +} + +- (BOOL)handleContextManagerMessage:(NSDictionary *)message { + if ([FIRMessagingContextManagerService isContextManagerMessage:message]) { + return [FIRMessagingContextManagerService handleContextManagerMessage:message]; + } + return NO; +} + ++ (BOOL)isAPNSSyncMessage:(NSDictionary *)message { + if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) { + NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey]; + return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue]; + } + return NO; +} + +- (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message { + NSURL *url = [self linkURLFromMessage:message]; + if (url == nil) { + return; + } + if (![NSThread isMainThread]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self handleIncomingLinkIfNeededFromMessage:message]; + + }); + return; + } + UIApplication *application = FIRMessagingUIApplication(); + if (!application) { + return; + } + id appDelegate = application.delegate; + SEL continueUserActivitySelector = + @selector(application:continueUserActivity:restorationHandler:); + SEL openURLWithOptionsSelector = @selector(application:openURL:options:); + SEL openURLWithSourceApplicationSelector = + @selector(application:openURL:sourceApplication:annotation:); + SEL handleOpenURLSelector = @selector(application:handleOpenURL:); + // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or + // not the actual application has implemented + // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user + // if they haven't implemented it. + if ([NSUserActivity class] != nil && + [appDelegate respondsToSelector:continueUserActivitySelector]) { + NSUserActivity *userActivity = + [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb]; + userActivity.webpageURL = url; + [appDelegate application:application + continueUserActivity:userActivity + restorationHandler:^(NSArray * _Nullable restorableObjects) { + // Do nothing, as we don't support the app calling this block + }]; + + } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + [appDelegate application:application openURL:url options:@{}]; +#pragma clang diagnostic pop + + // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called, due + // to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics + } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [appDelegate application:application + openURL:url + sourceApplication:FIRMessagingAppIdentifier() + annotation:@{}]; + } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) { + [appDelegate application:application handleOpenURL:url]; +#pragma clang diagnostic pop + } +} + +- (NSURL *)linkURLFromMessage:(NSDictionary *)message { + NSString *urlString = message[kFIRMessagingMessageLinkKey]; + if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) { + return nil; + } + NSURL *url = [NSURL URLWithString:urlString]; + return url; +} + +#pragma mark - APNS + +- (NSData *)APNSToken { + return self.apnsTokenData; +} + +- (void)setAPNSToken:(NSData *)APNSToken { + [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown]; +} + +- (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type { + if ([apnsToken isEqual:self.apnsTokenData]) { + return; + } + self.apnsTokenData = apnsToken; + + // Notify InstanceID that APNS Token has been set. + NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)}; + NSNotification *notification = + [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification + object:[apnsToken copy] + userInfo:userInfo]; + [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP]; +} + +#pragma mark - FCM + +- (BOOL)isAutoInitEnabled { + // Check storage + id isAutoInitEnabledObject = + [_messagingUserDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled]; + if (isAutoInitEnabledObject) { + return [isAutoInitEnabledObject boolValue]; + } + + // Check Info.plist + isAutoInitEnabledObject = + [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled]; + if (isAutoInitEnabledObject) { + return [isAutoInitEnabledObject boolValue]; + } + + // If none of above exists, we default to the global switch that comes from FIRApp. + return [[FIRApp defaultApp] isDataCollectionDefaultEnabled]; +} + +- (void)setAutoInitEnabled:(BOOL)autoInitEnabled { + BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled]; + [_messagingUserDefaults setBool:autoInitEnabled + forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled]; + [_messagingUserDefaults synchronize]; + if (!isFCMAutoInitEnabled && autoInitEnabled) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + self.defaultFcmToken = self.instanceID.token; +#pragma clang diagnostic pop + } +} + +- (NSString *)FCMToken { + NSString *token = self.defaultFcmToken; + if (!token) { + // We may not have received it from Instance ID yet (via NSNotification), so extract it directly +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + token = self.instanceID.token; +#pragma clang diagnostic pop + } + return token; +} + +- (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID + completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion { + if (!senderID.length) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch, + @"Sender ID not supplied. It is required for a token fetch, " + @"to identify the sender."); + if (completion) { + NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid " + @"Sender ID is required to fetch an FCM token"; + NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest + userInfo:@{NSLocalizedDescriptionKey : description}]; + completion(nil, error); + } + return; + } + NSDictionary *options = nil; + if (self.APNSToken) { + options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken}; + } else { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch, + @"APNS device token not set before retrieving FCM Token for Sender ID " + @"'%@'. Notifications to this FCM Token will not be delivered over APNS." + @"Be sure to re-retrieve the FCM token once the APNS device token is " + @"set.", senderID); + } + [self.instanceID tokenWithAuthorizedEntity:senderID + scope:kFIRMessagingDefaultTokenScope + options:options + handler:completion]; +} + +- (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID + completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion { + if (!senderID.length) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete, + @"Sender ID not supplied. It is required to delete an FCM token."); + if (completion) { + NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A " + @"valid Sender ID is required to delete an FCM token"; + NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest + userInfo:@{NSLocalizedDescriptionKey : description}]; + completion(error); + } + return; + } + [self.instanceID deleteTokenWithAuthorizedEntity:senderID + scope:kFIRMessagingDefaultTokenScope + handler:completion]; +} + +#pragma mark - FIRMessagingDelegate helper methods +- (void)setDelegate:(id)delegate { + _delegate = delegate; + [self validateDelegateConformsToTokenAvailabilityMethods]; +} + +// Check if the delegate conforms to |didReceiveRegistrationToken:| +// and display a warning to the developer if not. +// NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this +// check can be removed. +- (void)validateDelegateConformsToTokenAvailabilityMethods { + if (self.delegate && + ![self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented, + @"The object %@ does not respond to " + @"-messaging:didReceiveRegistrationToken:. Please implement " + @"-messaging:didReceiveRegistrationToken: to be provided with an FCM " + @"token.", self.delegate.description); + } +} + +- (void)notifyDelegateOfFCMTokenAvailability { + __weak FIRMessaging *weakSelf = self; + if (![NSThread isMainThread]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [weakSelf notifyDelegateOfFCMTokenAvailability]; + }); + return; + } + if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) { + [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken]; + } +} + + +- (void)setUseMessagingDelegateForDirectChannel:(BOOL)useMessagingDelegateForDirectChannel { + self.receiver.useDirectChannel = useMessagingDelegateForDirectChannel; +} + +- (BOOL)useMessagingDelegateForDirectChannel { + return self.receiver.useDirectChannel; +} + +#pragma mark - Application State Changes + +- (void)applicationStateChanged { + if (self.shouldEstablishDirectChannel) { + [self updateAutomaticClientConnection]; + } +} + +#pragma mark - Direct Channel + +- (void)setShouldEstablishDirectChannel:(BOOL)shouldEstablishDirectChannel { + if (_shouldEstablishDirectChannel == shouldEstablishDirectChannel) { + return; + } + _shouldEstablishDirectChannel = shouldEstablishDirectChannel; + [self updateAutomaticClientConnection]; +} + +- (BOOL)isDirectChannelEstablished { + return self.client.isConnectionActive; +} + +- (BOOL)shouldBeConnectedAutomatically { + // We require a token from Instance ID + NSString *token = self.defaultFcmToken; + // Only on foreground connections + UIApplication *application = FIRMessagingUIApplication(); + if (!application) { + return NO; + } + UIApplicationState applicationState = application.applicationState; + BOOL shouldBeConnected = _shouldEstablishDirectChannel && + (token.length > 0) && + applicationState == UIApplicationStateActive; + return shouldBeConnected; +} + +- (void)updateAutomaticClientConnection { + if (![NSThread isMainThread]) { + // Call this method from the main thread + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateAutomaticClientConnection]; + }); + return; + } + BOOL shouldBeConnected = [self shouldBeConnectedAutomatically]; + if (shouldBeConnected && !self.client.isConnected) { + [self.client connectWithHandler:^(NSError *error) { + if (!error) { + // It means we connected. Fire connection change notification + [self notifyOfDirectChannelConnectionChange]; + } + }]; + } else if (!shouldBeConnected && self.client.isConnected) { + [self.client disconnect]; + [self notifyOfDirectChannelConnectionChange]; + } +} + +- (void)notifyOfDirectChannelConnectionChange { + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + [center postNotificationName:FIRMessagingConnectionStateChangedNotification object:self]; +} + +#pragma mark - Connect + +- (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler { + _FIRMessagingDevAssert([NSThread isMainThread], + @"FIRMessaging connect should be called from main thread only."); + _FIRMessagingDevAssert(self.isClientSetup, @"FIRMessaging client not setup."); + [self.client connectWithHandler:^(NSError *error) { + if (handler) { + handler(error); + } + if (!error) { + // It means we connected. Fire connection change notification + [self notifyOfDirectChannelConnectionChange]; + } + }]; + +} + +- (void)disconnect { + _FIRMessagingDevAssert([NSThread isMainThread], + @"FIRMessaging should be called from main thread only."); + if ([self.client isConnected]) { + [self.client disconnect]; + [self notifyOfDirectChannelConnectionChange]; + } +} + +#pragma mark - Topics + ++ (NSString *)normalizeTopic:(NSString *)topic { + if (!topic.length) { + return nil; + } + if (![FIRMessagingPubSub hasTopicsPrefix:topic]) { + topic = [FIRMessagingPubSub addPrefixToTopic:topic]; + } + if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) { + return [topic copy]; + } + return nil; +} + +- (void)subscribeToTopic:(NSString *)topic { + [self subscribeToTopic:topic completion:nil]; +} + +- (void)subscribeToTopic:(NSString *)topic + completion:(nullable FIRMessagingTopicOperationCompletion)completion { + if ([FIRMessagingPubSub hasTopicsPrefix:topic]) { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated, + @"Format '%@' is deprecated. Only '%@' should be used in " + @"subscribeToTopic.", + topic, [FIRMessagingPubSub removePrefixFromTopic:topic]); + } + if (!self.defaultFcmToken.length) { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeMessaging010, + @"The subscription operation is suspended because you don't have a " + @"token. The operation will resume once you get an FCM token."); + } + NSString *normalizeTopic = [[self class] normalizeTopic:topic]; + if (normalizeTopic.length) { + [self.pubsub subscribeToTopic:normalizeTopic handler:completion]; + return; + } + FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009, + @"Cannot parse topic name %@. Will not subscribe.", topic); + if (completion) { + completion([NSError fcm_errorWithCode:FIRMessagingErrorInvalidTopicName userInfo:nil]); + } +} + +- (void)unsubscribeFromTopic:(NSString *)topic { + [self unsubscribeFromTopic:topic completion:nil]; +} + +- (void)unsubscribeFromTopic:(NSString *)topic + completion:(nullable FIRMessagingTopicOperationCompletion)completion { + if ([FIRMessagingPubSub hasTopicsPrefix:topic]) { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated, + @"Format '%@' is deprecated. Only '%@' should be used in " + @"unsubscribeFromTopic.", + topic, [FIRMessagingPubSub removePrefixFromTopic:topic]); + } + if (!self.defaultFcmToken.length) { + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeMessaging012, + @"The unsubscription operation is suspended because you don't have a " + @"token. The operation will resume once you get an FCM token."); + } + NSString *normalizeTopic = [[self class] normalizeTopic:topic]; + if (normalizeTopic.length) { + [self.pubsub unsubscribeFromTopic:normalizeTopic handler:completion]; + return; + } + FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011, + @"Cannot parse topic name %@. Will not unsubscribe.", topic); + if (completion) { + completion([NSError fcm_errorWithCode:FIRMessagingErrorInvalidTopicName userInfo:nil]); + } +} + +#pragma mark - Send + +- (void)sendMessage:(NSDictionary *)message + to:(NSString *)to + withMessageID:(NSString *)messageID + timeToLive:(int64_t)ttl { + _FIRMessagingDevAssert([to length] != 0, @"Invalid receiver id for FIRMessaging-message"); + + NSMutableDictionary *fcmMessage = [[self class] createFIRMessagingMessageWithMessage:message + to:to + withID:messageID + timeToLive:ttl + delay:0]; + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessaging013, @"Sending message: %@ with id: %@", + message, messageID); + [self.dataMessageManager sendDataMessageStanza:fcmMessage]; +} + ++ (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message + to:(NSString *)to + withID:(NSString *)msgID + timeToLive:(int64_t)ttl + delay:(int)delay { + NSMutableDictionary *fcmMessage = [NSMutableDictionary dictionary]; + fcmMessage[kFIRMessagingSendTo] = [to copy]; + fcmMessage[kFIRMessagingSendMessageID] = msgID ? [msgID copy] : @""; + fcmMessage[kFIRMessagingSendTTL] = @(ttl); + fcmMessage[kFIRMessagingSendDelay] = @(delay); + fcmMessage[KFIRMessagingSendMessageAppData] = + [NSMutableDictionary dictionaryWithDictionary:message]; + return fcmMessage; +} + +#pragma mark - IID dependencies + ++ (NSString *)FIRMessagingSDKVersion { + return FIRMessagingCurrentLibraryVersion(); +} + ++ (NSString *)FIRMessagingSDKCurrentLocale { + return [self currentLocale]; +} + +#pragma mark - FIRMessagingReceiverDelegate + +- (void)receiver:(FIRMessagingReceiver *)receiver + receivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { + if ([self.delegate respondsToSelector:@selector(messaging:didReceiveMessage:)]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + [self.delegate messaging:self didReceiveMessage:remoteMessage]; +#pragma pop + } else { + // Delegate methods weren't implemented, so messages are being dropped, log a warning + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented, + @"FIRMessaging received data-message, but FIRMessagingDelegate's" + @"-messaging:didReceiveMessage: not implemented"); + } +} + +#pragma mark - GULReachabilityDelegate + +- (void)reachability:(GULReachabilityChecker *)reachability + statusChanged:(GULReachabilityStatus)status { + [self onNetworkStatusChanged]; +} + +#pragma mark - Network + +- (void)onNetworkStatusChanged { + if (![self.client isConnected] && [self isNetworkAvailable]) { + if (self.client.shouldStayConnected) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging014, + @"Attempting to establish direct channel."); + [self.client retryConnectionImmediately:YES]; + } + [self.pubsub scheduleSync:YES]; + } +} + +- (BOOL)isNetworkAvailable { + GULReachabilityStatus status = self.reachability.reachabilityStatus; + return (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi); +} + +- (FIRMessagingNetworkStatus)networkType { + GULReachabilityStatus status = self.reachability.reachabilityStatus; + if (![self isNetworkAvailable]) { + return kFIRMessagingReachabilityNotReachable; + } else if (status == kGULReachabilityViaCellular) { + return kFIRMessagingReachabilityReachableViaWWAN; + } else { + return kFIRMessagingReachabilityReachableViaWiFi; + } +} + +#pragma mark - Notifications + +- (void)didReceiveDefaultInstanceIDToken:(NSNotification *)notification { + if (notification.object && ![notification.object isKindOfClass:[NSString class]]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015, + @"Invalid default FCM token type %@", + NSStringFromClass([notification.object class])); + return; + } + NSString *oldToken = self.defaultFcmToken; + self.defaultFcmToken = [(NSString *)notification.object copy]; + if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) { + [self notifyDelegateOfFCMTokenAvailability]; + } + [self.pubsub scheduleSync:YES]; + if (self.shouldEstablishDirectChannel) { + [self updateAutomaticClientConnection]; + } +} + +- (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification { + // Retrieve the Instance ID default token, and if it is non-nil, post it +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + NSString *token = self.instanceID.token; +#pragma clang diagnostic pop + // Sometimes Instance ID doesn't yet have a token, so wait until the default + // token is fetched, and then notify. This ensures that this token should not + // be nil when the developer accesses it. + if (token != nil) { + NSString *oldToken = self.defaultFcmToken; + self.defaultFcmToken = [token copy]; + if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) { + [self notifyDelegateOfFCMTokenAvailability]; + } + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification object:nil]; + } +} + +#pragma mark - Application Support Directory + ++ (BOOL)hasApplicationSupportSubDirectory:(NSString *)subDirectoryName { + NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName]; + BOOL isDirectory; + if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath + isDirectory:&isDirectory]) { + return NO; + } else if (!isDirectory) { + return NO; + } + return YES; +} + ++ (NSString *)pathForApplicationSupportSubDirectory:(NSString *)subDirectoryName { + NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, + NSUserDomainMask, YES); + NSString *applicationSupportDirPath = directoryPaths.lastObject; + NSArray *components = @[applicationSupportDirPath, subDirectoryName]; + return [NSString pathWithComponents:components]; +} + ++ (BOOL)createApplicationSupportSubDirectory:(NSString *)subDirectoryName { + NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName]; + BOOL hasSubDirectory; + + if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath + isDirectory:&hasSubDirectory]) { + NSError *error; + [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath + withIntermediateDirectories:YES + attributes:nil + error:&error]; + if (error) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017, + @"Cannot create directory %@, error: %@", subDirectoryPath, error); + return NO; + } + } else { + if (!hasSubDirectory) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018, + @"Found file instead of directory at %@", subDirectoryPath); + return NO; + } + } + return YES; +} + +#pragma mark - Locales + ++ (NSString *)currentLocale { + NSArray *locales = [self firebaseLocales]; + NSArray *preferredLocalizations = + [NSBundle preferredLocalizationsFromArray:locales + forPreferences:[NSLocale preferredLanguages]]; + NSString *legalDocsLanguage = [preferredLocalizations firstObject]; + // Use en as the default language + return legalDocsLanguage ? legalDocsLanguage : @"en"; +} + ++ (NSArray *)firebaseLocales { + NSMutableArray *locales = [NSMutableArray array]; + NSDictionary *localesMap = [self firebaselocalesMap]; + for (NSString *key in localesMap) { + [locales addObjectsFromArray:localesMap[key]]; + } + return locales; +} + ++ (NSDictionary *)firebaselocalesMap { + return @{ + // Albanian + @"sq" : @[ @"sq_AL" ], + // Belarusian + @"be" : @[ @"be_BY" ], + // Bulgarian + @"bg" : @[ @"bg_BG" ], + // Catalan + @"ca" : @[ @"ca", @"ca_ES" ], + // Croatian + @"hr" : @[ @"hr", @"hr_HR" ], + // Czech + @"cs" : @[ @"cs", @"cs_CZ" ], + // Danish + @"da" : @[ @"da", @"da_DK" ], + // Estonian + @"et" : @[ @"et_EE" ], + // Finnish + @"fi" : @[ @"fi", @"fi_FI" ], + // Hebrew + @"he" : @[ @"he", @"iw_IL" ], + // Hindi + @"hi" : @[ @"hi_IN" ], + // Hungarian + @"hu" : @[ @"hu", @"hu_HU" ], + // Icelandic + @"is" : @[ @"is_IS" ], + // Indonesian + @"id" : @[ @"id", @"in_ID", @"id_ID" ], + // Irish + @"ga" : @[ @"ga_IE" ], + // Korean + @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ], + // Latvian + @"lv" : @[ @"lv_LV" ], + // Lithuanian + @"lt" : @[ @"lt_LT" ], + // Macedonian + @"mk" : @[ @"mk_MK" ], + // Malay + @"ms" : @[ @"ms_MY" ], + // Maltese + @"ms" : @[ @"mt_MT" ], + // Polish + @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ], + // Romanian + @"ro" : @[ @"ro", @"ro_RO" ], + // Russian + @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ], + // Slovak + @"sk" : @[ @"sk", @"sk_SK" ], + // Slovenian + @"sl" : @[ @"sl_SI" ], + // Swedish + @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ], + // Turkish + @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ], + // Ukrainian + @"uk" : @[ @"uk", @"uk_UA" ], + // Vietnamese + @"vi" : @[ @"vi", @"vi_VN" ], + // The following are groups of locales or locales that sub-divide a + // language). + // Arabic + @"ar" : @[ + @"ar", + @"ar_DZ", + @"ar_BH", + @"ar_EG", + @"ar_IQ", + @"ar_JO", + @"ar_KW", + @"ar_LB", + @"ar_LY", + @"ar_MA", + @"ar_OM", + @"ar_QA", + @"ar_SA", + @"ar_SD", + @"ar_SY", + @"ar_TN", + @"ar_AE", + @"ar_YE", + @"ar_GB", + @"ar-IQ", + @"ar_US" + ], + // Simplified Chinese + @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ], + // Traditional Chinese + @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ], + // Dutch + @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ], + // English + @"en" : @[ + @"en", + @"en_AU", + @"en_CA", + @"en_IN", + @"en_IE", + @"en_MT", + @"en_NZ", + @"en_PH", + @"en_SG", + @"en_ZA", + @"en_GB", + @"en_US", + @"en_AE", + @"en-AE", + @"en_AS", + @"en-AU", + @"en_BD", + @"en-CA", + @"en_EG", + @"en_ES", + @"en_GB", + @"en-GB", + @"en_HK", + @"en_ID", + @"en-IN", + @"en_NG", + @"en-PH", + @"en_PK", + @"en-SG", + @"en-US" + ], + // French + + @"fr" : @[ + @"fr", + @"fr_BE", + @"fr_CA", + @"fr_FR", + @"fr_LU", + @"fr_CH", + @"fr-CA", + @"fr-FR", + @"fr_MA" + ], + // German + @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ], + // Greek + @"el" : @[ @"el", @"el_CY", @"el_GR" ], + // Italian + @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ], + // Japanese + @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ], + // Norwegian + @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ], + // Brazilian Portuguese + @"pt_BR" : @[ @"pt_BR", @"pt-BR" ], + // European Portuguese + @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ], + // Serbian + @"sr" : @[ + @"sr_BA", + @"sr_ME", + @"sr_RS", + @"sr_Latn_BA", + @"sr_Latn_ME", + @"sr_Latn_RS" + ], + // European Spanish + @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ], + // Mexican Spanish + @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ], + // Latin American Spanish + @"es_419" : @[ + @"es_AR", + @"es_BO", + @"es_CL", + @"es_CO", + @"es_CR", + @"es_DO", + @"es_EC", + @"es_SV", + @"es_GT", + @"es_HN", + @"es_NI", + @"es_PA", + @"es_PY", + @"es_PE", + @"es_PR", + @"es_UY", + @"es_VE", + @"es-AR", + @"es-CL", + @"es-CO" + ], + // Thai + @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ], + }; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.h new file mode 100644 index 0000000..13bfab5 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.h @@ -0,0 +1,44 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Provides integration between FIRMessaging and Analytics. + * + * All Analytics dependencies should be kept in this class, and missing dependencies should be + * handled gracefully. + * + */ +@interface FIRMessagingAnalytics : NSObject + +/** + * Determine whether a notification has the properties to be loggable to Analytics. + * If so, send the notification. + * @param notification The notification payload from APNs + * @param analytics The class to be used as the receiver of the logging method + */ + ++ (void)logMessage:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.m new file mode 100644 index 0000000..42124be --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingAnalytics.m @@ -0,0 +1,225 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRMessagingAnalytics.h" +#import "FIRMessagingLogger.h" + +#import +#import +#import + +static NSString *const kLogTag = @"FIRMessagingAnalytics"; + +// aps Key +static NSString *const kApsKey = @"aps"; +static NSString *const kApsAlertKey = @"alert"; +static NSString *const kApsSoundKey = @"sound"; +static NSString *const kApsBadgeKey = @"badge"; +static NSString *const kApsContentAvailableKey = @"badge"; + +// Data Key +static NSString *const kDataKey = @"data"; + +// Messaging From Key +static NSString *const kFIRMessagingFromKey = @"from"; + +static NSString *const kFIRParameterLabel = @"label"; + +static NSString *const kReengagementSource = @"Firebase"; +static NSString *const kReengagementMedium = @"notification"; + +// Analytics +static NSString *const kAnalyticsEnabled = @"google.c.a." @"e"; +static NSString *const kAnalyticsComposerIdentifier = @"google.c.a." @"c_id"; +static NSString *const kAnalyticsComposerLabel = @"google.c.a." @"c_l"; +static NSString *const kAnalyticsMessageLabel = @"google.c.a." @"m_l"; +static NSString *const kAnalyticsMessageTimestamp = @"google.c.a." @"ts"; +static NSString *const kAnalyticsMessageUseDeviceTime = @"google.c.a." @"udt"; +static NSString *const kAnalyticsTrackConversions = @"google.c.a." @"tc"; + +@implementation FIRMessagingAnalytics + ++ (BOOL)canLogNotification:(NSDictionary *)notification { + if (!notification.count) { + // Payload is empty + return NO; + } + NSString *isAnalyticsLoggingEnabled = notification[kAnalyticsEnabled]; + if (![isAnalyticsLoggingEnabled isKindOfClass:[NSString class]] || + ![isAnalyticsLoggingEnabled isEqualToString:@"1"]) { + // Analytics logging is not enabled + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalytics001, + @"Analytics logging is disabled. Do not log event."); + return NO; + } + return YES; +} + ++ (void)logOpenNotification:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics { + [self logUserPropertyForConversionTracking:notification toAnalytics:analytics]; + [self logEvent:kFIRIEventNotificationOpen +withNotification:notification + toAnalytics:analytics]; +} + ++ (void)logForegroundNotification:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics { + [self logEvent:kFIRIEventNotificationForeground +withNotification:notification + toAnalytics:analytics]; +} + ++ (void)logEvent:(NSString *)event +withNotification:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics { + if (!event.length) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalyticsInvalidEvent, + @"Can't log analytics with empty event."); + return; + } + NSMutableDictionary *params = [self paramsForEvent:event withNotification:notification]; + + [analytics logEventWithOrigin:@"fcm" name:event parameters:params]; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalytics005, + @"%@: Sending event: %@ params: %@", kLogTag, event, params); +} + ++ (NSMutableDictionary *)paramsForEvent:(NSString *)event + withNotification:(NSDictionary *)notification { + NSDictionary *analyticsDataMap = notification; + if (!analyticsDataMap.count) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalytics000, + @"No data found in notification. Will not log any analytics events."); + return nil; + } + + if (![self canLogNotification:analyticsDataMap]) { + return nil; + } + + NSMutableDictionary *params = [NSMutableDictionary dictionary]; + NSString *composerIdentifier = analyticsDataMap[kAnalyticsComposerIdentifier]; + if ([composerIdentifier isKindOfClass:[NSString class]] && composerIdentifier.length) { + params[kFIRIParameterMessageIdentifier] = [composerIdentifier copy]; + } + + NSString *composerLabel = analyticsDataMap[kAnalyticsComposerLabel]; + if ([composerLabel isKindOfClass:[NSString class]] && composerLabel.length) { + params[kFIRIParameterMessageName] = [composerLabel copy]; + } + + NSString *messageLabel = analyticsDataMap[kAnalyticsMessageLabel]; + if ([messageLabel isKindOfClass:[NSString class]] && messageLabel.length) { + params[kFIRParameterLabel] = [messageLabel copy]; + } + + NSString *from = analyticsDataMap[kFIRMessagingFromKey]; + if ([from isKindOfClass:[NSString class]] && [from containsString:@"/topics/"]) { + params[kFIRIParameterTopic] = [from copy]; + } + + id timestamp = analyticsDataMap[kAnalyticsMessageTimestamp]; + if ([timestamp respondsToSelector:@selector(longLongValue)]) { + int64_t timestampValue = [timestamp longLongValue]; + if (timestampValue != 0) { + params[kFIRIParameterMessageTime] = @(timestampValue); + } + } + + if (analyticsDataMap[kAnalyticsMessageUseDeviceTime]) { + params[kFIRIParameterMessageDeviceTime] = analyticsDataMap[kAnalyticsMessageUseDeviceTime]; + } + + return params; +} + ++ (void)logUserPropertyForConversionTracking:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics { + NSInteger shouldTrackConversions = [notification[kAnalyticsTrackConversions] integerValue]; + if (shouldTrackConversions != 1) { + return; + } + + NSString *composerIdentifier = notification[kAnalyticsComposerIdentifier]; + if ([composerIdentifier isKindOfClass:[NSString class]] && composerIdentifier.length) { + // Set user property for event. + [analytics setUserPropertyWithOrigin:@"fcm" + name:kFIRIUserPropertyLastNotification + value:composerIdentifier]; + + // Set the re-engagement attribution properties. + NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3]; + params[kFIRIParameterSource] = kReengagementSource; + params[kFIRIParameterMedium] = kReengagementMedium; + params[kFIRIParameterCampaign] = composerIdentifier; + [analytics logEventWithOrigin:@"fcm" name:kFIRIEventFirebaseCampaign parameters:params]; + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalytics003, + @"%@: Sending event: %@ params: %@", kLogTag, + kFIRIEventFirebaseCampaign, params); + + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeAnalytics004, + @"%@: Failed to set user property: %@ value: %@", kLogTag, + kFIRIUserPropertyLastNotification, composerIdentifier); + } +} + ++ (void)logMessage:(NSDictionary *)notification + toAnalytics:(id _Nullable)analytics { + if (![self canLogNotification:notification]) { + return; + } + + UIApplication *application = [self currentUIApplication]; + if (!application) { + return; + } + UIApplicationState applicationState = application.applicationState; + switch (applicationState) { + case UIApplicationStateInactive: + // App was either in background(suspended) or inactive and user tapped on a display + // notification. + [self logOpenNotification:notification toAnalytics:analytics]; + break; + + case UIApplicationStateActive: + // App was in foreground when it received the notification. + [self logForegroundNotification:notification toAnalytics:analytics]; + break; + + default: + // Only a silent notification (i.e. 'content-available' is true) can be received while the app + // is in the background. These messages aren't loggable anyway. + break; + } +} + ++ (UIApplication *)currentUIApplication { + Class applicationClass = nil; + if (![GULAppEnvironmentUtil isAppExtension]) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + return [applicationClass sharedApplication]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.h new file mode 100644 index 0000000..155143a --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + * Register the device with Checkin Service and get back the `authID`, `secret token` etc. for the + * client. Checkin results are cached in the `FIRMessagingDefaultsManager` and periodically refreshed to + * prevent them from being stale. Each client needs to register with checkin before registering + * with FIRMessaging. + */ +@interface FIRMessagingCheckinService : NSObject + +@property(nonatomic, readonly, strong) NSString *deviceAuthID; +@property(nonatomic, readonly, strong) NSString *secretToken; +@property(nonatomic, readonly, strong) NSString *versionInfo; +@property(nonatomic, readonly, assign) BOOL hasValidCheckinInfo; + +/** + * Verify if valid checkin preferences have been loaded in memory. + * + * @return YES if valid checkin preferences exist in memory else NO. + */ +- (BOOL)hasValidCheckinInfo; + +/** + * Try to load prefetched checkin preferences from the cache. This supports the use case where + * InstanceID library has already obtained a valid checkin and we should be using that. + * + * This should be used as a last gasp effort to retreive any cached checkin preferences before + * hitting the FIRMessaging backend to retrieve new preferences. + * + * Note this is only required because InstanceID and FIRMessaging both require checkin preferences which + * need to be synced with each other. + * + * @return YES if successfully loaded cached checkin preferences into memory else NO. + */ +- (BOOL)tryToLoadPrefetchedCheckinPreferences; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.m new file mode 100644 index 0000000..9dad847 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCheckinService.m @@ -0,0 +1,132 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingCheckinService.h" + +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" + +@interface FIRMessagingCheckinService () + +// This property is of type FIRInstanceIDCheckinPreferences, if InstanceID was directly linkable +@property(nonatomic, readwrite, strong) id checkinPreferences; + +@end + +@implementation FIRMessagingCheckinService; + +#pragma mark - Reflection-Based Getter Functions + +// Encapsulates the -hasValidCheckinInfo method of FIRInstanceIDCheckinPreferences +BOOL FIRMessagingCheckinService_hasValidCheckinInfo(id checkinPreferences) { + SEL hasValidCheckinInfoSelector = NSSelectorFromString(@"hasValidCheckinInfo"); + if (![checkinPreferences respondsToSelector:hasValidCheckinInfoSelector]) { + // Can't check hasValidCheckinInfo + return NO; + } + + // Since hasValidCheckinInfo returns a BOOL, use NSInvocation + NSMethodSignature *methodSignature = + [[checkinPreferences class] instanceMethodSignatureForSelector:hasValidCheckinInfoSelector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; + invocation.selector = hasValidCheckinInfoSelector; + invocation.target = checkinPreferences; + [invocation invoke]; + BOOL returnValue; + [invocation getReturnValue:&returnValue]; + return returnValue; +} + +// Returns a non-scalar (id) object based on the property name +id FIRMessagingCheckinService_propertyNamed(id checkinPreferences, NSString *propertyName) { + SEL propertyGetterSelector = NSSelectorFromString(propertyName); + if ([checkinPreferences respondsToSelector:propertyGetterSelector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + return [checkinPreferences performSelector:propertyGetterSelector]; +#pragma clang diagnostic pop + } + return nil; +} + +#pragma mark - Methods + +- (BOOL)tryToLoadPrefetchedCheckinPreferences { + Class instanceIDClass = NSClassFromString(@"FIRInstanceID"); + if (!instanceIDClass) { + // InstanceID is not linked + return NO; + } + + // [FIRInstanceID instanceID] + SEL instanceIDSelector = NSSelectorFromString(@"instanceID"); + if (![instanceIDClass respondsToSelector:instanceIDSelector]) { + return NO; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id instanceID = [instanceIDClass performSelector:instanceIDSelector]; +#pragma clang diagnostic pop + if (!instanceID) { + // Instance ID singleton not available + return NO; + } + + // [[FIRInstanceID instanceID] cachedCheckinPreferences] + SEL cachedCheckinPrefsSelector = NSSelectorFromString(@"cachedCheckinPreferences"); + if (![instanceID respondsToSelector:cachedCheckinPrefsSelector]) { + // cachedCheckinPreferences is not accessible + return NO; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id checkinPreferences = [instanceID performSelector:cachedCheckinPrefsSelector]; +#pragma clang diagnostic pop + if (!checkinPreferences) { + // No cached checkin prefs + return NO; + } + + BOOL hasValidInfo = FIRMessagingCheckinService_hasValidCheckinInfo(checkinPreferences); + if (hasValidInfo) { + self.checkinPreferences = checkinPreferences; + } + return hasValidInfo; +} + +#pragma mark - API + +- (NSString *)deviceAuthID { + return FIRMessagingCheckinService_propertyNamed(self.checkinPreferences, @"deviceID"); +} + +- (NSString *)secretToken { + return FIRMessagingCheckinService_propertyNamed(self.checkinPreferences, @"secretToken"); +} + +- (NSString *)versionInfo { + return FIRMessagingCheckinService_propertyNamed(self.checkinPreferences, @"versionInfo"); +} + +- (NSString *)digest { + return FIRMessagingCheckinService_propertyNamed(self.checkinPreferences, @"digest"); +} + +- (BOOL)hasValidCheckinInfo { + return FIRMessagingCheckinService_hasValidCheckinInfo(self.checkinPreferences); +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.h new file mode 100644 index 0000000..98337a3 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.h @@ -0,0 +1,156 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" + +@class GULReachabilityChecker; +@class GPBMessage; + +@class FIRMessagingConnection; +@class FIRMessagingDataMessageManager; +@class FIRMessagingRmqManager; + +/** + * Callback to handle MCS connection requests. + * + * @param error The error object if any while trying to connect with MCS else nil. + */ +typedef void(^FIRMessagingConnectCompletionHandler)(NSError *error); + +@protocol FIRMessagingClientDelegate + +@end + +/** + * The client handles the subscribe/unsubscribe for an unregistered senderID + * and device. It also manages the FIRMessaging data connection, the exponential backoff + * algorithm in case of registration failures, sign in failures and unregister + * failures. It also handles the reconnect logic if the FIRMessaging connection is + * broken off by some error during an active session. + */ +@interface FIRMessagingClient : NSObject + +@property(nonatomic, readonly, strong) FIRMessagingConnection *connection; +@property(nonatomic, readwrite, weak) FIRMessagingDataMessageManager *dataMessageManager; + +// Designated initializer +- (instancetype)initWithDelegate:(id)delegate + reachability:(GULReachabilityChecker *)reachability + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager; + +- (void)teardown; + +- (void)cancelAllRequests; + +#pragma mark - FIRMessaging subscribe + +/** + * Update the subscription associated with the given token and topic. + * + * For a to-be-created subscription we check if the client is already + * subscribed to the topic or not. If subscribed we should have the + * subscriptionID in the cache and we return from there itself, else we call + * the FIRMessaging backend to create a new subscription for the topic for this client. + * + * For delete subscription requests we delete the stored subscription in the + * client and then invoke the FIRMessaging backend to delete the existing subscription + * completely. + * + * @param token The token associated with the device. + * @param topic The topic for which the subscription should be updated. + * @param options The options to be passed in to the subscription request. + * @param shouldDelete If YES this would delete the subscription from the cache + * and also let the FIRMessaging backend know that we need to delete + * the subscriptionID associated with this topic. + * If NO we try to create a new subscription for the given + * token and topic. + * @param handler The handler to invoke once the subscription request + * finishes. + */ +- (void)updateSubscriptionWithToken:(NSString *)token + topic:(NSString *)topic + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler; + +#pragma mark - MCS Connection + +/** + * Create a MCS connection. + * + * @param handler The handler to be invokend once the connection is setup. If + * setting up the connection fails we invoke the handler with + * an appropriate error object. + */ +- (void)connectWithHandler:(FIRMessagingConnectCompletionHandler)handler; + +/** + * Disconnect the current MCS connection. If there is no valid connection this + * should be a NO-OP. + */ +- (void)disconnect; + +#pragma mark - MCS Connection State + +/** + * If we are connected to MCS or not. This doesn't take into account the fact if + * the client has been signed in(verified) by MCS. + * + * @return YES if we are signed in or connecting and trying to sign-in else NO. + */ +@property(nonatomic, readonly) BOOL isConnected; + +/** + * If we have an active MCS connection + * + * @return YES if we have an active MCS connection else NO. + */ +@property(nonatomic, readonly) BOOL isConnectionActive; + +/** + * If we should be connected to MCS + * + * @return YES if we have attempted a connection and not requested to disconect. + */ +@property(nonatomic, readonly) BOOL shouldStayConnected; + +/** + * Schedule a retry to connect to MCS. If `immediately` is `YES` try to + * schedule a retry now else retry with some delay. + * + * @param immediately Should retry right now. + */ +- (void)retryConnectionImmediately:(BOOL)immediately; + +#pragma mark - Messages + +/** + * Send a message over the MCS connection. + * + * @param message Message to be sent. + */ +- (void)sendMessage:(GPBMessage *)message; + +/** + * Send message if we have an active MCS connection. If not cache the message + * for this session and in case we are able to re-establish the connection try + * again else drop it. This should only be used for TTL=0 messages for now. + * + * @param message Message to be sent. + */ +- (void)sendOnConnectOrDrop:(GPBMessage *)message; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.m new file mode 100644 index 0000000..9d8c558 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingClient.m @@ -0,0 +1,506 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingClient.h" + +#import + +#import "FIRMessaging.h" +#import "FIRMessagingConnection.h" +#import "FIRMessagingConstants.h" +#import "FIRMessagingDataMessageManager.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingRegistrar.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessagingTopicsCommon.h" +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" + +static const NSTimeInterval kConnectTimeoutInterval = 40.0; +static const NSTimeInterval kReconnectDelayInSeconds = 2 * 60; // 2 minutes + +static const NSUInteger kMaxRetryExponent = 10; // 2^10 = 1024 seconds ~= 17 minutes + +static NSString *const kFIRMessagingMCSServerHost = @"mtalk.google.com"; +static NSUInteger const kFIRMessagingMCSServerPort = 5228; + +// register device with checkin +typedef void(^FIRMessagingRegisterDeviceHandler)(NSError *error); + +static NSString *FIRMessagingServerHost() { + static NSString *serverHost = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSDictionary *environment = [[NSProcessInfo processInfo] environment]; + NSString *customServerHostAndPort = environment[@"FCM_MCS_HOST"]; + NSString *host = [customServerHostAndPort componentsSeparatedByString:@":"].firstObject; + if (host) { + serverHost = host; + } else { + serverHost = kFIRMessagingMCSServerHost; + } + }); + return serverHost; +} + +static NSUInteger FIRMessagingServerPort() { + static NSUInteger serverPort = kFIRMessagingMCSServerPort; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSDictionary *environment = [[NSProcessInfo processInfo] environment]; + NSString *customServerHostAndPort = environment[@"FCM_MCS_HOST"]; + NSArray *components = [customServerHostAndPort componentsSeparatedByString:@":"]; + NSUInteger port = (NSUInteger)[components.lastObject integerValue]; + if (port != 0) { + serverPort = port; + } + }); + return serverPort; +} + +@interface FIRMessagingClient () + +@property(nonatomic, readwrite, weak) id clientDelegate; +@property(nonatomic, readwrite, strong) FIRMessagingConnection *connection; +@property(nonatomic, readwrite, strong) FIRMessagingRegistrar *registrar; + +@property(nonatomic, readwrite, strong) NSString *senderId; + +// FIRMessagingService owns these instances +@property(nonatomic, readwrite, weak) FIRMessagingRmqManager *rmq2Manager; +@property(nonatomic, readwrite, weak) GULReachabilityChecker *reachability; + +@property(nonatomic, readwrite, assign) int64_t lastConnectedTimestamp; +@property(nonatomic, readwrite, assign) int64_t lastDisconnectedTimestamp; +@property(nonatomic, readwrite, assign) NSUInteger connectRetryCount; + +// Should we stay connected to MCS or not. Should be YES throughout the lifetime +// of a MCS connection. If set to NO it signifies that an existing MCS connection +// should be disconnected. +@property(nonatomic, readwrite, assign) BOOL stayConnected; +@property(nonatomic, readwrite, assign) NSTimeInterval connectionTimeoutInterval; + +// Used if the MCS connection suddenly breaksdown in the middle and we want to reconnect +// with some permissible delay we schedule a reconnect and set it to YES and when it's +// scheduled this will be set back to NO. +@property(nonatomic, readwrite, assign) BOOL didScheduleReconnect; + +// handlers +@property(nonatomic, readwrite, copy) FIRMessagingConnectCompletionHandler connectHandler; + +@end + +@implementation FIRMessagingClient + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithDelegate:(id)delegate + reachability:(GULReachabilityChecker *)reachability + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager { + self = [super init]; + if (self) { + _reachability = reachability; + _clientDelegate = delegate; + _rmq2Manager = rmq2Manager; + _registrar = [[FIRMessagingRegistrar alloc] init]; + _connectionTimeoutInterval = kConnectTimeoutInterval; + // Listen for checkin fetch notifications, as connecting to MCS may have failed due to + // missing checkin info (while it was being fetched). + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(checkinFetched:) + name:kFIRMessagingCheckinFetchedNotification + object:nil]; + } + return self; +} + +- (void)teardown { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient000, @""); + self.stayConnected = NO; + + // Clear all the handlers + self.connectHandler = nil; + + [self.connection teardown]; + + // Stop all subscription requests + [self.registrar cancelAllRequests]; + + _FIRMessagingDevAssert(self.connection.state == kFIRMessagingConnectionNotConnected, @"Did not disconnect"); + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)cancelAllRequests { + // Stop any checkin requests or any subscription requests + [self.registrar cancelAllRequests]; + + // Stop any future connection requests to MCS + if (self.stayConnected && self.isConnected && !self.isConnectionActive) { + self.stayConnected = NO; + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + } +} + +#pragma mark - FIRMessaging subscribe + +- (void)updateSubscriptionWithToken:(NSString *)token + topic:(NSString *)topic + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler { + + _FIRMessagingDevAssert(handler != nil, @"Invalid handler to FIRMessaging subscribe"); + + FIRMessagingTopicOperationCompletion completion = ^void(NSError *error) { + if (error) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeClient001, @"Failed to subscribe to topic %@", + error); + } else { + if (shouldDelete) { + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeClient002, + @"Successfully unsubscribed from topic %@", topic); + } else { + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeClient003, + @"Successfully subscribed to topic %@", topic); + } + } + handler(error); + }; + + [self.registrar updateSubscriptionToTopic:topic + withToken:token + options:options + shouldDelete:shouldDelete + handler:completion]; +} + +#pragma mark - MCS Connection + +- (BOOL)isConnected { + return self.stayConnected && self.connection.state != kFIRMessagingConnectionNotConnected; +} + +- (BOOL)isConnectionActive { + return self.stayConnected && self.connection.state == kFIRMessagingConnectionSignedIn; +} + +- (BOOL)shouldStayConnected { + return self.stayConnected; +} + +- (void)retryConnectionImmediately:(BOOL)immediately { + // Do not connect to an invalid host or an invalid port + if (!self.stayConnected || !self.connection.host || self.connection.port == 0) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient004, + @"FIRMessaging connection will not reconnect to MCS. " + @"Stay connected: %d", + self.stayConnected); + return; + } + if (self.isConnectionActive) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient005, + @"FIRMessaging Connection skip retry, active"); + // already connected and logged in. + // Heartbeat alarm is set and will force close the connection + return; + } + if (self.isConnected) { + // already connected and logged in. + // Heartbeat alarm is set and will force close the connection + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient006, + @"FIRMessaging Connection skip retry, connected"); + return; + } + + if (immediately) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient007, + @"Try to connect to MCS immediately"); + [self tryToConnect]; + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient008, @"Try to connect to MCS lazily"); + // Avoid all the other logic that we have in other clients, since this would always happen + // when the app is in the foreground and since the FIRMessaging connection isn't shared with any other + // app we can be more aggressive in reconnections + if (!self.didScheduleReconnect) { + FIRMessaging_WEAKIFY(self); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, + (int64_t)(kReconnectDelayInSeconds * NSEC_PER_SEC)), + dispatch_get_main_queue(), ^{ + FIRMessaging_STRONGIFY(self); + self.didScheduleReconnect = NO; + [self tryToConnect]; + }); + + self.didScheduleReconnect = YES; + } + } +} + +- (void)connectWithHandler:(FIRMessagingConnectCompletionHandler)handler { + if (self.isConnected) { + NSError *error = [NSError fcm_errorWithCode:kFIRMessagingErrorCodeAlreadyConnected + userInfo:@{ + NSLocalizedFailureReasonErrorKey: @"FIRMessaging is already connected", + }]; + handler(error); + return; + } + self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds(); + self.connectHandler = handler; + [self connect]; +} + +- (void)connect { + // reset retry counts + self.connectRetryCount = 0; + + if (self.isConnected) { + return; + } + + self.stayConnected = YES; + if (![self.registrar tryToLoadValidCheckinInfo]) { + // Checkin info is not available. This may be due to the checkin still being fetched. + if (self.connectHandler) { + NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeMissingDeviceID]; + self.connectHandler(error); + } + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient009, + @"Failed to connect to MCS. No deviceID and secret found."); + // Return for now. If checkin is, in fact, retrieved, the + // |kFIRMessagingCheckinFetchedNotification| will be fired. + return; + } + [self setupConnectionAndConnect]; +} + +- (void)disconnect { + // user called disconnect + // We don't want to connect later even if no network is available. + [self disconnectWithTryToConnectLater:NO]; +} + +/** + * Disconnect the current client connection. Also explicitly stop and connction retries. + * + * @param tryToConnectLater If YES will try to connect later when sending upstream messages + * else if NO do not connect again until user explicitly calls + * connect. + */ +- (void)disconnectWithTryToConnectLater:(BOOL)tryToConnectLater { + + self.stayConnected = tryToConnectLater; + [self.connection signOut]; + _FIRMessagingDevAssert(self.connection.state == kFIRMessagingConnectionNotConnected, + @"FIRMessaging connection did not disconnect"); + + // since we can disconnect while still trying to establish the connection it's required to + // cancel all performSelectors else the object might be retained + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(tryToConnect) + object:nil]; + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(didConnectTimeout) + object:nil]; + self.connectHandler = nil; +} + +#pragma mark - Checkin Notification +- (void)checkinFetched:(NSNotification *)notification { + // A failed checkin may have been the reason for the connection failure. Attempt a connection + // if the checkin fetched notification is fired. + if (self.stayConnected && !self.isConnected) { + [self connect]; + } +} + +#pragma mark - Messages + +- (void)sendMessage:(GPBMessage *)message { + [self.connection sendProto:message]; +} + +- (void)sendOnConnectOrDrop:(GPBMessage *)message { + [self.connection sendOnConnectOrDrop:message]; +} + +#pragma mark - FIRMessagingConnectionDelegate + +- (void)connection:(FIRMessagingConnection *)fcmConnection + didCloseForReason:(FIRMessagingConnectionCloseReason)reason { + + self.lastDisconnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds(); + + if (reason == kFIRMessagingConnectionCloseReasonSocketDisconnected) { + // Cancel the not-yet-triggered timeout task before rescheduling, in case the previous sign in + // failed, due to a connection error caused by bad network. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(didConnectTimeout) + object:nil]; + } + if (self.stayConnected) { + [self scheduleConnectRetry]; + } +} + +- (void)didLoginWithConnection:(FIRMessagingConnection *)fcmConnection { + // Cancel the not-yet-triggered timeout task. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(didConnectTimeout) + object:nil]; + self.connectRetryCount = 0; + self.lastConnectedTimestamp = FIRMessagingCurrentTimestampInMilliseconds(); + + + [self.dataMessageManager setDeviceAuthID:self.registrar.deviceAuthID + secretToken:self.registrar.secretToken]; + if (self.connectHandler) { + self.connectHandler(nil); + // notified the third party app with the registrationId. + // we don't want them to know about the connection status and how it changes + // so remove this handler + self.connectHandler = nil; + } +} + +- (void)connectionDidRecieveMessage:(GtalkDataMessageStanza *)message { + NSDictionary *parsedMessage = [self.dataMessageManager processPacket:message]; + if ([parsedMessage count]) { + [self.dataMessageManager didReceiveParsedMessage:parsedMessage]; + } +} + +- (int)connectionDidReceiveAckForRmqIds:(NSArray *)rmqIds { + NSSet *rmqIDSet = [NSSet setWithArray:rmqIds]; + NSMutableArray *messagesSent = [NSMutableArray arrayWithCapacity:rmqIds.count]; + [self.rmq2Manager scanWithRmqMessageHandler:nil + dataMessageHandler:^(int64_t rmqId, GtalkDataMessageStanza *stanza) { + NSString *rmqIdString = [NSString stringWithFormat:@"%lld", rmqId]; + if ([rmqIDSet containsObject:rmqIdString]) { + [messagesSent addObject:stanza]; + } + }]; + for (GtalkDataMessageStanza *message in messagesSent) { + [self.dataMessageManager didSendDataMessageStanza:message]; + } + return [self.rmq2Manager removeRmqMessagesWithRmqIds:rmqIds]; +} + +#pragma mark - Private + +- (void)setupConnectionAndConnect { + [self setupConnection]; + [self tryToConnect]; +} + +- (void)setupConnection { + NSString *host = FIRMessagingServerHost(); + NSUInteger port = FIRMessagingServerPort(); + _FIRMessagingDevAssert([host length] > 0 && port != 0, @"Invalid port or host"); + + if (self.connection != nil) { + // if there is an old connection, explicitly sign it off. + [self.connection signOut]; + self.connection.delegate = nil; + } + self.connection = [[FIRMessagingConnection alloc] initWithAuthID:self.registrar.deviceAuthID + token:self.registrar.secretToken + host:host + port:port + runLoop:[NSRunLoop mainRunLoop] + rmq2Manager:self.rmq2Manager + fcmManager:self.dataMessageManager]; + self.connection.delegate = self; +} + +- (void)tryToConnect { + if (!self.stayConnected) { + return; + } + + // Cancel any other pending signin requests. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(tryToConnect) + object:nil]; + + // Do not re-sign in if there is already a connection in progress. + if (self.connection.state != kFIRMessagingConnectionNotConnected) { + return; + } + + _FIRMessagingDevAssert(self.registrar.deviceAuthID.length > 0 && + self.registrar.secretToken.length > 0 && + self.connection != nil, + @"Invalid state cannot connect"); + + self.connectRetryCount = MIN(kMaxRetryExponent, self.connectRetryCount + 1); + [self performSelector:@selector(didConnectTimeout) + withObject:nil + afterDelay:self.connectionTimeoutInterval]; + [self.connection signIn]; +} + +- (void)didConnectTimeout { + _FIRMessagingDevAssert(self.connection.state != kFIRMessagingConnectionSignedIn, + @"Invalid state for MCS connection"); + + if (self.stayConnected) { + [self.connection signOut]; + [self scheduleConnectRetry]; + } +} + +#pragma mark - Schedulers + +- (void)scheduleConnectRetry { + GULReachabilityStatus status = self.reachability.reachabilityStatus; + BOOL isReachable = (status == kGULReachabilityViaWifi || status == kGULReachabilityViaCellular); + if (!isReachable) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient010, + @"Internet not reachable when signing into MCS during a retry"); + + FIRMessagingConnectCompletionHandler handler = [self.connectHandler copy]; + // disconnect before issuing a callback + [self disconnectWithTryToConnectLater:YES]; + NSError *error = + [NSError errorWithDomain:@"No internet available, cannot connect to FIRMessaging" + code:kFIRMessagingErrorCodeNetwork + userInfo:nil]; + if (handler) { + handler(error); + self.connectHandler = nil; + } + return; + } + + NSUInteger retryInterval = [self nextRetryInterval]; + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeClient011, + @"Failed to sign in to MCS, retry in %lu seconds", + _FIRMessaging_UL(retryInterval)); + [self performSelector:@selector(tryToConnect) withObject:nil afterDelay:retryInterval]; +} + +- (NSUInteger)nextRetryInterval { + return 1u << self.connectRetryCount; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.h new file mode 100644 index 0000000..8f22290 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FIRMessagingCodedInputStream : NSObject + +@property(nonatomic, readonly, assign) size_t offset; + +- (instancetype)initWithData:(NSData *)data; +- (BOOL)readTag:(int8_t *)tag; +- (BOOL)readLength:(int32_t *)length; +- (NSData *)readDataWithLength:(uint32_t)length; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.m new file mode 100644 index 0000000..82c0677 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingCodedInputStream.m @@ -0,0 +1,142 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingCodedInputStream.h" +#import "FIRMessagingDefines.h" + +typedef struct { + const void *bytes; + size_t bufferSize; + size_t bufferPos; +} BufferState; + +static BOOL CheckSize(BufferState *state, size_t size) { + size_t newSize = state->bufferPos + size; + if (newSize > state->bufferSize) { + return NO; + } + return YES; +} + +static BOOL ReadRawByte(BufferState *state, int8_t *output) { + _FIRMessagingDevAssert(output != NULL && state != NULL, @"Invalid parameters"); + + if (CheckSize(state, sizeof(int8_t))) { + *output = ((int8_t *)state->bytes)[state->bufferPos++]; + return YES; + } + return NO; +} + +static BOOL ReadRawVarInt32(BufferState *state, int32_t *output) { + _FIRMessagingDevAssert(output != NULL && state != NULL, @"Invalid parameters"); + + int8_t tmp = 0; + if (!ReadRawByte(state, &tmp)) { + return NO; + } + if (tmp >= 0) { + *output = tmp; + return YES; + } + int32_t result = tmp & 0x7f; + if (!ReadRawByte(state, &tmp)) { + return NO; + } + if (tmp >= 0) { + result |= tmp << 7; + } else { + result |= (tmp & 0x7f) << 7; + if (!ReadRawByte(state, &tmp)) { + return NO; + } + if (tmp >= 0) { + result |= tmp << 14; + } else { + result |= (tmp & 0x7f) << 14; + if (!ReadRawByte(state, &tmp)) { + return NO; + } + if (tmp >= 0) { + result |= tmp << 21; + } else { + result |= (tmp & 0x7f) << 21; + if (!ReadRawByte(state, &tmp)) { + return NO; + } + result |= tmp << 28; + if (tmp < 0) { + // Discard upper 32 bits. + for (int i = 0; i < 5; ++i) { + if (!ReadRawByte(state, &tmp)) { + return NO; + } + if (tmp >= 0) { + *output = result; + return YES; + } + } + return NO; + } + } + } + } + *output = result; + return YES; +} + +@interface FIRMessagingCodedInputStream() + +@property(nonatomic, readwrite, strong) NSData *buffer; +@property(nonatomic, readwrite, assign) BufferState state; + +@end + +@implementation FIRMessagingCodedInputStream; + +- (instancetype)initWithData:(NSData *)data { + self = [super init]; + if (self) { + _buffer = data; + _state.bytes = _buffer.bytes; + _state.bufferSize = _buffer.length; + } + return self; +} + +- (size_t)offset { + return _state.bufferPos; +} + +- (BOOL)readTag:(int8_t *)tag { + return ReadRawByte(&_state, tag); +} + +- (BOOL)readLength:(int32_t *)length { + return ReadRawVarInt32(&_state, length); +} + +- (NSData *)readDataWithLength:(uint32_t)length { + if (!CheckSize(&_state, length)) { + return nil; + } + const void *bytesToRead = _state.bytes + _state.bufferPos; + NSData *result = [NSData dataWithBytes:bytesToRead length:length]; + _state.bufferPos += length; + return result; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.h new file mode 100644 index 0000000..25a018c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.h @@ -0,0 +1,106 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRMessagingConnection; +@class FIRMessagingDataMessageManager; +@class FIRMessagingRmqManager; + +@class GtalkDataMessageStanza; +@class GPBMessage; + +typedef void (^FIRMessagingMessageHandler)(NSDictionary *); + +typedef NS_ENUM(NSUInteger, FIRMessagingConnectionState) { + kFIRMessagingConnectionNotConnected = 0, + kFIRMessagingConnectionConnecting, + kFIRMessagingConnectionConnected, + kFIRMessagingConnectionSignedIn, +}; + +typedef NS_ENUM(NSUInteger, FIRMessagingConnectionCloseReason) { + kFIRMessagingConnectionCloseReasonSocketDisconnected = 0, + kFIRMessagingConnectionCloseReasonTimeout, + kFIRMessagingConnectionCloseReasonUserDisconnect, +}; + +@protocol FIRMessagingConnectionDelegate + +- (void)connection:(FIRMessagingConnection *)fcmConnection + didCloseForReason:(FIRMessagingConnectionCloseReason)reason; +- (void)didLoginWithConnection:(FIRMessagingConnection *)fcmConnection; +- (void)connectionDidRecieveMessage:(GtalkDataMessageStanza *)message; +/** + * Called when a stream ACK or a selective ACK are received - this indicates the + * message has been received by MCS. + * @return The count of rmqIds deleted from the client RMQ store. + */ +- (int)connectionDidReceiveAckForRmqIds:(NSArray *)rmqIds; + +@end + + +/** + * This class maintains the actual FIRMessaging connection that we use to receive and send messages + * while the app is in foreground. Once we have a registrationID from the FIRMessaging backend we + * are able to set up this connection which is used for any further communication with FIRMessaging + * backend. In case the connection breaks off while the app is still being used we try to rebuild + * the connection with an exponential backoff. + * + * This class also notifies the delegate about the main events happening in the lifcycle of the + * FIRMessaging connection (read FIRMessagingConnectionDelegate). All of the `on-the-wire` + * interactions with FIRMessaging are channelled through here. + */ +@interface FIRMessagingConnection : NSObject + +@property(nonatomic, readonly, assign) FIRMessagingConnectionState state; +@property(nonatomic, readonly, copy) NSString *host; +@property(nonatomic, readonly, assign) NSUInteger port; +@property(nonatomic, readwrite, weak) id delegate; + +- (instancetype)initWithAuthID:(NSString *)authId + token:(NSString *)token + host:(NSString *)host + port:(NSUInteger)port + runLoop:(NSRunLoop *)runLoop + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager + fcmManager:(FIRMessagingDataMessageManager *)dataMessageManager; + +- (void)signIn; // connect +- (void)signOut; // disconnect + +/** + * Teardown the FIRMessaging connection and deallocate the resources being held up by the + * connection. + */ +- (void)teardown; + +/** + * Send proto to the wire. The message will be cached before we try to send so that in case of + * failure we can send it again later on when we have connection. + */ +- (void)sendProto:(GPBMessage *)proto; + +/** + * Send a message after the currently in progress connection succeeds, otherwise drop it. + * + * This should be used for TTL=0 messages that force a reconnect. They shouldn't be persisted + * in the RMQ, but they should be sent if the reconnect is successful. + */ +- (void)sendOnConnectOrDrop:(GPBMessage *)message; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.m new file mode 100644 index 0000000..8694326 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConnection.m @@ -0,0 +1,708 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingConnection.h" + +#import "Protos/GtalkCore.pbobjc.h" +#import "Protos/GtalkExtensions.pbobjc.h" + +#import "FIRMessaging.h" +#import "FIRMessagingDataMessageManager.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessagingSecureSocket.h" +#import "FIRMessagingUtilities.h" +#import "FIRMessagingVersionUtilities.h" +#import "FIRMessaging_Private.h" + +static NSInteger const kIqSelectiveAck = 12; +static NSInteger const kIqStreamAck = 13; +static int const kInvalidStreamId = -1; +// Threshold for number of messages removed that we will ack, for short lived connections +static int const kMessageRemoveAckThresholdCount = 5; + +static NSTimeInterval const kHeartbeatInterval = 30.0; +static NSTimeInterval const kConnectionTimeout = 20.0; +static int32_t const kAckingInterval = 10; + +static NSString *const kUnackedS2dIdKey = @"FIRMessagingUnackedS2dIdKey"; +static NSString *const kAckedS2dIdMapKey = @"FIRMessagingAckedS2dIdMapKey"; + +static NSString *const kRemoteFromAddress = @"from"; + +@interface FIRMessagingD2SInfo : NSObject + +@property(nonatomic, readwrite, assign) int streamId; +@property(nonatomic, readwrite, strong) NSString *d2sID; +- (instancetype)initWithStreamId:(int)streamId d2sId:(NSString *)d2sID; + +@end + +@implementation FIRMessagingD2SInfo + +- (instancetype)initWithStreamId:(int)streamId d2sId:(NSString *)d2sID { + self = [super init]; + if (self) { + _streamId = streamId; + _d2sID = [d2sID copy]; + } + return self; +} + +- (BOOL)isEqual:(id)object { + if ([object isKindOfClass:[self class]]) { + FIRMessagingD2SInfo *other = (FIRMessagingD2SInfo *)object; + return self.streamId == other.streamId && [self.d2sID isEqualToString:other.d2sID]; + } + return NO; +} + +- (NSUInteger)hash { + return [self.d2sID hash]; +} + +@end + +@interface FIRMessagingConnection () + +@property(nonatomic, readwrite, weak) FIRMessagingRmqManager *rmq2Manager; +@property(nonatomic, readwrite, weak) FIRMessagingDataMessageManager *dataMessageManager; + +@property(nonatomic, readwrite, assign) FIRMessagingConnectionState state; +@property(nonatomic, readwrite, copy) NSString *host; +@property(nonatomic, readwrite, assign) NSUInteger port; + +@property(nonatomic, readwrite, strong) NSString *authId; +@property(nonatomic, readwrite, strong) NSString *token; + +@property(nonatomic, readwrite, strong) FIRMessagingSecureSocket *socket; + +@property(nonatomic, readwrite, assign) int64_t lastLoginServerTimestamp; +@property(nonatomic, readwrite, assign) int lastStreamIdAcked; +@property(nonatomic, readwrite, assign) int inStreamId; +@property(nonatomic, readwrite, assign) int outStreamId; + +@property(nonatomic, readwrite, strong) NSMutableArray *unackedS2dIds; +@property(nonatomic, readwrite, strong) NSMutableDictionary *ackedS2dMap; +@property(nonatomic, readwrite, strong) NSMutableArray *d2sInfos; +// ttl=0 messages that need to be sent as soon as we establish a connection +@property(nonatomic, readwrite, strong) NSMutableArray *sendOnConnectMessages; + +@property(nonatomic, readwrite, strong) NSRunLoop *runLoop; + +@end + + +@implementation FIRMessagingConnection; + +- (instancetype)initWithAuthID:(NSString *)authId + token:(NSString *)token + host:(NSString *)host + port:(NSUInteger)port + runLoop:(NSRunLoop *)runLoop + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager + fcmManager:(FIRMessagingDataMessageManager *)dataMessageManager { + self = [super init]; + if (self) { + _authId = [authId copy]; + _token = [token copy]; + _host = [host copy]; + _port = port; + _runLoop = runLoop; + _rmq2Manager = rmq2Manager; + _dataMessageManager = dataMessageManager; + + _d2sInfos = [NSMutableArray array]; + + _unackedS2dIds = [NSMutableArray arrayWithArray:[_rmq2Manager unackedS2dRmqIds]]; + _ackedS2dMap = [NSMutableDictionary dictionary]; + _sendOnConnectMessages = [NSMutableArray array]; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"host: %@, port: %lu, stream id in: %d, stream id out: %d", + self.host, + _FIRMessaging_UL(self.port), + self.inStreamId, + self.outStreamId]; +} + +- (void)signIn { + _FIRMessagingDevAssert(self.state == kFIRMessagingConnectionNotConnected, @"Invalid connection state."); + if (self.state != kFIRMessagingConnectionNotConnected) { + return; + } + + // break it up for testing + [self setupConnectionSocket]; + [self connectToSocket:self.socket]; +} + +- (void)setupConnectionSocket { + self.socket = [[FIRMessagingSecureSocket alloc] init]; + self.socket.delegate = self; +} + +- (void)connectToSocket:(FIRMessagingSecureSocket *)socket { + self.state = kFIRMessagingConnectionConnecting; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection000, + @"Start connecting to FIRMessaging service."); + [socket connectToHost:self.host port:self.port onRunLoop:self.runLoop]; +} + +- (void)signOut { + // Clear the list of messages to be sent on connect. This will only + // have messages in it if an error happened before receiving the LoginResponse. + [self.sendOnConnectMessages removeAllObjects]; + + if (self.state == kFIRMessagingConnectionSignedIn) { + [self sendClose]; + } + if (self.state != kFIRMessagingConnectionNotConnected) { + [self disconnect]; + } +} + +- (void)teardown { + if (self.state != kFIRMessagingConnectionNotConnected) { + [self disconnect]; + } +} + +#pragma mark - FIRMessagingSecureSocketDelegate + +- (void)secureSocketDidConnect:(FIRMessagingSecureSocket *)socket { + self.state = kFIRMessagingConnectionConnected; + self.lastStreamIdAcked = 0; + self.inStreamId = 0; + self.outStreamId = 0; + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection001, + @"Connected to FIRMessaging service."); + [self resetUnconfirmedAcks]; + [self sendLoginRequest:self.authId token:self.token]; +} + +- (void)didDisconnectWithSecureSocket:(FIRMessagingSecureSocket *)socket { + _FIRMessagingDevAssert(self.socket == socket, @"Invalid socket"); + _FIRMessagingDevAssert(self.socket.state == kFIRMessagingSecureSocketClosed, @"Socket already closed"); + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection002, + @"Secure socket disconnected from FIRMessaging service."); + [self disconnect]; + [self.delegate connection:self didCloseForReason:kFIRMessagingConnectionCloseReasonSocketDisconnected]; +} + +- (void)secureSocket:(FIRMessagingSecureSocket *)socket + didReceiveData:(NSData *)data + withTag:(int8_t)tag { + if (tag < 0) { + // Invalid proto tag + return; + } + + Class klassForTag = FIRMessagingGetClassForTag((FIRMessagingProtoTag)tag); + if ([klassForTag isSubclassOfClass:[NSNull class]]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeConnection003, @"Invalid tag %d for proto", + tag); + return; + } + + GPBMessage *proto = [klassForTag parseFromData:data error:NULL]; + if (tag == kFIRMessagingProtoTagLoginResponse && self.state != kFIRMessagingConnectionConnected) { + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeConnection004, + @"Should not receive generated message when the connection is not connected."); + return; + } else if (tag != kFIRMessagingProtoTagLoginResponse && self.state != kFIRMessagingConnectionSignedIn) { + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeConnection005, + @"Should not receive generated message when the connection is not signed in."); + return; + } + + // If traffic is received after a heartbeat it is safe to assume the connection is healthy. + [self cancelConnectionTimeoutTask]; + [self performSelector:@selector(sendHeartbeatPing) + withObject:nil + afterDelay:kHeartbeatInterval]; + + [self willProcessProto:proto]; + switch (tag) { + case kFIRMessagingProtoTagLoginResponse: + [self didReceiveLoginResponse:(GtalkLoginResponse *)proto]; + break; + case kFIRMessagingProtoTagDataMessageStanza: + [self didReceiveDataMessageStanza:(GtalkDataMessageStanza *)proto]; + break; + case kFIRMessagingProtoTagHeartbeatPing: + [self didReceiveHeartbeatPing:(GtalkHeartbeatPing *)proto]; + break; + case kFIRMessagingProtoTagHeartbeatAck: + [self didReceiveHeartbeatAck:(GtalkHeartbeatAck *)proto]; + break; + case kFIRMessagingProtoTagClose: + [self didReceiveClose:(GtalkClose *)proto]; + break; + case kFIRMessagingProtoTagIqStanza: + [self handleIqStanza:(GtalkIqStanza *)proto]; + break; + default: + [self didReceiveUnhandledProto:proto]; + break; + } +} + +// Called from secure socket once we have send the proto with given rmqId over the wire +// since we are mostly concerned with user facing messages which certainly have a rmqId +// we can retrieve them from the Rmq if necessary to look at stuff but for now we just +// log it. +- (void)secureSocket:(FIRMessagingSecureSocket *)socket + didSendProtoWithTag:(int8_t)tag + rmqId:(NSString *)rmqId { + // log the message + [self logMessage:rmqId messageType:tag isOut:YES]; +} + +#pragma mark - FIRMessagingTestConnection + +- (void)sendProto:(GPBMessage *)proto { + FIRMessagingProtoTag tag = FIRMessagingGetTagForProto(proto); + if (tag == kFIRMessagingProtoTagLoginRequest && self.state != kFIRMessagingConnectionConnected) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection006, + @"Cannot send generated message when the connection is not connected."); + return; + } else if (tag != kFIRMessagingProtoTagLoginRequest && self.state != kFIRMessagingConnectionSignedIn) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection007, + @"Cannot send generated message when the connection is not signed in."); + return; + } + + _FIRMessagingDevAssert(self.socket != nil, @"Socket shouldn't be nil"); + if (self.socket == nil) { + return; + } + + [self willSendProto:proto]; + + [self.socket sendData:proto.data withTag:tag rmqId:FIRMessagingGetRmq2Id(proto)]; +} + +- (void)sendOnConnectOrDrop:(GPBMessage *)message { + if (self.state == kFIRMessagingConnectionSignedIn) { + // If a connection has already been established, send normally + [self sendProto:message]; + } else { + // Otherwise add them to the list of messages to send after login + [self.sendOnConnectMessages addObject:message]; + } +} + ++ (GtalkLoginRequest *)loginRequestWithToken:(NSString *)token authID:(NSString *)authID { + GtalkLoginRequest *login = [[GtalkLoginRequest alloc] init]; + login.accountId = 1000000; + login.authService = GtalkLoginRequest_AuthService_AndroidId; + login.authToken = token; + login.id_p = [NSString stringWithFormat:@"%@-%@", @"ios", FIRMessagingCurrentLibraryVersion()]; + login.domain = @"mcs.android.com"; + login.deviceId = [NSString stringWithFormat:@"android-%llx", authID.longLongValue]; + login.networkType = [self currentNetworkType]; + login.resource = authID; + login.user = authID; + login.useRmq2 = YES; + login.lastRmqId = 1; // Sending not enabled yet so this stays as 1. + return login; +} + ++ (int32_t)currentNetworkType { + // http://developer.android.com/reference/android/net/ConnectivityManager.html + int32_t fcmNetworkType; + FIRMessagingNetworkStatus type = [[FIRMessaging messaging] networkType]; + switch (type) { + case kFIRMessagingReachabilityReachableViaWiFi: + fcmNetworkType = 1; + break; + + case kFIRMessagingReachabilityReachableViaWWAN: + fcmNetworkType = 0; + break; + + default: + fcmNetworkType = -1; + break; + } + return fcmNetworkType; +} + +- (void)sendLoginRequest:(NSString *)authId + token:(NSString *)token { + GtalkLoginRequest *login = [[self class] loginRequestWithToken:token authID:authId]; + + // clear the messages sent during last connection + if ([self.d2sInfos count]) { + [self.d2sInfos removeAllObjects]; + } + + if (self.unackedS2dIds.count > 0) { + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeConnection008, + @"There are unacked persistent Ids in the login request: %@", + [self.unackedS2dIds.description stringByReplacingOccurrencesOfString:@"%" + withString:@"%%"]); + } + // Send out acks. + for (NSString *unackedPersistentS2dId in self.unackedS2dIds) { + [login.receivedPersistentIdArray addObject:unackedPersistentS2dId]; + } + + GtalkSetting *setting = [[GtalkSetting alloc] init]; + setting.name = @"new_vc"; + setting.value = @"1"; + [login.settingArray addObject:setting]; + + [self sendProto:login]; +} + +- (void)sendHeartbeatAck { + [self sendProto:[[GtalkHeartbeatAck alloc] init]]; +} + +- (void)sendHeartbeatPing { + // cancel the previous heartbeat request. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(sendHeartbeatPing) + object:nil]; + [self scheduleConnectionTimeoutTask]; + [self sendProto:[[GtalkHeartbeatPing alloc] init]]; +} + ++ (GtalkIqStanza *)createStreamAck { + GtalkIqStanza *iq = [[GtalkIqStanza alloc] init]; + iq.type = GtalkIqStanza_IqType_Set; + iq.id_p = @""; + GtalkExtension *ext = [[GtalkExtension alloc] init]; + ext.id_p = kIqStreamAck; + ext.data_p = @""; + iq.extension = ext; + return iq; +} + +- (void)sendStreamAck { + GtalkIqStanza *iq = [[self class] createStreamAck]; + [self sendProto:iq]; +} + +- (void)sendClose { + [self sendProto:[[GtalkClose alloc] init]]; +} + +- (void)handleIqStanza:(GtalkIqStanza *)iq { + if (iq.hasExtension) { + if (iq.extension.id_p == kIqStreamAck) { + [self didReceiveStreamAck:iq]; + return; + } + if (iq.extension.id_p == kIqSelectiveAck) { + [self didReceiveSelectiveAck:iq]; + return; + } + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection009, @"Unknown ack extension id %d.", + iq.extension.id_p); + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection010, @"Ip stanza without extension."); + } + [self didReceiveUnhandledProto:iq]; +} + +- (void)didReceiveLoginResponse:(GtalkLoginResponse *)loginResponse { + if (loginResponse.hasError) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection011, + @"Login error with type: %@, message: %@.", loginResponse.error.type, + loginResponse.error.message); + return; + } + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection012, @"Logged onto MCS service."); + // We sent the persisted list of unack'd messages with login so we can assume they have been ack'd + // by the server. + _FIRMessagingDevAssert(self.unackedS2dIds.count == 0, @"No ids present"); + _FIRMessagingDevAssert(self.outStreamId == 1, @"Login should be the first stream id"); + + self.state = kFIRMessagingConnectionSignedIn; + self.lastLoginServerTimestamp = loginResponse.serverTimestamp; + [self.delegate didLoginWithConnection:self]; + [self sendHeartbeatPing]; + + // Add all the TTL=0 messages on connect + for (GPBMessage *message in self.sendOnConnectMessages) { + [self sendProto:message]; + } + [self.sendOnConnectMessages removeAllObjects]; +} + +- (void)didReceiveHeartbeatPing:(GtalkHeartbeatPing *)heartbeatPing { + [self sendHeartbeatAck]; +} + +- (void)didReceiveHeartbeatAck:(GtalkHeartbeatAck *)heartbeatAck { +} + +- (void)didReceiveDataMessageStanza:(GtalkDataMessageStanza *)dataMessageStanza { + // TODO: Maybe add support raw data later + [self.delegate connectionDidRecieveMessage:dataMessageStanza]; +} + +- (void)didReceiveUnhandledProto:(GPBMessage *)proto { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection013, @"Received unhandled proto"); +} + +- (void)didReceiveStreamAck:(GtalkIqStanza *)iq { + // Server received some stuff from us we don't really need to do anything special +} + +- (void)didReceiveSelectiveAck:(GtalkIqStanza *)iq { + GtalkExtension *extension = iq.extension; + if (extension) { + int extensionId = extension.id_p; + if (extensionId == kIqSelectiveAck) { + + NSString *dataString = extension.data_p; + GtalkSelectiveAck *selectiveAck = [[GtalkSelectiveAck alloc] init]; + [selectiveAck mergeFromData:[dataString dataUsingEncoding:NSUTF8StringEncoding] + extensionRegistry:nil]; + + NSArray *acks = [selectiveAck idArray]; + + // we've received ACK's + [self.delegate connectionDidReceiveAckForRmqIds:acks]; + + // resend unacked messages + [self.dataMessageManager resendMessagesWithConnection:self]; + } + } +} + +- (void)didReceiveClose:(GtalkClose *)close { + [self disconnect]; +} + +- (void)willProcessProto:(GPBMessage *)proto { + self.inStreamId++; + + if ([proto isKindOfClass:GtalkDataMessageStanza.class]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection014, + @"RMQ: Receiving %@ with rmq_id: %@ incoming stream Id: %d", + proto.class, FIRMessagingGetRmq2Id(proto), self.inStreamId); + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection015, + @"RMQ: Receiving %@ with incoming stream Id: %d.", proto.class, + self.inStreamId); + } + int streamId = FIRMessagingGetLastStreamId(proto); + if (streamId != kInvalidStreamId) { + // confirm the D2S messages that were sent by us + [self confirmAckedD2sIdsWithStreamId:streamId]; + + // We can now confirm that our ack was received by the server and start our unack'd list fresh + // with the proto we just received. + [self confirmAckedS2dIdsWithStreamId:streamId]; + } + NSString *rmq2Id = FIRMessagingGetRmq2Id(proto); + if (rmq2Id != nil) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection016, + @"RMQ: Add unacked persistent Id: %@.", + [rmq2Id stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]); + [self.unackedS2dIds addObject:rmq2Id]; + [self.rmq2Manager saveS2dMessageWithRmqId:rmq2Id]; // RMQ save + } + BOOL explicitAck = ([proto isKindOfClass:[GtalkDataMessageStanza class]] && + [(GtalkDataMessageStanza *)proto immediateAck]); + // If we have not sent anything and the ack threshold has been reached then explicitly send one + // to notify the server that we have received messages. + if (self.inStreamId - self.lastStreamIdAcked >= kAckingInterval || explicitAck) { + [self sendStreamAck]; + } +} + +- (void)willSendProto:(GPBMessage *)proto { + self.outStreamId++; + + NSString *rmq2Id = FIRMessagingGetRmq2Id(proto); + if ([rmq2Id length]) { + FIRMessagingD2SInfo *d2sInfo = [[FIRMessagingD2SInfo alloc] initWithStreamId:self.outStreamId d2sId:rmq2Id]; + [self.d2sInfos addObject:d2sInfo]; + } + + // each time we send a d2s message, it acks previously received + // s2d messages via the last (s2d) stream id received. + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection017, + @"RMQ: Sending %@ with outgoing stream Id: %d.", proto.class, + self.outStreamId); + // We have received messages since last time we sent something - send ack info to server. + if (self.inStreamId > self.lastStreamIdAcked) { + FIRMessagingSetLastStreamId(proto, self.inStreamId); + self.lastStreamIdAcked = self.inStreamId; + } + + if (self.unackedS2dIds.count > 0) { + // Move all 'unack'd' messages to the ack'd map so they can be removed once the + // ack is confirmed. + NSArray *ackedS2dIds = [NSArray arrayWithArray:self.unackedS2dIds]; + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeConnection018, @"RMQ: Mark persistent Ids as acked: %@.", + [ackedS2dIds.description stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]); + [self.unackedS2dIds removeAllObjects]; + self.ackedS2dMap[[@(self.outStreamId) stringValue]] = ackedS2dIds; + } +} + +#pragma mark - Private + +/** + * This processes the s2d message received in reference to the d2s messages + * that we have sent before. + */ +- (void)confirmAckedD2sIdsWithStreamId:(int)lastReceivedStreamId { + NSMutableArray *d2sIdsAcked = [NSMutableArray array]; + for (FIRMessagingD2SInfo *d2sInfo in self.d2sInfos) { + if (lastReceivedStreamId < d2sInfo.streamId) { + break; + } + [d2sIdsAcked addObject:d2sInfo]; + } + + NSMutableArray *rmqIds = [NSMutableArray arrayWithCapacity:[d2sIdsAcked count]]; + // remove ACK'ed messages + for (FIRMessagingD2SInfo *d2sInfo in d2sIdsAcked) { + if ([d2sInfo.d2sID length]) { + [rmqIds addObject:d2sInfo.d2sID]; + } + [self.d2sInfos removeObject:d2sInfo]; + } + [self.delegate connectionDidReceiveAckForRmqIds:rmqIds]; + int count = [self.delegate connectionDidReceiveAckForRmqIds:rmqIds]; + if (kMessageRemoveAckThresholdCount > 0 && count >= kMessageRemoveAckThresholdCount) { + // For short lived connections, if a large number of messages are removed, send an + // ack straight away so the server knows that this message was received. + [self sendStreamAck]; + } +} + +/** + * Called when a stream ACK or a selective ACK are received - this indicates the message has + * been received by MCS. + */ +- (void)didReceiveAckForRmqIds:(NSArray *)rmqIds { + // TODO: let the user know that the following messages were received by the server +} + +- (void)confirmAckedS2dIdsWithStreamId:(int)lastReceivedStreamId { + // If the server hasn't received the streamId yet. + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection019, + @"RMQ: Server last received stream Id: %d.", lastReceivedStreamId); + if (lastReceivedStreamId < self.outStreamId) { + // TODO: This could be a good indicator that we need to re-send something (acks)? + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection020, + @"RMQ: There are unsent messages that should be send...\n" + "server received: %d\nlast stream id sent: %d", + lastReceivedStreamId, self.outStreamId); + } + + NSSet *ackedStreamIds = + [self.ackedS2dMap keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { + NSString *streamId = key; + return streamId.intValue <= lastReceivedStreamId; + }]; + NSMutableArray *s2dIdsToDelete = [NSMutableArray array]; + + for (NSString *streamId in ackedStreamIds) { + NSArray *ackedS2dIds = self.ackedS2dMap[streamId]; + if (ackedS2dIds.count > 0) { + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeConnection021, + @"RMQ: Mark persistent Ids as confirmed by stream id %@: %@.", streamId, + [ackedS2dIds.description stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]); + [self.ackedS2dMap removeObjectForKey:streamId]; + } + + [s2dIdsToDelete addObjectsFromArray:ackedS2dIds]; + } + + // clean up s2d ids that the server knows we've received. + // we let the server know via a s2d last stream id received in a + // d2s message. the server lets us know it has received our d2s + // message via a d2s last stream id received in a s2d message. + [self.rmq2Manager removeS2dIds:s2dIdsToDelete]; +} + +- (void)resetUnconfirmedAcks { + [self.ackedS2dMap enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [self.unackedS2dIds addObjectsFromArray:obj]; + }]; + [self.ackedS2dMap removeAllObjects]; +} + +- (void)disconnect { + _FIRMessagingDevAssert(self.state != kFIRMessagingConnectionNotConnected, @"Connection already not connected"); + // cancel pending timeout tasks. + [self cancelConnectionTimeoutTask]; + // cancel pending heartbeat. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(sendHeartbeatPing) + object:nil]; + // Unset the delegate. FIRMessagingConnection will not receive further events from the socket from now on. + self.socket.delegate = nil; + [self.socket disconnect]; + self.state = kFIRMessagingConnectionNotConnected; +} + +- (void)connectionTimedOut { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection022, + @"Connection to FIRMessaging service timed out."); + [self disconnect]; + [self.delegate connection:self didCloseForReason:kFIRMessagingConnectionCloseReasonTimeout]; +} + +- (void)scheduleConnectionTimeoutTask { + // cancel the previous heartbeat timeout event and schedule a new one. + [self cancelConnectionTimeoutTask]; + [self performSelector:@selector(connectionTimedOut) + withObject:nil + afterDelay:[self connectionTimeoutInterval]]; +} + +- (void)cancelConnectionTimeoutTask { + // cancel pending timeout tasks. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(connectionTimedOut) + object:nil]; +} + +- (void)logMessage:(NSString *)description messageType:(int)messageType isOut:(BOOL)isOut { + messageType = isOut ? -messageType : messageType; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeConnection023, + @"Send msg: %@ type: %d inStreamId: %d outStreamId: %d", description, + messageType, self.inStreamId, self.outStreamId); +} + +- (NSTimeInterval)connectionTimeoutInterval { + return kConnectionTimeout; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.h new file mode 100644 index 0000000..ad0d6c9 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.h @@ -0,0 +1,58 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Global constants to be put here. + * + */ +#import + +#ifndef _FIRMessaging_CONSTANTS_H +#define _FIRMessaging_CONSTANTS_H + +FOUNDATION_EXPORT NSString *const kFIRMessagingRawDataKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingCollapseKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingFromKey; + +FOUNDATION_EXPORT NSString *const kFIRMessagingSendTo; +FOUNDATION_EXPORT NSString *const kFIRMessagingSendTTL; +FOUNDATION_EXPORT NSString *const kFIRMessagingSendDelay; +FOUNDATION_EXPORT NSString *const kFIRMessagingSendMessageID; +FOUNDATION_EXPORT NSString *const KFIRMessagingSendMessageAppData; + +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageInternalReservedKeyword; +FOUNDATION_EXPORT NSString *const kFIRMessagingMessagePersistentIDKey; + +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageIDKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageAPNSContentAvailableKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageSyncViaMCSKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageSyncMessageTTLKey; +FOUNDATION_EXPORT NSString *const kFIRMessagingMessageLinkKey; + +FOUNDATION_EXPORT NSString *const kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey; + +FOUNDATION_EXPORT NSString *const kFIRMessagingApplicationSupportSubDirectory; + +// Notifications +FOUNDATION_EXPORT NSString *const kFIRMessagingCheckinFetchedNotification; +FOUNDATION_EXPORT NSString *const kFIRMessagingAPNSTokenNotification; +FOUNDATION_EXPORT NSString *const kFIRMessagingFCMTokenNotification; +FOUNDATION_EXPORT NSString *const kFIRMessagingInstanceIDTokenRefreshNotification __deprecated_msg("Use kFIRMessagingRegistrationTokenRefreshNotification instead"); +FOUNDATION_EXPORT NSString *const kFIRMessagingRegistrationTokenRefreshNotification; + +FOUNDATION_EXPORT const int kFIRMessagingSendTtlDefault; // 24 hours + +#endif diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.m new file mode 100644 index 0000000..8904cc5 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingConstants.m @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingConstants.h" + +NSString *const kFIRMessagingRawDataKey = @"rawData"; +NSString *const kFIRMessagingCollapseKey = @"collapse_key"; +NSString *const kFIRMessagingFromKey = @"from"; + +NSString *const kFIRMessagingSendTo = @"google." @"to"; +NSString *const kFIRMessagingSendTTL = @"google." @"ttl"; +NSString *const kFIRMessagingSendDelay = @"google." @"delay"; +NSString *const kFIRMessagingSendMessageID = @"google." @"msg_id"; +NSString *const KFIRMessagingSendMessageAppData = @"google." @"data"; + +NSString *const kFIRMessagingMessageInternalReservedKeyword = @"gcm."; +NSString *const kFIRMessagingMessagePersistentIDKey = @"persistent_id"; + +NSString *const kFIRMessagingMessageIDKey = @"gcm." @"message_id"; +NSString *const kFIRMessagingMessageAPNSContentAvailableKey = @"content-available"; +NSString *const kFIRMessagingMessageSyncViaMCSKey = @"gcm." @"duplex"; +NSString *const kFIRMessagingMessageSyncMessageTTLKey = @"gcm." @"ttl"; +NSString *const kFIRMessagingMessageLinkKey = @"gcm." @"app_link"; + +NSString *const kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey = + @"FirebaseAppDelegateProxyEnabled"; + +NSString *const kFIRMessagingApplicationSupportSubDirectory = @"Google/FirebaseMessaging"; + +// Notifications +NSString *const kFIRMessagingCheckinFetchedNotification = @"com.google.gcm.notif-checkin-fetched"; +NSString *const kFIRMessagingAPNSTokenNotification = @"com.firebase.iid.notif.apns-token"; +NSString *const kFIRMessagingFCMTokenNotification = @"com.firebase.iid.notif.fcm-token"; +NSString *const kFIRMessagingInstanceIDTokenRefreshNotification = + @"com.firebase.iid.notif.refresh-token"; +NSString *const kFIRMessagingRegistrationTokenRefreshNotification = + @"com.firebase.iid.notif.refresh-token"; + +const int kFIRMessagingSendTtlDefault = 24 * 60 * 60; // 24 hours diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.h new file mode 100644 index 0000000..83e6444 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.h @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +FOUNDATION_EXPORT NSString *const kFIRMessagingContextManagerCategory; +FOUNDATION_EXPORT NSString *const kFIRMessagingContextManagerLocalTimeStart; +FOUNDATION_EXPORT NSString *const kFIRMessagingContextManagerLocalTimeEnd; +FOUNDATION_EXPORT NSString *const kFIRMessagingContextManagerBodyKey; + +@interface FIRMessagingContextManagerService : NSObject + +/** + * Check if the message is a context manager message or not. + * + * @param message The message to verify. + * + * @return YES if the message is a context manager message else NO. + */ ++ (BOOL)isContextManagerMessage:(NSDictionary *)message; + +/** + * Handle context manager message. + * + * @param message The message to handle. + * + * @return YES if the message was handled successfully else NO. + */ ++ (BOOL)handleContextManagerMessage:(NSDictionary *)message; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.m new file mode 100644 index 0000000..8527db1 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingContextManagerService.m @@ -0,0 +1,203 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingContextManagerService.h" + +#import + +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingUtilities.h" + +#define kFIRMessagingContextManagerPrefixKey @"google.c.cm." +#define kFIRMessagingContextManagerNotificationKeyPrefix @"gcm.notification." + +static NSString *const kLogTag = @"FIRMessagingAnalytics"; + +static NSString *const kLocalTimeFormatString = @"yyyy-MM-dd HH:mm:ss"; + +static NSString *const kContextManagerPrefixKey = kFIRMessagingContextManagerPrefixKey; + +// Local timed messages (format yyyy-mm-dd HH:mm:ss) +NSString *const kFIRMessagingContextManagerLocalTimeStart = kFIRMessagingContextManagerPrefixKey @"lt_start"; +NSString *const kFIRMessagingContextManagerLocalTimeEnd = kFIRMessagingContextManagerPrefixKey @"lt_end"; + +// Local Notification Params +NSString *const kFIRMessagingContextManagerBodyKey = kFIRMessagingContextManagerNotificationKeyPrefix @"body"; +NSString *const kFIRMessagingContextManagerTitleKey = kFIRMessagingContextManagerNotificationKeyPrefix @"title"; +NSString *const kFIRMessagingContextManagerBadgeKey = kFIRMessagingContextManagerNotificationKeyPrefix @"badge"; +NSString *const kFIRMessagingContextManagerCategoryKey = + kFIRMessagingContextManagerNotificationKeyPrefix @"click_action"; +NSString *const kFIRMessagingContextManagerSoundKey = kFIRMessagingContextManagerNotificationKeyPrefix @"sound"; +NSString *const kFIRMessagingContextManagerContentAvailableKey = + kFIRMessagingContextManagerNotificationKeyPrefix @"content-available"; + +typedef NS_ENUM(NSUInteger, FIRMessagingContextManagerMessageType) { + FIRMessagingContextManagerMessageTypeNone, + FIRMessagingContextManagerMessageTypeLocalTime, +}; + +@implementation FIRMessagingContextManagerService + ++ (BOOL)isContextManagerMessage:(NSDictionary *)message { + // For now we only support local time in ContextManager. + if (![message[kFIRMessagingContextManagerLocalTimeStart] length]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeContextManagerService000, + @"Received message missing local start time, dropped."); + return NO; + } + + return YES; +} + ++ (BOOL)handleContextManagerMessage:(NSDictionary *)message { + NSString *startTimeString = message[kFIRMessagingContextManagerLocalTimeStart]; + if (startTimeString.length) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeContextManagerService001, + @"%@ Received context manager message with local time %@", kLogTag, + startTimeString); + return [self handleContextManagerLocalTimeMessage:message]; + } + + return NO; +} + ++ (BOOL)handleContextManagerLocalTimeMessage:(NSDictionary *)message { + NSString *startTimeString = message[kFIRMessagingContextManagerLocalTimeStart]; + NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; + dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; + [dateFormatter setDateFormat:kLocalTimeFormatString]; + NSDate *startDate = [dateFormatter dateFromString:startTimeString]; + + _FIRMessagingDevAssert(startDate, @"Invalid local start date format %@", startTimeString); + if (!startTimeString) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeContextManagerService002, + @"Invalid local start date format %@. Message dropped", + startTimeString); + return NO; + } + + NSDate *currentDate = [NSDate date]; + + if ([currentDate compare:startDate] == NSOrderedAscending) { + [self scheduleLocalNotificationForMessage:message + atDate:startDate]; + } else { + // check end time has not passed + NSString *endTimeString = message[kFIRMessagingContextManagerLocalTimeEnd]; + if (!endTimeString) { + FIRMessagingLoggerInfo( + kFIRMessagingMessageCodeContextManagerService003, + @"No end date specified for message, start date elapsed. Message dropped."); + return YES; + } + + NSDate *endDate = [dateFormatter dateFromString:endTimeString]; + + _FIRMessagingDevAssert(endDate, @"Invalid local end date format %@", endTimeString); + if (!endTimeString) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeContextManagerService004, + @"Invalid local end date format %@. Message dropped", endTimeString); + return NO; + } + + if ([endDate compare:currentDate] == NSOrderedAscending) { + // end date has already passed drop the message + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeContextManagerService005, + @"End date %@ has already passed. Message dropped.", endTimeString); + return YES; + } + + // schedule message right now (buffer 10s) + [self scheduleLocalNotificationForMessage:message + atDate:[currentDate dateByAddingTimeInterval:10]]; + } + return YES; +} + ++ (void)scheduleLocalNotificationForMessage:(NSDictionary *)message + atDate:(NSDate *)date { + NSDictionary *apsDictionary = message; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + UILocalNotification *notification = [[UILocalNotification alloc] init]; +#pragma clang diagnostic pop + + // A great way to understand timezones and UILocalNotifications + // http://stackoverflow.com/questions/18424569/understanding-uilocalnotification-timezone + notification.timeZone = [NSTimeZone defaultTimeZone]; + notification.fireDate = date; + + // In the current solution all of the display stuff goes into a special "aps" dictionary + // being sent in the message. + if ([apsDictionary[kFIRMessagingContextManagerBodyKey] length]) { + notification.alertBody = apsDictionary[kFIRMessagingContextManagerBodyKey]; + } + if ([apsDictionary[kFIRMessagingContextManagerTitleKey] length]) { + // |alertTitle| is iOS 8.2+, so check if we can set it + if ([notification respondsToSelector:@selector(setAlertTitle:)]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + notification.alertTitle = apsDictionary[kFIRMessagingContextManagerTitleKey]; +#pragma pop + } + } + + if (apsDictionary[kFIRMessagingContextManagerSoundKey]) { + notification.soundName = apsDictionary[kFIRMessagingContextManagerSoundKey]; + } + if (apsDictionary[kFIRMessagingContextManagerBadgeKey]) { + notification.applicationIconBadgeNumber = + [apsDictionary[kFIRMessagingContextManagerBadgeKey] integerValue]; + } + if (apsDictionary[kFIRMessagingContextManagerCategoryKey]) { + // |category| is iOS 8.0+, so check if we can set it + if ([notification respondsToSelector:@selector(setCategory:)]) { + notification.category = apsDictionary[kFIRMessagingContextManagerCategoryKey]; + } + } + + NSDictionary *userInfo = [self parseDataFromMessage:message]; + if (userInfo.count) { + notification.userInfo = userInfo; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + UIApplication *application = FIRMessagingUIApplication(); + if (!application) { + return; + } + [application scheduleLocalNotification:notification]; +#pragma clang diagnostic pop +} + ++ (NSDictionary *)parseDataFromMessage:(NSDictionary *)message { + NSMutableDictionary *data = [NSMutableDictionary dictionary]; + for (NSObject *key in message) { + if ([key isKindOfClass:[NSString class]]) { + NSString *keyString = (NSString *)key; + if ([keyString isEqualToString:kFIRMessagingContextManagerContentAvailableKey]) { + continue; + } else if ([keyString hasPrefix:kContextManagerPrefixKey]) { + continue; + } + } + data[[key copy]] = message[key]; + } + return [data copy]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.h new file mode 100644 index 0000000..cf8df74 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.h @@ -0,0 +1,101 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class GtalkDataMessageStanza; + +@class FIRMessagingClient; +@class FIRMessagingConnection; +@class FIRMessagingReceiver; +@class FIRMessagingRmqManager; +@class FIRMessagingSyncMessageManager; + +@protocol FIRMessagingDataMessageManagerDelegate + +#pragma mark - Downstream Callbacks + +/** + * Invoked when FIRMessaging receives a downstream message via the MCS connection. + * Let's the user know that they have received a new message by invoking the + * App's remoteNotification callback. + * + * @param message The downstream message received by the MCS connection. + */ +- (void)didReceiveMessage:(nonnull NSDictionary *)message + withIdentifier:(nullable NSString *)messageID; + +#pragma mark - Upstream Callbacks + +/** + * Notify the app that FIRMessaging will soon be sending the upstream message requested by the app. + * + * @param messageID The messageId passed in by the app to track this particular message. + * @param error The error in case FIRMessaging cannot send the message upstream. + */ +- (void)willSendDataMessageWithID:(nullable NSString *)messageID error:(nullable NSError *)error; + +/** + * Notify the app that FIRMessaging did successfully send it's message via the MCS + * connection and the message was successfully delivered. + * + * @param messageId The messageId passed in by the app to track this particular + * message. + */ +- (void)didSendDataMessageWithID:(nonnull NSString *)messageId; + +#pragma mark - Server Callbacks + +/** + * Notify the app that FIRMessaging server deleted some messages which exceeded storage limits. This + * indicates the "deleted_messages" message type we received from the server. + */ +- (void)didDeleteMessagesOnServer; + +@end + +/** + * This manages all of the data messages being sent by the client and also the messages that + * were received from the server. + */ +@interface FIRMessagingDataMessageManager : NSObject + +NS_ASSUME_NONNULL_BEGIN + +- (instancetype)initWithDelegate:(id)delegate + client:(FIRMessagingClient *)client + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager + syncMessageManager:(FIRMessagingSyncMessageManager *)syncMessageManager; + +- (void)setDeviceAuthID:(NSString *)deviceAuthID secretToken:(NSString *)secretToken; + +- (void)refreshDelayedMessages; + +#pragma mark - Receive + +- (nullable NSDictionary *)processPacket:(GtalkDataMessageStanza *)packet; +- (void)didReceiveParsedMessage:(NSDictionary *)message; + +#pragma mark - Send + +- (void)sendDataMessageStanza:(NSMutableDictionary *)dataMessage; +- (void)didSendDataMessageStanza:(GtalkDataMessageStanza *)message; + +- (void)resendMessagesWithConnection:(FIRMessagingConnection *)connection; + +NS_ASSUME_NONNULL_END + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.m new file mode 100644 index 0000000..b62763a --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDataMessageManager.m @@ -0,0 +1,528 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingDataMessageManager.h" + +#import "Protos/GtalkCore.pbobjc.h" + +#import "FIRMessagingClient.h" +#import "FIRMessagingConnection.h" +#import "FIRMessagingConstants.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingDelayedMessageQueue.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingReceiver.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessaging_Private.h" +#import "FIRMessagingSyncMessageManager.h" +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" + +static const int kMaxAppDataSizeDefault = 4 * 1024; // 4k +static const int kMinDelaySeconds = 1; // 1 second +static const int kMaxDelaySeconds = 60 * 60; // 1 hour + +static NSString *const kFromForFIRMessagingMessages = @"mcs.android.com"; +static NSString *const kGSFMessageCategory = @"com.google.android.gsf.gtalkservice"; +// TODO: Update Gcm to FIRMessaging in the constants below +static NSString *const kFCMMessageCategory = @"com.google.gcm"; +static NSString *const kMessageReservedPrefix = @"google."; + +static NSString *const kFCMMessageSpecialMessage = @"message_type"; + +// special messages sent by the server +static NSString *const kFCMMessageTypeDeletedMessages = @"deleted_messages"; + +static NSString *const kMCSNotificationPrefix = @"gcm.notification."; +static NSString *const kDataMessageNotificationKey = @"notification"; + + +typedef NS_ENUM(int8_t, UpstreamForceReconnect) { + // Never force reconnect on upstream messages + kUpstreamForceReconnectOff = 0, + // Force reconnect for TTL=0 upstream messages + kUpstreamForceReconnectTTL0 = 1, + // Force reconnect for all upstream messages + kUpstreamForceReconnectAll = 2, +}; + +@interface FIRMessagingDataMessageManager () + +@property(nonatomic, readwrite, weak) FIRMessagingClient *client; +@property(nonatomic, readwrite, weak) FIRMessagingRmqManager *rmq2Manager; +@property(nonatomic, readwrite, weak) FIRMessagingSyncMessageManager *syncMessageManager; +@property(nonatomic, readwrite, weak) id delegate; +@property(nonatomic, readwrite, strong) FIRMessagingDelayedMessageQueue *delayedMessagesQueue; + +@property(nonatomic, readwrite, assign) int ttl; +@property(nonatomic, readwrite, copy) NSString *deviceAuthID; +@property(nonatomic, readwrite, copy) NSString *secretToken; +@property(nonatomic, readwrite, assign) int maxAppDataSize; +@property(nonatomic, readwrite, assign) UpstreamForceReconnect upstreamForceReconnect; + +@end + +@implementation FIRMessagingDataMessageManager + +- (instancetype)initWithDelegate:(id)delegate + client:(FIRMessagingClient *)client + rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager + syncMessageManager:(FIRMessagingSyncMessageManager *)syncMessageManager { + self = [super init]; + if (self) { + _delegate = delegate; + _client = client; + _rmq2Manager = rmq2Manager; + _syncMessageManager = syncMessageManager; + _ttl = kFIRMessagingSendTtlDefault; + _maxAppDataSize = kMaxAppDataSizeDefault; + // on by default + _upstreamForceReconnect = kUpstreamForceReconnectAll; + } + return self; +} + +- (void)setDeviceAuthID:(NSString *)deviceAuthID secretToken:(NSString *)secretToken { + _FIRMessagingDevAssert([deviceAuthID length] && [secretToken length], + @"Invalid credentials for FIRMessaging"); + self.deviceAuthID = deviceAuthID; + self.secretToken = secretToken; +} + +- (void)refreshDelayedMessages { + FIRMessaging_WEAKIFY(self); + self.delayedMessagesQueue = + [[FIRMessagingDelayedMessageQueue alloc] initWithRmqScanner:self.rmq2Manager + sendDelayedMessagesHandler:^(NSArray *messages) { + FIRMessaging_STRONGIFY(self); + [self sendDelayedMessages:messages]; + }]; +} + +- (nullable NSDictionary *)processPacket:(GtalkDataMessageStanza *)dataMessage { + NSString *category = dataMessage.category; + NSString *from = dataMessage.from; + if ([kFCMMessageCategory isEqualToString:category] || + [kGSFMessageCategory isEqualToString:category]) { + [self handleMCSDataMessage:dataMessage]; + return nil; + } else if ([kFromForFIRMessagingMessages isEqualToString:from]) { + [self handleMCSDataMessage:dataMessage]; + return nil; + } + + return [self parseDataMessage:dataMessage]; +} + +- (void)handleMCSDataMessage:(GtalkDataMessageStanza *)dataMessage { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager000, + @"Received message for FIRMessaging from downstream %@", dataMessage); +} + +- (NSDictionary *)parseDataMessage:(GtalkDataMessageStanza *)dataMessage { + NSMutableDictionary *message = [NSMutableDictionary dictionary]; + NSString *from = [dataMessage from]; + if ([from length]) { + message[kFIRMessagingFromKey] = from; + } + + // raw data + NSData *rawData = [dataMessage rawData]; + if ([rawData length]) { + message[kFIRMessagingRawDataKey] = rawData; + } + + NSString *token = [dataMessage token]; + if ([token length]) { + message[kFIRMessagingCollapseKey] = token; + } + + // Add the persistent_id. This would be removed later before sending the message to the device. + NSString *persistentID = [dataMessage persistentId]; + _FIRMessagingDevAssert([persistentID length], @"Invalid MCS message without persistentID"); + if ([persistentID length]) { + message[kFIRMessagingMessageIDKey] = persistentID; + } + + // third-party data + for (GtalkAppData *item in dataMessage.appDataArray) { + _FIRMessagingDevAssert(item.hasKey && item.hasValue, @"Invalid AppData"); + + // do not process the "from" key -- is not useful + if ([kFIRMessagingFromKey isEqualToString:item.key]) { + continue; + } + + // Filter the "gcm.notification." keys in the message + if ([item.key hasPrefix:kMCSNotificationPrefix]) { + NSString *key = [item.key substringFromIndex:[kMCSNotificationPrefix length]]; + if ([key length]) { + if (!message[kDataMessageNotificationKey]) { + message[kDataMessageNotificationKey] = [NSMutableDictionary dictionary]; + } + message[kDataMessageNotificationKey][key] = item.value; + } else { + _FIRMessagingDevAssert([key length], @"Invalid key in MCS message: %@", key); + FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager001, + @"Invalid key in MCS message: %@", key); + } + continue; + } + + // Filter the "gcm.duplex" key + if ([item.key isEqualToString:kFIRMessagingMessageSyncViaMCSKey]) { + BOOL value = [item.value boolValue]; + message[kFIRMessagingMessageSyncViaMCSKey] = @(value); + continue; + } + + // do not allow keys with "reserved" keyword + if ([[item.key lowercaseString] hasPrefix:kMessageReservedPrefix]) { + continue; + } + + [message setObject:item.value forKey:item.key]; + } + // TODO: Add support for encrypting raw data later + return [NSDictionary dictionaryWithDictionary:message]; +} + +- (void)didReceiveParsedMessage:(NSDictionary *)message { + if ([message[kFCMMessageSpecialMessage] length]) { + NSString *messageType = message[kFCMMessageSpecialMessage]; + if ([kFCMMessageTypeDeletedMessages isEqualToString:messageType]) { + // TODO: Maybe trim down message to remove some unnecessary fields. + // tell the FCM receiver of deleted messages + [self.delegate didDeleteMessagesOnServer]; + return; + } + FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager002, + @"Invalid message type received: %@", messageType); + } else if (message[kFIRMessagingMessageSyncViaMCSKey]) { + // Update SYNC_RMQ with the message + BOOL isDuplicate = [self.syncMessageManager didReceiveMCSSyncMessage:message]; + if (isDuplicate) { + return; + } + } + NSString *messageId = message[kFIRMessagingMessageIDKey]; + NSDictionary *filteredMessage = [self filterInternalFIRMessagingKeysFromMessage:message]; + [self.delegate didReceiveMessage:filteredMessage withIdentifier:messageId]; +} + +- (NSDictionary *)filterInternalFIRMessagingKeysFromMessage:(NSDictionary *)message { + NSMutableDictionary *newMessage = [NSMutableDictionary dictionaryWithDictionary:message]; + for (NSString *key in message) { + if ([key hasPrefix:kFIRMessagingMessageInternalReservedKeyword]) { + [newMessage removeObjectForKey:key]; + } + } + return [newMessage copy]; +} + +- (void)sendDataMessageStanza:(NSMutableDictionary *)dataMessage { + NSNumber *ttlNumber = dataMessage[kFIRMessagingSendTTL]; + NSString *to = dataMessage[kFIRMessagingSendTo]; + NSString *msgId = dataMessage[kFIRMessagingSendMessageID]; + NSString *appPackage = [self categoryForUpstreamMessages]; + GtalkDataMessageStanza *stanza = [[GtalkDataMessageStanza alloc] init]; + + // TODO: enforce TTL (right now only ttl=0 is special, means no storage) + int ttl = [ttlNumber intValue]; + if (ttl < 0 || ttl > self.ttl) { + ttl = self.ttl; + } + [stanza setTtl:ttl]; + [stanza setSent:FIRMessagingCurrentTimestampInSeconds()]; + + int delay = [self delayForMessage:dataMessage]; + if (delay > 0) { + [stanza setMaxDelay:delay]; + } + + if (msgId) { + [stanza setId_p:msgId]; + } + + // collapse key as given by the sender + NSString *token = dataMessage[KFIRMessagingSendMessageAppData][kFIRMessagingCollapseKey]; + if ([token length]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager003, + @"FIRMessaging using %@ as collapse key", token); + [stanza setToken:token]; + } + + if (!self.secretToken) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager004, + @"Trying to send data message without a secret token. " + @"Authentication failed."); + [self willSendDataMessageFail:stanza + withMessageId:msgId + error:kFIRMessagingErrorCodeMissingDeviceID]; + return; + } + + if (![to length]) { + [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorMissingTo]; + return; + } + [stanza setTo:to]; + [stanza setCategory:appPackage]; + // required field in the proto this is set by the server + // set it to a sentinel so the runtime doesn't throw an exception + [stanza setFrom:@""]; + + // MCS itself would set the registration ID + // [stanza setRegId:nil]; + + int size = [self addData:dataMessage[KFIRMessagingSendMessageAppData] toStanza:stanza]; + if (size > kMaxAppDataSizeDefault) { + [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorSizeExceeded]; + return; + } + + BOOL useRmq = (ttl != 0) && (msgId != nil); + if (useRmq) { + if (!self.client.isConnected) { + // do nothing assuming rmq save is enabled + } + + NSError *error; + if (![self.rmq2Manager saveRmqMessage:stanza error:&error]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager005, @"%@", error); + [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorSave]; + return; + } + + [self willSendDataMessageSuccess:stanza withMessageId:msgId]; + } + + // if delay > 0 we don't really care about sending the message right now + // so we piggy-back on any other urgent(delay = 0) message that we are sending + if (delay > 0 && [self delayMessage:stanza]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager006, @"Delaying Message %@", + dataMessage); + return; + } + // send delayed messages + [self sendDelayedMessages:[self.delayedMessagesQueue removeDelayedMessages]]; + + BOOL sending = [self tryToSendDataMessageStanza:stanza]; + if (!sending) { + if (useRmq) { + NSString *event __unused = [NSString stringWithFormat:@"Queued message: %@", [stanza id_p]]; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager007, @"%@", event); + } else { + [self willSendDataMessageFail:stanza + withMessageId:msgId + error:kFIRMessagingErrorCodeNetwork]; + return; + } + } +} + +- (void)sendDelayedMessages:(NSArray *)delayedMessages { + for (GtalkDataMessageStanza *message in delayedMessages) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager008, + @"%@ Sending delayed message %@", @"DMM", message); + [message setActualDelay:(int)(FIRMessagingCurrentTimestampInSeconds() - message.sent)]; + [self tryToSendDataMessageStanza:message]; + } +} + +- (void)didSendDataMessageStanza:(GtalkDataMessageStanza *)message { + NSString *msgId = [message id_p] ?: @""; + [self.delegate didSendDataMessageWithID:msgId]; +} + +- (void)addParamWithKey:(NSString *)key + value:(NSString *)val + toStanza:(GtalkDataMessageStanza *)stanza { + if (!key || !val) { + return; + } + GtalkAppData *appData = [[GtalkAppData alloc] init]; + [appData setKey:key]; + [appData setValue:val]; + [[stanza appDataArray] addObject:appData]; +} + +/** + @return The size of the data being added to stanza. + */ +- (int)addData:(NSDictionary *)data toStanza:(GtalkDataMessageStanza *)stanza { + int size = 0; + for (NSString *key in data) { + NSObject *val = data[key]; + if ([val isKindOfClass:[NSString class]]) { + NSString *strVal = (NSString *)val; + [self addParamWithKey:key value:strVal toStanza:stanza]; + size += [key length] + [strVal length]; + } else if ([val isKindOfClass:[NSNumber class]]) { + NSString *strVal = [(NSNumber *)val stringValue]; + [self addParamWithKey:key value:strVal toStanza:stanza]; + size += [key length] + [strVal length]; + } else if ([kFIRMessagingRawDataKey isEqualToString:key] && + [val isKindOfClass:[NSData class]]) { + NSData *rawData = (NSData *)val; + [stanza setRawData:[rawData copy]]; + size += [rawData length]; + } else { + FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager009, @"Ignoring key: %@", + key); + } + } + return size; +} + +/** + * Notify the messenger that send data message completed with success. This is called for + * TTL=0, after the message has been sent, or when message is saved, to unlock the send() + * method. + */ +- (void)willSendDataMessageSuccess:(GtalkDataMessageStanza *)stanza + withMessageId:(NSString *)messageId { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager010, + @"send message success: %@", messageId); + [self.delegate willSendDataMessageWithID:messageId error:nil]; +} + +/** + * We send 'send failures' from server as normal FIRMessaging messages, with a 'message_type' + * extra - same as 'message deleted'. + * + * For TTL=0 or errors that can be detected during send ( too many messages, invalid, etc) + * we throw IOExceptions + */ +- (void)willSendDataMessageFail:(GtalkDataMessageStanza *)stanza + withMessageId:(NSString *)messageId + error:(FIRMessagingInternalErrorCode)errorCode { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager011, + @"Send message fail: %@ error: %lu", messageId, (unsigned long)errorCode); + + NSError *error = [NSError errorWithFCMErrorCode:errorCode]; + if ([self.delegate respondsToSelector:@selector(willSendDataMessageWithID:error:)]) { + [self.delegate willSendDataMessageWithID:messageId error:error]; + } +} + +- (void)resendMessagesWithConnection:(FIRMessagingConnection *)connection { + NSMutableString *rmqIdsResent = [NSMutableString string]; + NSMutableArray *toRemoveRmqIds = [NSMutableArray array]; + FIRMessaging_WEAKIFY(self); + FIRMessaging_WEAKIFY(connection); + FIRMessagingRmqMessageHandler messageHandler = ^(int64_t rmqId, int8_t tag, NSData *data) { + FIRMessaging_STRONGIFY(self); + FIRMessaging_STRONGIFY(connection); + GPBMessage *proto = + [FIRMessagingGetClassForTag((FIRMessagingProtoTag)tag) parseFromData:data error:NULL]; + if ([proto isKindOfClass:GtalkDataMessageStanza.class]) { + GtalkDataMessageStanza *stanza = (GtalkDataMessageStanza *)proto; + + if (![self handleExpirationForDataMessage:stanza]) { + // time expired let's delete from RMQ + [toRemoveRmqIds addObject:stanza.persistentId]; + return; + } + [rmqIdsResent appendString:[NSString stringWithFormat:@"%@,", stanza.id_p]]; + } + + [connection sendProto:proto]; + }; + [self.rmq2Manager scanWithRmqMessageHandler:messageHandler + dataMessageHandler:nil]; + + if ([rmqIdsResent length]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager012, @"Resent: %@", + rmqIdsResent); + } + + if ([toRemoveRmqIds count]) { + [self.rmq2Manager removeRmqMessagesWithRmqIds:toRemoveRmqIds]; + } +} + +/** + * Check the TTL and generate an error if needed. + * + * @return false if the message needs to be deleted + */ +- (BOOL)handleExpirationForDataMessage:(GtalkDataMessageStanza *)message { + if (message.ttl == 0) { + return NO; + } + + int64_t now = FIRMessagingCurrentTimestampInSeconds(); + if (now > message.sent + message.ttl) { + [self willSendDataMessageFail:message + withMessageId:message.id_p + error:kFIRMessagingErrorServiceNotAvailable]; + return NO; + } + return YES; +} + +#pragma mark - Private + +- (int)delayForMessage:(NSMutableDictionary *)message { + int delay = 0; // default + if (message[kFIRMessagingSendDelay]) { + delay = [message[kFIRMessagingSendDelay] intValue]; + [message removeObjectForKey:kFIRMessagingSendDelay]; + if (delay < kMinDelaySeconds) { + delay = 0; + } else if (delay > kMaxDelaySeconds) { + delay = kMaxDelaySeconds; + } + } + return delay; +} + +// return True if successfully delayed else False +- (BOOL)delayMessage:(GtalkDataMessageStanza *)message { + return [self.delayedMessagesQueue queueMessage:message]; +} + +- (BOOL)tryToSendDataMessageStanza:(GtalkDataMessageStanza *)stanza { + if (self.client.isConnectionActive) { + [self.client sendMessage:stanza]; + return YES; + } + + // if we only reconnect for TTL = 0 messages check if we ttl = 0 or + // if we reconnect for all messages try to reconnect + if ((self.upstreamForceReconnect == kUpstreamForceReconnectTTL0 && stanza.ttl == 0) || + self.upstreamForceReconnect == kUpstreamForceReconnectAll) { + BOOL isNetworkAvailable = [[FIRMessaging messaging] isNetworkAvailable]; + if (isNetworkAvailable) { + if (stanza.ttl == 0) { + // Add TTL = 0 messages to be sent on next connect. TTL != 0 messages are + // persisted, and will be sent from the RMQ. + [self.client sendOnConnectOrDrop:stanza]; + } + + [self.client retryConnectionImmediately:YES]; + return YES; + } + } + return NO; +} + +- (NSString *)categoryForUpstreamMessages { + return FIRMessagingAppIdentifier(); +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDefines.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDefines.h new file mode 100644 index 0000000..abf79a5 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDefines.h @@ -0,0 +1,84 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRMessaging_xcodeproj_FIRMessagingDefines_h +#define FIRMessaging_xcodeproj_FIRMessagingDefines_h + +#define _FIRMessaging_VERBOSE_LOGGING 1 + +// Verbose Logging +#if (_FIRMessaging_VERBOSE_LOGGING) +#define FIRMessaging_DEV_VERBOSE_LOG(...) NSLog(__VA_ARGS__) +#else +#define FIRMessaging_DEV_VERBOSE_LOG(...) do { } while (0) +#endif // FIRMessaging_VERBOSE_LOGGING + + +// WEAKIFY & STRONGIFY +// Helper macro. +#define _FIRMessaging_WEAKNAME(VAR) VAR ## _weak_ + +#define FIRMessaging_WEAKIFY(VAR) __weak __typeof__(VAR) _FIRMessaging_WEAKNAME(VAR) = (VAR); + +#define FIRMessaging_STRONGIFY(VAR) \ +_Pragma("clang diagnostic push") \ +_Pragma("clang diagnostic ignored \"-Wshadow\"") \ +__strong __typeof__(VAR) VAR = _FIRMessaging_WEAKNAME(VAR); \ +_Pragma("clang diagnostic pop") + + +// Type Conversions (used for NSInteger etc) +#ifndef _FIRMessaging_L +#define _FIRMessaging_L(v) (long)(v) +#endif + +#ifndef _FIRMessaging_UL +#define _FIRMessaging_UL(v) (unsigned long)(v) +#endif + +#endif + +// Debug Assert +#ifndef _FIRMessagingDevAssert +// we directly invoke the NSAssert handler so we can pass on the varargs +// (NSAssert doesn't have a macro we can use that takes varargs) +#ifdef DEBUG +#define _FIRMessagingDevAssert(condition, ...) \ + do { \ + if (!(condition)) { \ + [[NSAssertionHandler currentHandler] \ + handleFailureInFunction:(NSString *) \ + [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \ + file:(NSString *)[NSString stringWithUTF8String:__FILE__] \ + lineNumber:__LINE__ \ + description:__VA_ARGS__]; \ + } \ + } while(0) +#else // !defined(DEBUG) +#define _FIRMessagingDevAssert(condition, ...) do { } while (0) +#endif // !defined(DEBUG) + +#endif // _FIRMessagingDevAssert + +// Invalidates the initializer from which it's called. +#ifndef FIRMessagingInvalidateInitializer +#define FIRMessagingInvalidateInitializer() \ + do { \ + [self class]; /* Avoid warning of dead store to |self|. */ \ + _FIRMessagingDevAssert(NO, @"Invalid initializer."); \ + return nil; \ + } while (0) +#endif diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.h new file mode 100644 index 0000000..d20ec91 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class GtalkDataMessageStanza; +@class FIRMessagingRmqManager; + +@protocol FIRMessagingRmqScanner; + +typedef void(^FIRMessagingSendDelayedMessagesHandler)(NSArray *messages); + +@interface FIRMessagingDelayedMessageQueue : NSObject + +- (instancetype)initWithRmqScanner:(id)rmqScanner + sendDelayedMessagesHandler:(FIRMessagingSendDelayedMessagesHandler)sendDelayedMessagesHandler; + +- (BOOL)queueMessage:(GtalkDataMessageStanza *)message; + +- (NSArray *)removeDelayedMessages; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.m new file mode 100644 index 0000000..0371c02 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingDelayedMessageQueue.m @@ -0,0 +1,146 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingDelayedMessageQueue.h" + +#import "Protos/GtalkCore.pbobjc.h" + +#import "FIRMessagingDefines.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessagingUtilities.h" + +static const int kMaxQueuedMessageCount = 10; + +@interface FIRMessagingDelayedMessageQueue () + +@property(nonatomic, readonly, weak) id rmqScanner; +@property(nonatomic, readonly, copy) FIRMessagingSendDelayedMessagesHandler sendDelayedMessagesHandler; + +@property(nonatomic, readwrite, assign) int persistedMessageCount; +// the scheduled timeout or -1 if not set +@property(nonatomic, readwrite, assign) int64_t scheduledTimeoutMilliseconds; +// The time of the last scan of the message DB, +// used to avoid retrieving messages more than once. +@property(nonatomic, readwrite, assign) int64_t lastDBScanTimestampSeconds; + +@property(nonatomic, readwrite, strong) NSMutableArray *messages; +@property(nonatomic, readwrite, strong) NSTimer *sendTimer; + +@end + +@implementation FIRMessagingDelayedMessageQueue + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithRmqScanner:(id)rmqScanner + sendDelayedMessagesHandler:(FIRMessagingSendDelayedMessagesHandler)sendDelayedMessagesHandler { + _FIRMessagingDevAssert(sendDelayedMessagesHandler, @"Invalid nil callback for delayed messages"); + self = [super init]; + if (self) { + _rmqScanner = rmqScanner; + _sendDelayedMessagesHandler = sendDelayedMessagesHandler; + _messages = [NSMutableArray arrayWithCapacity:10]; + _scheduledTimeoutMilliseconds = -1; + } + return self; +} + +- (BOOL)queueMessage:(GtalkDataMessageStanza *)message { + if (self.messages.count >= kMaxQueuedMessageCount) { + return NO; + } + if (message.ttl == 0) { + // ttl=0 messages aren't persisted, add it to memory + [self.messages addObject:message]; + } else { + self.persistedMessageCount++; + } + int64_t timeoutMillis = [self calculateTimeoutInMillisWithDelayInSeconds:message.maxDelay]; + if (![self isTimeoutScheduled] || timeoutMillis < self.scheduledTimeoutMilliseconds) { + [self scheduleTimeoutInMillis:timeoutMillis]; + } + return YES; +} + +- (NSArray *)removeDelayedMessages { + [self cancelTimeout]; + if ([self messageCount] == 0) { + return @[]; + } + + NSMutableArray *delayedMessages = [NSMutableArray array]; + // add the ttl=0 messages + if (self.messages.count) { + [delayedMessages addObjectsFromArray:delayedMessages]; + [self.messages removeAllObjects]; + } + + // add persistent messages + if (self.persistedMessageCount > 0) { + FIRMessaging_WEAKIFY(self); + [self.rmqScanner scanWithRmqMessageHandler:nil + dataMessageHandler:^(int64_t rmqId, GtalkDataMessageStanza *stanza) { + FIRMessaging_STRONGIFY(self); + if ([stanza hasMaxDelay] && + [stanza sent] >= self.lastDBScanTimestampSeconds) { + [delayedMessages addObject:stanza]; + } + }]; + self.lastDBScanTimestampSeconds = FIRMessagingCurrentTimestampInSeconds(); + self.persistedMessageCount = 0; + } + return delayedMessages; +} + +- (void)sendMessages { + if (self.sendDelayedMessagesHandler) { + self.sendDelayedMessagesHandler([self removeDelayedMessages]); + } +} + +#pragma mark - Private + +- (NSInteger)messageCount { + return self.messages.count + self.persistedMessageCount; +} + +- (BOOL)isTimeoutScheduled { + return self.scheduledTimeoutMilliseconds > 0; +} + +- (int64_t)calculateTimeoutInMillisWithDelayInSeconds:(int)delay { + return FIRMessagingCurrentTimestampInMilliseconds() + delay * 1000.0; +} + +- (void)scheduleTimeoutInMillis:(int64_t)time { + [self cancelTimeout]; + self.scheduledTimeoutMilliseconds = time; + double delay = (time - FIRMessagingCurrentTimestampInMilliseconds()) / 1000.0; + [self performSelector:@selector(sendMessages) withObject:self afterDelay:delay]; +} + +- (void)cancelTimeout { + if ([self isTimeoutScheduled]) { + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(sendMessages) + object:nil]; + self.scheduledTimeoutMilliseconds = -1; + } +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.h new file mode 100644 index 0000000..223ac9c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.h @@ -0,0 +1,67 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMMessageCode.h" + +// The convenience macros are only defined if they haven't already been defined. +#ifndef FIRMessagingLoggerInfo + +// Convenience macros that log to the shared FIRMessagingLogger instance. These macros +// are how users should typically log to FIRMessagingLogger. +#define FIRMessagingLoggerDebug(code, ...) \ + [FIRMessagingSharedLogger() logFuncDebug:__func__ messageCode:code msg:__VA_ARGS__] +#define FIRMessagingLoggerInfo(code, ...) \ + [FIRMessagingSharedLogger() logFuncInfo:__func__ messageCode:code msg:__VA_ARGS__] +#define FIRMessagingLoggerNotice(code, ...) \ + [FIRMessagingSharedLogger() logFuncNotice:__func__ messageCode:code msg:__VA_ARGS__] +#define FIRMessagingLoggerWarn(code, ...) \ + [FIRMessagingSharedLogger() logFuncWarning:__func__ messageCode:code msg:__VA_ARGS__] +#define FIRMessagingLoggerError(code, ...) \ + [FIRMessagingSharedLogger() logFuncError:__func__ messageCode:code msg:__VA_ARGS__] + +#endif // !defined(FIRMessagingLoggerInfo) + +@interface FIRMessagingLogger : NSObject + +- (void)logFuncDebug:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4); + +- (void)logFuncInfo:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4); + +- (void)logFuncNotice:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4); + +- (void)logFuncWarning:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4); + +- (void)logFuncError:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(3, 4); + +@end + +/** + * Instantiates and/or returns a shared FIRMessagingLogger used exclusively + * for FIRMessaging log messages. + * + * @return the shared FIRMessagingLogger instance + */ +FIRMessagingLogger *FIRMessagingSharedLogger(void); diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.m new file mode 100644 index 0000000..62eb8da --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingLogger.m @@ -0,0 +1,93 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingLogger.h" + +#import + +@implementation FIRMessagingLogger + ++ (instancetype)standardLogger { + return [[FIRMessagingLogger alloc] init]; +} + +#pragma mark - Log Helpers + ++ (NSString *)formatMessageCode:(FIRMessagingMessageCode)messageCode { + return [NSString stringWithFormat:@"I-FCM%06ld", (long)messageCode]; +} + +- (void)logFuncDebug:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... { + va_list args; + va_start(args, fmt); + FIRLogBasic(FIRLoggerLevelDebug, kFIRLoggerMessaging, + [FIRMessagingLogger formatMessageCode:messageCode], fmt, args); + va_end(args); +} + +- (void)logFuncInfo:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... { + va_list args; + va_start(args, fmt); + FIRLogBasic(FIRLoggerLevelInfo, kFIRLoggerMessaging, + [FIRMessagingLogger formatMessageCode:messageCode], fmt, args); + va_end(args); +} + +- (void)logFuncNotice:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... { + va_list args; + va_start(args, fmt); + FIRLogBasic(FIRLoggerLevelNotice, kFIRLoggerMessaging, + [FIRMessagingLogger formatMessageCode:messageCode], fmt, args); + va_end(args); +} + +- (void)logFuncWarning:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... { + va_list args; + va_start(args, fmt); + FIRLogBasic(FIRLoggerLevelWarning, kFIRLoggerMessaging, + [FIRMessagingLogger formatMessageCode:messageCode], fmt, args); + va_end(args); +} + +- (void)logFuncError:(const char *)func + messageCode:(FIRMessagingMessageCode)messageCode + msg:(NSString *)fmt, ... { + va_list args; + va_start(args, fmt); + FIRLogBasic(FIRLoggerLevelError, kFIRLoggerMessaging, + [FIRMessagingLogger formatMessageCode:messageCode], fmt, args); + va_end(args); +} + +@end + +FIRMessagingLogger *FIRMessagingSharedLogger(void) { + static dispatch_once_t onceToken; + static FIRMessagingLogger *logger; + dispatch_once(&onceToken, ^{ + logger = [FIRMessagingLogger standardLogger]; + }); + + return logger; +} diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.h new file mode 100644 index 0000000..1f528ab --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.h @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FIRMessagingPacket : NSObject + ++ (FIRMessagingPacket *)packetWithTag:(int8_t)tag rmqId:(NSString *)rmqId data:(NSData *)data; + +@property(nonatomic, readonly, strong) NSData *data; +@property(nonatomic, readonly, assign) int8_t tag; +// not sent over the wire required for bookkeeping +@property(nonatomic, readonly, assign) NSString *rmqId; + +@end + + +/** + * A queue of the packets(protos) that need to be send over the wire. + */ +@interface FIRMessagingPacketQueue : NSObject + +@property(nonatomic, readonly, assign) NSUInteger count; +@property(nonatomic, readonly, assign) BOOL isEmpty; + +- (void)push:(FIRMessagingPacket *)packet; +- (void)pushHead:(FIRMessagingPacket *)packet; +- (FIRMessagingPacket *)pop; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.m new file mode 100644 index 0000000..2b3410a --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPacketQueue.m @@ -0,0 +1,103 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingPacketQueue.h" + +#import "FIRMessagingDefines.h" + +@interface FIRMessagingPacket () + +@property(nonatomic, readwrite, strong) NSData *data; +@property(nonatomic, readwrite, assign) int8_t tag; +@property(nonatomic, readwrite, assign) NSString *rmqId; + +@end + +@implementation FIRMessagingPacket + ++ (FIRMessagingPacket *)packetWithTag:(int8_t)tag rmqId:(NSString *)rmqId data:(NSData *)data { + return [[self alloc] initWithTag:tag rmqId:rmqId data:data]; +} + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithTag:(int8_t)tag rmqId:(NSString *)rmqId data:(NSData *)data { + self = [super init]; + if (self != nil) { + _data = data; + _tag = tag; + _rmqId = rmqId; + } + return self; +} + +- (NSString *)description { + if ([self.rmqId length]) { + return [NSString stringWithFormat:@", RmqId - %@", + self.tag, _FIRMessaging_UL(self.data.length), self.rmqId]; + } else { + return [NSString stringWithFormat:@"", + self.tag, _FIRMessaging_UL(self.data.length)]; + } +} + +@end + +@interface FIRMessagingPacketQueue () + +@property(nonatomic, readwrite, strong) NSMutableArray *packetsContainer; + +@end + + +@implementation FIRMessagingPacketQueue; + +- (id)init { + self = [super init]; + if (self) { + _packetsContainer = [[NSMutableArray alloc] init]; + } + return self; +} + +- (BOOL)isEmpty { + return self.packetsContainer.count == 0; +} + +- (NSUInteger)count { + return self.packetsContainer.count; +} + +- (void)push:(FIRMessagingPacket *)packet { + [self.packetsContainer addObject:packet]; +} + +- (void)pushHead:(FIRMessagingPacket *)packet { + [self.packetsContainer insertObject:packet atIndex:0]; +} + +- (FIRMessagingPacket *)pop { + if (!self.isEmpty) { + FIRMessagingPacket *packet = self.packetsContainer[0]; + [self.packetsContainer removeObjectAtIndex:0]; + return packet; + } + return nil; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.h new file mode 100644 index 0000000..a8108bf --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.h @@ -0,0 +1,119 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRMessaging.h" +#import "FIRMessagingTopicsCommon.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Represents a single batch of topics, with the same action. + * + * Topic operations which have the same action (subscribe or unsubscribe) can be executed + * simultaneously, as the order of operations do not matter with the same action. The set of + * topics is unique, as it doesn't make sense to apply the same action to the same topic + * repeatedly; the result would be the same as the first time. + */ +@interface FIRMessagingTopicBatch : NSObject + +@property(nonatomic, readonly, assign) FIRMessagingTopicAction action; +@property(nonatomic, readonly, copy) NSMutableSet *topics; + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithAction:(FIRMessagingTopicAction)action NS_DESIGNATED_INITIALIZER; + +@end + +@class FIRMessagingPendingTopicsList; +/** + * This delegate must be supplied to the instance of FIRMessagingPendingTopicsList, via the + * @cdelegate property. It lets the + * pending topics list know whether or not it can begin making requests via + * @c-pendingTopicsListCanRequestTopicUpdates:, and handles the request to actually + * perform the topic operation. The delegate also handles when the pending topics list is updated, + * so that it can be archived or persisted. + * + * @see FIRMessagingPendingTopicsList + */ +@protocol FIRMessagingPendingTopicsListDelegate + +- (void)pendingTopicsList:(FIRMessagingPendingTopicsList *)list + requestedUpdateForTopic:(NSString *)topic + action:(FIRMessagingTopicAction)action + completion:(FIRMessagingTopicOperationCompletion)completion; +- (void)pendingTopicsListDidUpdate:(FIRMessagingPendingTopicsList *)list; +- (BOOL)pendingTopicsListCanRequestTopicUpdates:(FIRMessagingPendingTopicsList *)list; + +@end + +/** + * FIRMessagingPendingTopicsList manages a list of topic subscription updates, batched by the same + * action (subscribe or unsubscribe). The list roughly maintains the order of the topic operations, + * batched together whenever the topic action (subscribe or unsubscribe) changes. + * + * Topics operations are batched by action because it is safe to perform the same topic action + * (subscribe or unsubscribe) on many topics simultaneously. After each batch is successfully + * completed, the next batch operations can begin. + * + * When asked to resume its operations, FIRMessagingPendingTopicsList will begin performing updates + * of its current batch of topics. For example, it may begin subscription operations for topics + * [A, B, C] simultaneously. + * + * When the current batch is completed, the next batch of operations will be started. For example + * the list may begin unsubscribe operations for [D, A, E]. Note that because A is in both batches, + * A will be correctly subscribed in the first batch, then unsubscribed as part of the second batch + * of operations. Without batching, it would be ambiguous whether A's subscription operation or the + * unsubscription operation would be completed first. + * + * An app can subscribe and unsubscribe from many topics, and this class helps persist the pending + * topics and perform the operation safely and correctly. + * + * When a topic fails to subscribe or unsubscribe due to a network error, it is considered a + * recoverable error, and so it remains in the current batch until it is succesfully completed. + * Topic updates are completed when they either (a) succeed, (b) are cancelled, or (c) result in an + * unrecoverable error. Any error outside of `NSURLErrorDomain` is considered an unrecoverable + * error. + * + * In addition to maintaining the list of pending topic updates, FIRMessagingPendingTopicsList also + * can track completion handlers for topic operations. + * + * @discussion Completion handlers for topic updates are not maintained if it was restored from a + * keyed archive. They are only called if the topic operation finished within the same app session. + * + * You must supply an object conforming to FIRMessagingPendingTopicsListDelegate in order for the + * topic operations to execute. + * + * @see FIRMessagingPendingTopicsListDelegate + */ +@interface FIRMessagingPendingTopicsList : NSObject + +@property(nonatomic, weak) NSObject *delegate; + +@property(nonatomic, readonly, strong, nullable) NSDate *archiveDate; +@property(nonatomic, readonly) NSUInteger numberOfBatches; + + +- (instancetype)init NS_DESIGNATED_INITIALIZER; +- (void)addOperationForTopic:(NSString *)topic + withAction:(FIRMessagingTopicAction)action + completion:(nullable FIRMessagingTopicOperationCompletion)completion; +- (void)resumeOperationsIfNeeded; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.m new file mode 100644 index 0000000..b10b552 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPendingTopicsList.m @@ -0,0 +1,265 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingPendingTopicsList.h" + +#import "FIRMessaging_Private.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPubSub.h" + +#import "FIRMessagingDefines.h" + +NSString *const kPendingTopicBatchActionKey = @"action"; +NSString *const kPendingTopicBatchTopicsKey = @"topics"; + +NSString *const kPendingBatchesEncodingKey = @"batches"; +NSString *const kPendingTopicsTimestampEncodingKey = @"ts"; + +#pragma mark - FIRMessagingTopicBatch + +@interface FIRMessagingTopicBatch () + +@property(nonatomic, strong, nonnull) NSMutableDictionary + *> *topicHandlers; + +@end + +@implementation FIRMessagingTopicBatch + +- (instancetype)initWithAction:(FIRMessagingTopicAction)action { + if (self = [super init]) { + _action = action; + _topics = [NSMutableSet set]; + _topicHandlers = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark NSCoding + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeInteger:self.action forKey:kPendingTopicBatchActionKey]; + [aCoder encodeObject:self.topics forKey:kPendingTopicBatchTopicsKey]; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + + // Ensure that our integer -> enum casting is safe + NSInteger actionRawValue = [aDecoder decodeIntegerForKey:kPendingTopicBatchActionKey]; + FIRMessagingTopicAction action = FIRMessagingTopicActionSubscribe; + if (actionRawValue == FIRMessagingTopicActionUnsubscribe) { + action = FIRMessagingTopicActionUnsubscribe; + } + + if (self = [self initWithAction:action]) { + NSSet *topics = [aDecoder decodeObjectForKey:kPendingTopicBatchTopicsKey]; + if ([topics isKindOfClass:[NSSet class]]) { + _topics = [topics mutableCopy]; + } + _topicHandlers = [NSMutableDictionary dictionary]; + } + return self; +} + +@end + +#pragma mark - FIRMessagingPendingTopicsList + +@interface FIRMessagingPendingTopicsList () + +@property(nonatomic, readwrite, strong) NSDate *archiveDate; +@property(nonatomic, strong) NSMutableArray *topicBatches; + +@property(nonatomic, strong) FIRMessagingTopicBatch *currentBatch; +@property(nonatomic, strong) NSMutableSet *topicsInFlight; + +@end + +@implementation FIRMessagingPendingTopicsList + +- (instancetype)init { + if (self = [super init]) { + _topicBatches = [NSMutableArray array]; + _topicsInFlight = [NSMutableSet set]; + } + return self; +} + ++ (void)pruneTopicBatches:(NSMutableArray *)topicBatches { + // For now, just remove empty batches. In the future we can use this to make the subscriptions + // more efficient, by actually pruning topic actions that cancel each other out, for example. + for (NSInteger i = topicBatches.count-1; i >= 0; i--) { + FIRMessagingTopicBatch *batch = topicBatches[i]; + if (batch.topics.count == 0) { + [topicBatches removeObjectAtIndex:i]; + } + } +} + +#pragma mark NSCoding + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:[NSDate date] forKey:kPendingTopicsTimestampEncodingKey]; + [aCoder encodeObject:self.topicBatches forKey:kPendingBatchesEncodingKey]; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + + if (self = [self init]) { + _archiveDate = [aDecoder decodeObjectForKey:kPendingTopicsTimestampEncodingKey]; + NSArray *archivedBatches = [aDecoder decodeObjectForKey:kPendingBatchesEncodingKey]; + if (archivedBatches) { + _topicBatches = [archivedBatches mutableCopy]; + [FIRMessagingPendingTopicsList pruneTopicBatches:_topicBatches]; + } + _topicsInFlight = [NSMutableSet set]; + } + return self; +} + +#pragma mark Getters + +- (NSUInteger)numberOfBatches { + return self.topicBatches.count; +} + +#pragma mark Adding/Removing topics + +- (void)addOperationForTopic:(NSString *)topic + withAction:(FIRMessagingTopicAction)action + completion:(nullable FIRMessagingTopicOperationCompletion)completion { + + FIRMessagingTopicBatch *lastBatch = nil; + @synchronized (self) { + lastBatch = self.topicBatches.lastObject; + if (!lastBatch || lastBatch.action != action) { + // There either was no last batch, or our last batch's action was not the same, so we have to + // create a new batch + lastBatch = [[FIRMessagingTopicBatch alloc] initWithAction:action]; + [self.topicBatches addObject:lastBatch]; + } + BOOL topicExistedBefore = ([lastBatch.topics member:topic] != nil); + if (!topicExistedBefore) { + [lastBatch.topics addObject:topic]; + [self.delegate pendingTopicsListDidUpdate:self]; + } + // Add the completion handler to the batch + if (completion) { + NSMutableArray *handlers = lastBatch.topicHandlers[topic]; + if (!handlers) { + handlers = [[NSMutableArray alloc] init]; + } + [handlers addObject:completion]; + lastBatch.topicHandlers[topic] = handlers; + } + if (!self.currentBatch) { + self.currentBatch = lastBatch; + } + // This may have been the first topic added, or was added to an ongoing batch + if (self.currentBatch == lastBatch && !topicExistedBefore) { + // Add this topic to our ongoing operations + FIRMessaging_WEAKIFY(self); + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ + FIRMessaging_STRONGIFY(self); + [self resumeOperationsIfNeeded]; + }); + } + } +} + +- (void)resumeOperationsIfNeeded { + @synchronized (self) { + // If current batch is not set, set it now + if (!self.currentBatch) { + self.currentBatch = self.topicBatches.firstObject; + } + if (self.currentBatch.topics.count == 0) { + return; + } + if (!self.delegate) { + FIRMessagingLoggerError(kFIRMessagingMessageCodePendingTopicsList000, + @"Attempted to update pending topics without a delegate"); + return; + } + if (![self.delegate pendingTopicsListCanRequestTopicUpdates:self]) { + return; + } + for (NSString *topic in self.currentBatch.topics) { + if ([self.topicsInFlight member:topic]) { + // This topic is already active, so skip + continue; + } + [self beginUpdateForCurrentBatchTopic:topic]; + } + } +} + +- (BOOL)subscriptionErrorIsRecoverable:(NSError *)error { + return [error.domain isEqualToString:NSURLErrorDomain]; +} + +- (void)beginUpdateForCurrentBatchTopic:(NSString *)topic { + + @synchronized (self) { + [self.topicsInFlight addObject:topic]; + } + FIRMessaging_WEAKIFY(self); + [self.delegate + pendingTopicsList:self + requestedUpdateForTopic:topic + action:self.currentBatch.action + completion:^(NSError *error) { + dispatch_async( + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ + FIRMessaging_STRONGIFY(self); + @synchronized(self) { + [self.topicsInFlight removeObject:topic]; + + BOOL recoverableError = [self subscriptionErrorIsRecoverable:error]; + if (!error || !recoverableError) { + // Notify our handlers and remove the topic from our batch + NSMutableArray *handlers = self.currentBatch.topicHandlers[topic]; + if (handlers.count) { + dispatch_async(dispatch_get_main_queue(), ^{ + for (FIRMessagingTopicOperationCompletion handler in handlers) { + handler(error); + } + [handlers removeAllObjects]; + }); + } + [self.currentBatch.topics removeObject:topic]; + [self.currentBatch.topicHandlers removeObjectForKey:topic]; + if (self.currentBatch.topics.count == 0) { + // All topic updates successfully finished in this batch, move on + // to the next batch + [self.topicBatches removeObject:self.currentBatch]; + self.currentBatch = nil; + } + [self.delegate pendingTopicsListDidUpdate:self]; + FIRMessaging_WEAKIFY(self); + dispatch_async( + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), + ^{ + FIRMessaging_STRONGIFY(self); + [self resumeOperationsIfNeeded]; + }); + } + } + }); + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.h new file mode 100644 index 0000000..5a48e99 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.h @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface FIRMessagingPersistentSyncMessage : NSObject + +@property(nonatomic, readonly, strong) NSString *rmqID; +@property(nonatomic, readwrite, assign) BOOL apnsReceived; +@property(nonatomic, readwrite, assign) BOOL mcsReceived; +@property(nonatomic, readonly, assign) int64_t expirationTime; + +- (instancetype)initWithRMQID:(NSString *)rmqID expirationTime:(int64_t)expirationTime; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.m new file mode 100644 index 0000000..bf7d05b --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPersistentSyncMessage.m @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingPersistentSyncMessage.h" + +#import "FIRMessagingDefines.h" + +@interface FIRMessagingPersistentSyncMessage () + +@property(nonatomic, readwrite, strong) NSString *rmqID; +@property(nonatomic, readwrite, assign) int64_t expirationTime; + +@end + +@implementation FIRMessagingPersistentSyncMessage + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithRMQID:(NSString *)rmqID expirationTime:(int64_t)expirationTime { + self = [super init]; + if (self) { + _rmqID = [rmqID copy]; + _expirationTime = expirationTime; + } + return self; +} + +- (NSString *)description { + NSString *classDescription = NSStringFromClass([self class]); + NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.expirationTime]; + return [NSString stringWithFormat:@"%@: (rmqID: %@, apns: %d, mcs: %d, expiry: %@", + classDescription, self.rmqID, self.mcsReceived, self.apnsReceived, date]; +} + +- (NSString *)debugDescription { + return [self description]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.h new file mode 100644 index 0000000..2c2fbe6 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.h @@ -0,0 +1,171 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRMessagingClient; +@class FIRMessagingPubSubCache; + +/** + * FIRMessagingPubSub provides a publish-subscribe model for sending FIRMessaging topic messages. + * + * An app can subscribe to different topics defined by the + * developer. The app server can then send messages to the subscribed devices + * without having to maintain topic-subscribers mapping. Topics do not + * need to be explicitly created before subscribing or publishing—they + * are automatically created when publishing or subscribing. + * + * Messages published to the topic will be received as regular FIRMessaging messages + * with `"from"` set to `"/topics/myTopic"`. + * + * Only topic names that match the pattern `"/topics/[a-zA-Z0-9-_.~%]{1,900}"` + * are allowed for subscribing and publishing. + */ +@interface FIRMessagingPubSub : NSObject + +@property(nonatomic, readonly, strong) FIRMessagingPubSubCache *cache; +@property(nonatomic, readonly, strong) FIRMessagingClient *client; + +/** + * Initializes an instance of FIRMessagingPubSub. + * + * @return An instance of FIRMessagingPubSub. + */ +- (instancetype)initWithClient:(FIRMessagingClient *)client NS_DESIGNATED_INITIALIZER; + +/** + * Subscribes an app instance to a topic, enabling it to receive messages + * sent to that topic. + * + * This is an asynchronous call. If subscription fails, FIRMessaging + * invokes the completion callback with the appropriate error. + * + * @see FIRMessagingPubSub unsubscribeWithToken:topic:handler: + * + * @param token The registration token as received from the InstanceID + * library for a given `authorizedEntity` and "gcm" scope. + * @param topic The topic to subscribe to. Should be of the form + * `"/topics/"`. + * @param options Unused parameter, please pass nil or empty dictionary. + * @param handler The callback handler invoked when the subscribe call + * ends. In case of success, a nil error is returned. Otherwise, + * an appropriate error object is returned. + * @discussion This method is thread-safe. However, it is not guaranteed to + * return on the main thread. + */ +- (void)subscribeWithToken:(NSString *)token + topic:(NSString *)topic + options:(nullable NSDictionary *)options + handler:(FIRMessagingTopicOperationCompletion)handler; + +/** + * Unsubscribes an app instance from a topic, stopping it from receiving + * any further messages sent to that topic. + * + * This is an asynchronous call. If the attempt to unsubscribe fails, + * we invoke the `completion` callback passed in with an appropriate error. + * + * @param token The token used to subscribe to this topic. + * @param topic The topic to unsubscribe from. Should be of the form + * `"/topics/"`. + * @param options Unused parameter, please pass nil or empty dictionary. + * @param handler The handler that is invoked once the unsubscribe call ends. + * In case of success, nil error is returned. Otherwise, an + * appropriate error object is returned. + * @discussion This method is thread-safe. However, it is not guaranteed to + * return on the main thread. + */ +- (void)unsubscribeWithToken:(NSString *)token + topic:(NSString *)topic + options:(nullable NSDictionary *)options + handler:(FIRMessagingTopicOperationCompletion)handler; + +/** + * Asynchronously subscribe to the topic. Adds to the pending list of topic operations. + * Retry in case of failures. This makes a repeated attempt to subscribe to the topic + * as compared to the `subscribe` method above which tries once. + * + * @param topic The topic name to subscribe to. Should be of the form `"/topics/"`. + * @param handler The handler that is invoked once the unsubscribe call ends. + * In case of success, nil error is returned. Otherwise, an + * appropriate error object is returned. + */ +- (void)subscribeToTopic:(NSString *)topic + handler:(nullable FIRMessagingTopicOperationCompletion)handler; + +/** + * Asynchronously unsubscribe from the topic. Adds to the pending list of topic operations. + * Retry in case of failures. This makes a repeated attempt to unsubscribe from the topic + * as compared to the `unsubscribe` method above which tries once. + * + * @param topic The topic name to unsubscribe from. Should be of the form `"/topics/"`. + * @param handler The handler that is invoked once the unsubscribe call ends. + * In case of success, nil error is returned. Otherwise, an + * appropriate error object is returned. + */ +- (void)unsubscribeFromTopic:(NSString *)topic + handler:(nullable FIRMessagingTopicOperationCompletion)handler; + +/** + * Schedule subscriptions sync. + * + * @param immediately YES if the sync should be scheduled immediately else NO if we can delay + * the sync. + */ +- (void)scheduleSync:(BOOL)immediately; + +/** + * Adds the "/topics/" prefix to the topic. + * + * @param topic The topic to add the prefix to. + * + * @return The new topic name with the "/topics/" prefix added. + */ ++ (NSString *)addPrefixToTopic:(NSString *)topic; + +/** + * Removes the "/topics/" prefix from the topic. + * + * @param topic The topic to remove the prefix from. + * + * @return The new topic name with the "/topics/" prefix removed. + */ + ++ (NSString *)removePrefixFromTopic:(NSString *)topic; + +/** + * Check if the topic name has "/topics/" prefix. + * + * @param topic The topic name to verify. + * + * @return YES if the topic name has "/topics/" prefix else NO. + */ ++ (BOOL)hasTopicsPrefix:(NSString *)topic; + +/** + * Check if it's a valid topic name. This includes "/topics/" prefix in the topic name. + * + * @param topic The topic name to verify. + * + * @return YES if the topic name satisfies the regex "/topics/[a-zA-Z0-9-_.~%]{1,900}". + */ ++ (BOOL)isValidTopicWithPrefix:(NSString *)topic; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.m new file mode 100644 index 0000000..3f954e8 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSub.m @@ -0,0 +1,280 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingPubSub.h" + +#import "FIRMessaging.h" +#import "FIRMessagingClient.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPendingTopicsList.h" +#import "FIRMessagingUtilities.h" +#import "FIRMessaging_Private.h" +#import "NSDictionary+FIRMessaging.h" +#import "NSError+FIRMessaging.h" + +static NSString *const kPendingSubscriptionsListKey = + @"com.firebase.messaging.pending-subscriptions"; + +@interface FIRMessagingPubSub () + +@property(nonatomic, readwrite, strong) FIRMessagingPendingTopicsList *pendingTopicUpdates; +@property(nonatomic, readwrite, strong) FIRMessagingClient *client; + +@end + +@implementation FIRMessagingPubSub + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); + // Need this to disable an Xcode warning. + return [self initWithClient:nil]; +} + +- (instancetype)initWithClient:(FIRMessagingClient *)client { + self = [super init]; + if (self) { + _client = client; + [self restorePendingTopicsList]; + } + return self; +} + +- (void)subscribeWithToken:(NSString *)token + topic:(NSString *)topic + options:(NSDictionary *)options + handler:(FIRMessagingTopicOperationCompletion)handler { + _FIRMessagingDevAssert([token length], @"FIRMessaging error no token specified"); + _FIRMessagingDevAssert([topic length], @"FIRMessaging error Invalid empty topic specified"); + if (!self.client) { + handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubFIRMessagingNotSetup]); + return; + } + + token = [token copy]; + topic = [topic copy]; + + if (![options count]) { + options = @{}; + } + + if (![[self class] isValidTopicWithPrefix:topic]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub000, + @"Invalid FIRMessaging Pubsub topic %@", topic); + handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubInvalidTopic]); + return; + } + + if (![self verifyPubSubOptions:options]) { + // we do not want to quit even if options have some invalid values. + FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub001, + @"Invalid options passed to FIRMessagingPubSub with non-string keys or " + "values."); + } + // copy the dictionary would trim non-string keys or values if any. + options = [options fcm_trimNonStringValues]; + + [self.client updateSubscriptionWithToken:token + topic:topic + options:options + shouldDelete:NO + handler:^void(NSError *error) { + handler(error); + }]; +} + +- (void)unsubscribeWithToken:(NSString *)token + topic:(NSString *)topic + options:(NSDictionary *)options + handler:(FIRMessagingTopicOperationCompletion)handler { + _FIRMessagingDevAssert([token length], @"FIRMessaging error no token specified"); + _FIRMessagingDevAssert([topic length], @"FIRMessaging error Invalid empty topic specified"); + + if (!self.client) { + handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubFIRMessagingNotSetup]); + return; + } + + token = [token copy]; + topic = [topic copy]; + if (![options count]) { + options = @{}; + } + + if (![[self class] isValidTopicWithPrefix:topic]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodePubSub002, + @"Invalid FIRMessaging Pubsub topic %@", topic); + handler([NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubInvalidTopic]); + return; + } + if (![self verifyPubSubOptions:options]) { + // we do not want to quit even if options have some invalid values. + FIRMessagingLoggerError( + kFIRMessagingMessageCodePubSub003, + @"Invalid options passed to FIRMessagingPubSub with non-string keys or values."); + } + // copy the dictionary would trim non-string keys or values if any. + options = [options fcm_trimNonStringValues]; + + [self.client updateSubscriptionWithToken:token + topic:topic + options:options + shouldDelete:YES + handler:^void(NSError *error) { + handler(error); + }]; +} + +- (void)subscribeToTopic:(NSString *)topic + handler:(nullable FIRMessagingTopicOperationCompletion)handler { + [self.pendingTopicUpdates addOperationForTopic:topic + withAction:FIRMessagingTopicActionSubscribe + completion:handler]; +} + +- (void)unsubscribeFromTopic:(NSString *)topic + handler:(nullable FIRMessagingTopicOperationCompletion)handler { + [self.pendingTopicUpdates addOperationForTopic:topic + withAction:FIRMessagingTopicActionUnsubscribe + completion:handler]; +} + +- (void)scheduleSync:(BOOL)immediately { + NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken]; + if (fcmToken.length) { + [self.pendingTopicUpdates resumeOperationsIfNeeded]; + } +} + +#pragma mark - FIRMessagingPendingTopicsListDelegate + +- (void)pendingTopicsList:(FIRMessagingPendingTopicsList *)list + requestedUpdateForTopic:(NSString *)topic + action:(FIRMessagingTopicAction)action + completion:(FIRMessagingTopicOperationCompletion)completion { + + NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken]; + if (action == FIRMessagingTopicActionSubscribe) { + [self subscribeWithToken:fcmToken topic:topic options:nil handler:completion]; + } else { + [self unsubscribeWithToken:fcmToken topic:topic options:nil handler:completion]; + } +} + +- (void)pendingTopicsListDidUpdate:(FIRMessagingPendingTopicsList *)list { + [self archivePendingTopicsList:list]; +} + +- (BOOL)pendingTopicsListCanRequestTopicUpdates:(FIRMessagingPendingTopicsList *)list { + NSString *fcmToken = [[FIRMessaging messaging] defaultFcmToken]; + return (fcmToken.length > 0); +} + +#pragma mark - Storing Pending Topics + +- (void)archivePendingTopicsList:(FIRMessagingPendingTopicsList *)topicsList { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSData *pendingData = [NSKeyedArchiver archivedDataWithRootObject:topicsList]; + [defaults setObject:pendingData forKey:kPendingSubscriptionsListKey]; + [defaults synchronize]; +} + +- (void)restorePendingTopicsList { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSData *pendingData = [defaults objectForKey:kPendingSubscriptionsListKey]; + FIRMessagingPendingTopicsList *subscriptions; + @try { + if (pendingData) { + subscriptions = [NSKeyedUnarchiver unarchiveObjectWithData:pendingData]; + } + } @catch (NSException *exception) { + // Nothing we can do, just continue as if we don't have pending subscriptions + } @finally { + if (subscriptions) { + self.pendingTopicUpdates = subscriptions; + } else { + self.pendingTopicUpdates = [[FIRMessagingPendingTopicsList alloc] init]; + } + self.pendingTopicUpdates.delegate = self; + } +} + +#pragma mark - Private Helpers + +- (BOOL)verifyPubSubOptions:(NSDictionary *)options { + return ![options fcm_hasNonStringKeysOrValues]; +} + +#pragma mark - Topic Name Helpers + +static NSString *const kTopicsPrefix = @"/topics/"; +static NSString *const kTopicRegexPattern = @"/topics/([a-zA-Z0-9-_.~%]+)"; + ++ (NSString *)addPrefixToTopic:(NSString *)topic { + if (![self hasTopicsPrefix:topic]) { + return [NSString stringWithFormat:@"%@%@", kTopicsPrefix, topic]; + } else { + return [topic copy]; + } +} + ++ (NSString *)removePrefixFromTopic:(NSString *)topic { + if ([self hasTopicsPrefix:topic]) { + return [topic substringFromIndex:kTopicsPrefix.length]; + } else { + return [topic copy]; + } +} + ++ (BOOL)hasTopicsPrefix:(NSString *)topic { + return [topic hasPrefix:kTopicsPrefix]; +} + +/** + * Returns a regular expression for matching a topic sender. + * + * @return The topic matching regular expression + */ ++ (NSRegularExpression *)topicRegex { + // Since this is a static regex pattern, we only only need to declare it once. + static NSRegularExpression *topicRegex; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSError *error; + topicRegex = + [NSRegularExpression regularExpressionWithPattern:kTopicRegexPattern + options:NSRegularExpressionAnchorsMatchLines + error:&error]; + }); + return topicRegex; +} + +/** + * Gets the class describing occurences of topic names and sender IDs in the sender. + * + * @param expression The topic expression used to generate a pubsub topic + * + * @return Representation of captured subexpressions in topic regular expression + */ ++ (BOOL)isValidTopicWithPrefix:(NSString *)topic { + NSRange topicRange = NSMakeRange(0, topic.length); + NSRange regexMatchRange = [[self topicRegex] rangeOfFirstMatchInString:topic + options:NSMatchingAnchored + range:topicRange]; + return NSEqualRanges(topicRange, regexMatchRange); +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.h new file mode 100644 index 0000000..b51813f --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingTopicOperation.h" + +@class FIRMessagingCheckinService; + +@interface FIRMessagingPubSubRegistrar : NSObject + +/** + * Designated Initializer. + * + * @param checkinService The checkin service used to register with Checkin + * server. + * + * @return A new FIRMessagingPubSubRegistrar instance used to subscribe/unsubscribe. + */ +- (instancetype)initWithCheckinService:(FIRMessagingCheckinService *)checkinService; + +/** + * Stops all the subscription requests going on in parallel. This would + * invalidate all the handlers associated with the subscription requests. + */ +- (void)stopAllSubscriptionRequests; + +/** + * Update subscription status for a given topic with FIRMessaging's backend. + * + * @param topic The topic to subscribe to. + * @param token The registration token to be used. + * @param options The options to be passed in during subscription request. + * @param shouldDelete NO if the subscription is being added else YES if being + * removed. + * @param handler The handler invoked once the update subscription request + * finishes. + */ +- (void)updateSubscriptionToTopic:(NSString *)topic + withToken:(NSString *)token + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.m new file mode 100644 index 0000000..6268302 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingPubSubRegistrar.m @@ -0,0 +1,78 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingPubSubRegistrar.h" + +#import "FIRMessagingCheckinService.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingPubSubRegistrar.h" +#import "FIRMessagingTopicsCommon.h" +#import "NSError+FIRMessaging.h" + +@interface FIRMessagingPubSubRegistrar () + +@property(nonatomic, readwrite, strong) FIRMessagingCheckinService *checkinService; + +@property(nonatomic, readonly, strong) NSOperationQueue *topicOperations; +// Common errors, instantiated, to avoid generating multiple copies +@property(nonatomic, readwrite, strong) NSError *operationInProgressError; + +@end + +@implementation FIRMessagingPubSubRegistrar + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithCheckinService:(FIRMessagingCheckinService *)checkinService { + self = [super init]; + if (self) { + _checkinService = checkinService; + _topicOperations = [[NSOperationQueue alloc] init]; + // Do 10 topic operations at a time; it's enough to keep the TCP connection to the host alive, + // saving hundreds of milliseconds on each request (compared to a serial queue). + _topicOperations.maxConcurrentOperationCount = 10; + } + return self; +} + +- (void)stopAllSubscriptionRequests { + [self.topicOperations cancelAllOperations]; +} + +- (void)updateSubscriptionToTopic:(NSString *)topic + withToken:(NSString *)token + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler { + + FIRMessagingTopicAction action = FIRMessagingTopicActionSubscribe; + if (shouldDelete) { + action = FIRMessagingTopicActionUnsubscribe; + } + FIRMessagingTopicOperation *operation = + [[FIRMessagingTopicOperation alloc] initWithTopic:topic + action:action + token:token + options:options + checkinService:self.checkinService + completion:handler]; + [self.topicOperations addOperation:operation]; + +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.h new file mode 100644 index 0000000..e312420 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.h @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingDataMessageManager.h" +#import "FIRMessaging.h" + +@class FIRMessagingReceiver; +@protocol FIRMessagingReceiverDelegate + +- (void)receiver:(nonnull FIRMessagingReceiver *)receiver + receivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage; + +@end + +@interface FIRMessagingReceiver : NSObject + +@property(nonatomic, weak, nullable) id delegate; +/// Whether to use direct channel for direct channel message callback handler in all iOS versions. +@property(nonatomic, assign) BOOL useDirectChannel; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.m new file mode 100644 index 0000000..ac8a683 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingReceiver.m @@ -0,0 +1,182 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingReceiver.h" + +#import + +#import + +#import "FIRMessaging.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingUtilities.h" +#import "FIRMessaging_Private.h" + +static NSString *const kUpstreamMessageIDUserInfoKey = @"messageID"; +static NSString *const kUpstreamErrorUserInfoKey = @"error"; +/// "Should use Messaging delegate" key stored in NSUserDefaults +NSString *const kFIRMessagingUserDefaultsKeyUseMessagingDelegate = + @"com.firebase.messaging.useMessagingDelegate"; +/// "Should use Messaging Delegate" key stored in Info.plist +NSString *const kFIRMessagingPlistUseMessagingDelegate = + @"FirebaseMessagingUseMessagingDelegateForDirectChannel"; + +static int downstreamMessageID = 0; + +@implementation FIRMessagingReceiver + +#pragma mark - FIRMessagingDataMessageManager protocol + +- (void)didReceiveMessage:(NSDictionary *)message withIdentifier:(nullable NSString *)messageID { + if (![messageID length]) { + messageID = [[self class] nextMessageID]; + } + + NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue]; + if (majorOSVersion >= 10 || self.useDirectChannel) { + // iOS 10 and above or use direct channel is enabled. + [self scheduleIos10NotificationForMessage:message withIdentifier:messageID]; + } else { + // Post notification directly to AppDelegate handlers. This is valid pre-iOS 10. + [self scheduleNotificationForMessage:message]; + } +} + +- (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error { + NSNotification *notification; + if (error) { + NSDictionary *userInfo = @{ + kUpstreamMessageIDUserInfoKey : [messageID copy], + kUpstreamErrorUserInfoKey : error + }; + notification = [NSNotification notificationWithName:FIRMessagingSendErrorNotification + object:nil + userInfo:userInfo]; + [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP]; + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver000, + @"Fail to send upstream message: %@ error: %@", messageID, error); + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver001, @"Will send upstream message: %@", + messageID); + } +} + +- (void)didSendDataMessageWithID:(NSString *)messageID { + // invoke the callbacks asynchronously + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver002, @"Did send upstream message: %@", + messageID); + NSNotification * notification = + [NSNotification notificationWithName:FIRMessagingSendSuccessNotification + object:nil + userInfo:@{ kUpstreamMessageIDUserInfoKey : [messageID copy] }]; + + [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP]; +} + +- (void)didDeleteMessagesOnServer { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver003, + @"Will send deleted messages notification"); + NSNotification * notification = + [NSNotification notificationWithName:FIRMessagingMessagesDeletedNotification + object:nil]; + + [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP]; +} + +#pragma mark - Private Helpers +// As the new UserNotifications framework in iOS 10 doesn't support constructor/mutation for +// UNNotification object, FCM can't inject the message to the app with UserNotifications framework. +// Define our own protocol, which means app developers need to implement two interfaces to receive +// display notifications and data messages respectively for devices running iOS 10 or above. Devices +// running iOS 9 or below are not affected. +- (void)scheduleIos10NotificationForMessage:(NSDictionary *)message + withIdentifier:(NSString *)messageID { + FIRMessagingRemoteMessage *wrappedMessage = [[FIRMessagingRemoteMessage alloc] init]; + // TODO: wrap title, body, badge and other fields + wrappedMessage.appData = [message copy]; + wrappedMessage.messageID = messageID; + [self.delegate receiver:self receivedRemoteMessage:wrappedMessage]; +} + +- (void)scheduleNotificationForMessage:(NSDictionary *)message { + SEL newNotificationSelector = + @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:); + SEL oldNotificationSelector = @selector(application:didReceiveRemoteNotification:); + + dispatch_async(dispatch_get_main_queue(), ^{ + UIApplication *application = FIRMessagingUIApplication(); + if (!application) { + return; + } + id appDelegate = [application delegate]; + if ([appDelegate respondsToSelector:newNotificationSelector]) { + // Try the new remote notification callback + [appDelegate application:application + didReceiveRemoteNotification:message + fetchCompletionHandler:^(UIBackgroundFetchResult result) { + }]; + + } else if ([appDelegate respondsToSelector:oldNotificationSelector]) { + // Try the old remote notification callback +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [appDelegate application:application didReceiveRemoteNotification:message]; +#pragma clang diagnostic pop + } else { + FIRMessagingLoggerError(kFIRMessagingMessageCodeReceiver005, + @"None of the remote notification callbacks implemented by " + @"UIApplicationDelegate"); + } + }); +} + ++ (NSString *)nextMessageID { + @synchronized (self) { + ++downstreamMessageID; + return [NSString stringWithFormat:@"gcm-%d", downstreamMessageID]; + } +} + +- (BOOL)useDirectChannel { + // Check storage + NSUserDefaults *messagingDefaults = [NSUserDefaults standardUserDefaults]; + id shouldUseMessagingDelegate = + [messagingDefaults objectForKey:kFIRMessagingUserDefaultsKeyUseMessagingDelegate]; + if (shouldUseMessagingDelegate) { + return [shouldUseMessagingDelegate boolValue]; + } + + // Check Info.plist + shouldUseMessagingDelegate = + [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistUseMessagingDelegate]; + if (shouldUseMessagingDelegate) { + return [shouldUseMessagingDelegate boolValue]; + } + // If none of above exists, we go back to default behavior which is NO. + return NO; +} + +- (void)setUseDirectChannel:(BOOL)useDirectChannel { + NSUserDefaults *messagingDefaults = [NSUserDefaults standardUserDefaults]; + BOOL shouldUseMessagingDelegate = [self useDirectChannel]; + if (useDirectChannel != shouldUseMessagingDelegate) { + [messagingDefaults setBool:useDirectChannel + forKey:kFIRMessagingUserDefaultsKeyUseMessagingDelegate]; + [messagingDefaults synchronize]; + } +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.h new file mode 100644 index 0000000..065479c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.h @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" +#import "FIRMessagingCheckinService.h" + +@class FIRMessagingCheckinStore; +@class FIRMessagingPubSubRegistrar; + +/** + * Handle the registration process for the client. Fetch checkin information from the Checkin + * service if not cached on the device and then try to register the client with FIRMessaging backend. + */ +@interface FIRMessagingRegistrar : NSObject + +@property(nonatomic, readonly, strong) FIRMessagingPubSubRegistrar *pubsubRegistrar; +@property(nonatomic, readonly, strong) NSString *deviceAuthID; +@property(nonatomic, readonly, strong) NSString *secretToken; + +/** + * Initialize a FIRMessaging Registrar. + * + * @return A FIRMessaging Registrar object. + */ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +#pragma mark - Checkin + +/** + * Try to load checkin info from the disk if not currently loaded into memory. + * + * @return YES if successfully loaded valid checkin info to memory else NO. + */ +- (BOOL)tryToLoadValidCheckinInfo; + +#pragma mark - Subscribe/Unsubscribe + +/** + * Update the subscription for a given topic for the client. + * + * @param topic The topic for which the subscription should be updated. + * @param token The registration token to be used by the client. + * @param options The extra options if any being passed as part of + * subscription request. + * @param shouldDelete YES if we want to delete an existing subscription else NO + * if we want to create a new subscription. + * @param handler The handler to invoke once the subscription request is + * complete. + */ +- (void)updateSubscriptionToTopic:(NSString *)topic + withToken:(NSString *)token + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler; + +/** + * Cancel all subscription requests as well as any requests to checkin. Note if + * there are subscription requests waiting on checkin to complete those requests + * would be marked as stale and be NO-OP's if they happen in the future. + * + * Also note this is a one time operation, you should only call this if you want + * to immediately stop all requests and deallocate the registrar. After calling + * this once you would no longer be able to use this registrar object. + */ +- (void)cancelAllRequests; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.m new file mode 100644 index 0000000..47a22ec --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRegistrar.m @@ -0,0 +1,108 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingRegistrar.h" + +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPubSubRegistrar.h" +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" + +@interface FIRMessagingRegistrar () + +@property(nonatomic, readwrite, assign) BOOL stopAllSubscriptions; + +@property(nonatomic, readwrite, strong) FIRMessagingCheckinService *checkinService; +@property(nonatomic, readwrite, strong) FIRMessagingPubSubRegistrar *pubsubRegistrar; + +@end + +@implementation FIRMessagingRegistrar + +- (NSString *)deviceAuthID { + return self.checkinService.deviceAuthID; +} + +- (NSString *)secretToken { + return self.checkinService.secretToken; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _checkinService = [[FIRMessagingCheckinService alloc] init]; + // TODO(chliangGoogle): Merge pubsubRegistrar with Registrar as it is hard to track how many + // checkinService instances by separating classes too often. + _pubsubRegistrar = [[FIRMessagingPubSubRegistrar alloc] initWithCheckinService:_checkinService]; + } + return self; +} + +#pragma mark - Checkin + +- (BOOL)tryToLoadValidCheckinInfo { + [self.checkinService tryToLoadPrefetchedCheckinPreferences]; + return [self.checkinService hasValidCheckinInfo]; +} + +#pragma mark - Subscribe/Unsubscribe + +- (void)updateSubscriptionToTopic:(NSString *)topic + withToken:(NSString *)token + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + handler:(FIRMessagingTopicOperationCompletion)handler { + _FIRMessagingDevAssert(handler, @"Invalid nil handler"); + + if ([self tryToLoadValidCheckinInfo]) { + [self doUpdateSubscriptionForTopic:topic + token:token + options:options + shouldDelete:shouldDelete + completion:handler]; + + } else { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRegistrar000, + @"Device check in error, no auth credentials found"); + NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeMissingDeviceID]; + handler(error); + } +} + +- (void)cancelAllRequests { + self.stopAllSubscriptions = YES; + [self.pubsubRegistrar stopAllSubscriptionRequests]; +} + +#pragma mark - Private + +- (void)doUpdateSubscriptionForTopic:(NSString *)topic + token:(NSString *)token + options:(NSDictionary *)options + shouldDelete:(BOOL)shouldDelete + completion:(FIRMessagingTopicOperationCompletion)completion { + _FIRMessagingDevAssert([self.checkinService hasValidCheckinInfo], + @"No valid checkin info found before subscribe"); + + [self.pubsubRegistrar updateSubscriptionToTopic:topic + withToken:token + options:options + shouldDelete:shouldDelete + handler:completion]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.h new file mode 100644 index 0000000..59c3c15 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + * Swizzle remote-notification callbacks to invoke FIRMessaging methods + * before calling original implementations. + */ +@interface FIRMessagingRemoteNotificationsProxy : NSObject + +/** + * Checks the `FirebaseAppDelegateProxyEnabled` key in the App's Info.plist. If the key is + * missing or incorrectly formatted, returns `YES`. + * + * @return YES if the Application Delegate and User Notification Center methods can be swizzled. + * Otherwise, returns NO. + */ ++ (BOOL)canSwizzleMethods; + +/** + * Swizzles Application Delegate's remote-notification callbacks and User Notification Center + * delegate callback, and invokes the original selectors once done. + */ ++ (void)swizzleMethods; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.m new file mode 100644 index 0000000..7cea178 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.m @@ -0,0 +1,723 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingRemoteNotificationsProxy.h" + +#import +#import + +#import "FIRMessagingConstants.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingUtilities.h" +#import "FIRMessaging_Private.h" + +static const BOOL kDefaultAutoRegisterEnabledValue = YES; +static void * UserNotificationObserverContext = &UserNotificationObserverContext; + +static NSString *kUserNotificationWillPresentSelectorString = + @"userNotificationCenter:willPresentNotification:withCompletionHandler:"; +static NSString *kUserNotificationDidReceiveResponseSelectorString = + @"userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:"; +static NSString *kReceiveDataMessageSelectorString = @"messaging:didReceiveMessage:"; + +@interface FIRMessagingRemoteNotificationsProxy () + +@property(strong, nonatomic) NSMutableDictionary *originalAppDelegateImps; +@property(strong, nonatomic) NSMutableDictionary *swizzledSelectorsByClass; + +@property(nonatomic) BOOL didSwizzleMethods; +@property(nonatomic) BOOL didSwizzleAppDelegateMethods; + +@property(nonatomic) BOOL hasSwizzledUserNotificationDelegate; +@property(nonatomic) BOOL isObservingUserNotificationDelegateChanges; + +@property(strong, nonatomic) id userNotificationCenter; +@property(strong, nonatomic) id currentUserNotificationCenterDelegate; + +@end + +@implementation FIRMessagingRemoteNotificationsProxy + ++ (BOOL)canSwizzleMethods { + id canSwizzleValue = + [[NSBundle mainBundle] + objectForInfoDictionaryKey: kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey]; + if (canSwizzleValue && [canSwizzleValue isKindOfClass:[NSNumber class]]) { + NSNumber *canSwizzleNumberValue = (NSNumber *)canSwizzleValue; + return canSwizzleNumberValue.boolValue; + } else { + return kDefaultAutoRegisterEnabledValue; + } +} + ++ (void)swizzleMethods { + [[FIRMessagingRemoteNotificationsProxy sharedProxy] swizzleMethodsIfPossible]; +} + ++ (instancetype)sharedProxy { + static FIRMessagingRemoteNotificationsProxy *proxy; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + proxy = [[FIRMessagingRemoteNotificationsProxy alloc] init]; + }); + return proxy; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _originalAppDelegateImps = [[NSMutableDictionary alloc] init]; + _swizzledSelectorsByClass = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)dealloc { + [self unswizzleAllMethods]; + self.swizzledSelectorsByClass = nil; + [self.originalAppDelegateImps removeAllObjects]; + self.originalAppDelegateImps = nil; + [self removeUserNotificationCenterDelegateObserver]; +} + +- (void)swizzleMethodsIfPossible { + // Already swizzled. + if (self.didSwizzleMethods) { + return; + } + + UIApplication *application = FIRMessagingUIApplication(); + if (!application) { + return; + } + NSObject *appDelegate = [application delegate]; + [self swizzleAppDelegateMethods:appDelegate]; + + // Add KVO listener on [UNUserNotificationCenter currentNotificationCenter]'s delegate property + Class notificationCenterClass = NSClassFromString(@"UNUserNotificationCenter"); + if (notificationCenterClass) { + // We are linked against iOS 10 SDK or above + id notificationCenter = getNamedPropertyFromObject(notificationCenterClass, + @"currentNotificationCenter", + notificationCenterClass); + if (notificationCenter) { + [self listenForDelegateChangesInUserNotificationCenter:notificationCenter]; + } + } + + self.didSwizzleMethods = YES; +} + +- (void)unswizzleAllMethods { + for (NSString *className in self.swizzledSelectorsByClass) { + Class klass = NSClassFromString(className); + NSArray *selectorStrings = self.swizzledSelectorsByClass[className]; + for (NSString *selectorString in selectorStrings) { + SEL selector = NSSelectorFromString(selectorString); + [self unswizzleSelector:selector inClass:klass]; + } + } + [self.swizzledSelectorsByClass removeAllObjects]; +} + +- (void)swizzleAppDelegateMethods:(id)appDelegate { + if (![appDelegate conformsToProtocol:@protocol(UIApplicationDelegate)]) { + return; + } + Class appDelegateClass = [appDelegate class]; + + BOOL didSwizzleAppDelegate = NO; + // Message receiving handler for iOS 9, 8, 7 devices (both display notification and data message). + SEL remoteNotificationSelector = + @selector(application:didReceiveRemoteNotification:); + + SEL remoteNotificationWithFetchHandlerSelector = + @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:); + + // For recording when APNS tokens are registered (or fail to register) + SEL registerForAPNSFailSelector = + @selector(application:didFailToRegisterForRemoteNotificationsWithError:); + + SEL registerForAPNSSuccessSelector = + @selector(application:didRegisterForRemoteNotificationsWithDeviceToken:); + + + // Receive Remote Notifications. + BOOL selectorWithFetchHandlerImplemented = NO; + if ([appDelegate respondsToSelector:remoteNotificationWithFetchHandlerSelector]) { + selectorWithFetchHandlerImplemented = YES; + [self swizzleSelector:remoteNotificationWithFetchHandlerSelector + inClass:appDelegateClass + withImplementation:(IMP)FCM_swizzle_appDidReceiveRemoteNotificationWithHandler + inProtocol:@protocol(UIApplicationDelegate)]; + didSwizzleAppDelegate = YES; + } + + if ([appDelegate respondsToSelector:remoteNotificationSelector] || + !selectorWithFetchHandlerImplemented) { + [self swizzleSelector:remoteNotificationSelector + inClass:appDelegateClass + withImplementation:(IMP)FCM_swizzle_appDidReceiveRemoteNotification + inProtocol:@protocol(UIApplicationDelegate)]; + didSwizzleAppDelegate = YES; + } + + // For data message from MCS. + SEL receiveDataMessageSelector = NSSelectorFromString(kReceiveDataMessageSelectorString); + if ([appDelegate respondsToSelector:receiveDataMessageSelector]) { + [self swizzleSelector:receiveDataMessageSelector + inClass:appDelegateClass + withImplementation:(IMP)FCM_swizzle_messagingDidReceiveMessage + inProtocol:@protocol(UIApplicationDelegate)]; + didSwizzleAppDelegate = YES; + } + + // Receive APNS token + [self swizzleSelector:registerForAPNSSuccessSelector + inClass:appDelegateClass + withImplementation:(IMP)FCM_swizzle_appDidRegisterForRemoteNotifications + inProtocol:@protocol(UIApplicationDelegate)]; + + [self swizzleSelector:registerForAPNSFailSelector + inClass:appDelegateClass + withImplementation:(IMP)FCM_swizzle_appDidFailToRegisterForRemoteNotifications + inProtocol:@protocol(UIApplicationDelegate)]; + + self.didSwizzleAppDelegateMethods = didSwizzleAppDelegate; +} + +- (void)listenForDelegateChangesInUserNotificationCenter:(id)notificationCenter { + Class notificationCenterClass = NSClassFromString(@"UNUserNotificationCenter"); + if (![notificationCenter isKindOfClass:notificationCenterClass]) { + return; + } + id delegate = getNamedPropertyFromObject(notificationCenter, @"delegate", nil); + Protocol *delegateProtocol = NSProtocolFromString(@"UNUserNotificationCenterDelegate"); + if ([delegate conformsToProtocol:delegateProtocol]) { + // Swizzle this object now, if available + [self swizzleUserNotificationCenterDelegate:delegate]; + } + // Add KVO observer for "delegate" keyPath for future changes + [self addDelegateObserverToUserNotificationCenter:notificationCenter]; +} + +#pragma mark - UNNotificationCenter Swizzling + +- (void)swizzleUserNotificationCenterDelegate:(id _Nonnull)delegate { + if (self.currentUserNotificationCenterDelegate == delegate) { + // Via pointer-check, compare if we have already swizzled this item. + return; + } + Protocol *userNotificationCenterProtocol = + NSProtocolFromString(@"UNUserNotificationCenterDelegate"); + if ([delegate conformsToProtocol:userNotificationCenterProtocol]) { + SEL willPresentNotificationSelector = + NSSelectorFromString(kUserNotificationWillPresentSelectorString); + // Swizzle the optional method + // "userNotificationCenter:willPresentNotification:withCompletionHandler:", if it is + // implemented. Do not swizzle otherwise, as an implementation *will* be created, which will + // fool iOS into thinking that this method is implemented, and therefore not send notifications + // to the fallback method in the app delegate + // "application:didReceiveRemoteNotification:fetchCompletionHandler:". + if ([delegate respondsToSelector:willPresentNotificationSelector]) { + [self swizzleSelector:willPresentNotificationSelector + inClass:[delegate class] + withImplementation:(IMP)FCM_swizzle_willPresentNotificationWithHandler + inProtocol:userNotificationCenterProtocol]; + } + SEL didReceiveNotificationResponseSelector = + NSSelectorFromString(kUserNotificationDidReceiveResponseSelectorString); + if ([delegate respondsToSelector:didReceiveNotificationResponseSelector]) { + [self swizzleSelector:didReceiveNotificationResponseSelector + inClass:[delegate class] + withImplementation:(IMP)FCM_swizzle_didReceiveNotificationResponseWithHandler + inProtocol:userNotificationCenterProtocol]; + } + self.currentUserNotificationCenterDelegate = delegate; + self.hasSwizzledUserNotificationDelegate = YES; + } +} + +- (void)unswizzleUserNotificationCenterDelegate:(id _Nonnull)delegate { + if (self.currentUserNotificationCenterDelegate != delegate) { + // We aren't swizzling this delegate, so don't do anything. + return; + } + SEL willPresentNotificationSelector = + NSSelectorFromString(kUserNotificationWillPresentSelectorString); + // Call unswizzle methods, even if the method was not implemented (it will fail gracefully). + [self unswizzleSelector:willPresentNotificationSelector + inClass:[self.currentUserNotificationCenterDelegate class]]; + SEL didReceiveNotificationResponseSelector = + NSSelectorFromString(kUserNotificationDidReceiveResponseSelectorString); + [self unswizzleSelector:didReceiveNotificationResponseSelector + inClass:[self.currentUserNotificationCenterDelegate class]]; + self.currentUserNotificationCenterDelegate = nil; + self.hasSwizzledUserNotificationDelegate = NO; +} + +#pragma mark - KVO for UNUserNotificationCenter + +- (void)addDelegateObserverToUserNotificationCenter:(id)userNotificationCenter { + [self removeUserNotificationCenterDelegateObserver]; + @try { + [userNotificationCenter addObserver:self + forKeyPath:NSStringFromSelector(@selector(delegate)) + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + context:UserNotificationObserverContext]; + self.userNotificationCenter = userNotificationCenter; + self.isObservingUserNotificationDelegateChanges = YES; + } @catch (NSException *exception) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRemoteNotificationsProxy000, + @"Encountered exception trying to add a KVO observer for " + @"UNUserNotificationCenter's 'delegate' property: %@", + exception); + } @finally { + + } +} + +- (void)removeUserNotificationCenterDelegateObserver { + if (!self.userNotificationCenter) { + return; + } + @try { + [self.userNotificationCenter removeObserver:self + forKeyPath:NSStringFromSelector(@selector(delegate)) + context:UserNotificationObserverContext]; + self.userNotificationCenter = nil; + self.isObservingUserNotificationDelegateChanges = NO; + } @catch (NSException *exception) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRemoteNotificationsProxy001, + @"Encountered exception trying to remove a KVO observer for " + @"UNUserNotificationCenter's 'delegate' property: %@", + exception); + } @finally { + + } +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context { + if (context == UserNotificationObserverContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(delegate))]) { + id oldDelegate = change[NSKeyValueChangeOldKey]; + if (oldDelegate && oldDelegate != [NSNull null]) { + [self unswizzleUserNotificationCenterDelegate:oldDelegate]; + } + id newDelegate = change[NSKeyValueChangeNewKey]; + if (newDelegate && newDelegate != [NSNull null]) { + [self swizzleUserNotificationCenterDelegate:newDelegate]; + } + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +#pragma mark - NSProxy methods + +- (void)saveOriginalImplementation:(IMP)imp forSelector:(SEL)selector { + if (imp && selector) { + NSValue *IMPValue = [NSValue valueWithPointer:imp]; + NSString *selectorString = NSStringFromSelector(selector); + self.originalAppDelegateImps[selectorString] = IMPValue; + } +} + +- (IMP)originalImplementationForSelector:(SEL)selector { + NSString *selectorString = NSStringFromSelector(selector); + NSValue *implementation_value = self.originalAppDelegateImps[selectorString]; + if (!implementation_value) { + return nil; + } + + IMP imp; + [implementation_value getValue:&imp]; + return imp; +} + +- (void)trackSwizzledSelector:(SEL)selector ofClass:(Class)klass { + NSString *className = NSStringFromClass(klass); + NSString *selectorString = NSStringFromSelector(selector); + NSArray *selectors = self.swizzledSelectorsByClass[selectorString]; + if (selectors) { + selectors = [selectors arrayByAddingObject:selectorString]; + } else { + selectors = @[selectorString]; + } + self.swizzledSelectorsByClass[className] = selectors; +} + +- (void)removeImplementationForSelector:(SEL)selector { + NSString *selectorString = NSStringFromSelector(selector); + [self.originalAppDelegateImps removeObjectForKey:selectorString]; +} + +- (void)swizzleSelector:(SEL)originalSelector + inClass:(Class)klass + withImplementation:(IMP)swizzledImplementation + inProtocol:(Protocol *)protocol { + Method originalMethod = class_getInstanceMethod(klass, originalSelector); + + if (originalMethod) { + // This class implements this method, so replace the original implementation + // with our new implementation and save the old implementation. + + IMP __original_method_implementation = + method_setImplementation(originalMethod, swizzledImplementation); + + IMP __nonexistant_method_implementation = [self nonExistantMethodImplementationForClass:klass]; + + if (__original_method_implementation && + __original_method_implementation != __nonexistant_method_implementation && + __original_method_implementation != swizzledImplementation) { + [self saveOriginalImplementation:__original_method_implementation + forSelector:originalSelector]; + } + } else { + // The class doesn't have this method, so add our swizzled implementation as the + // original implementation of the original method. + struct objc_method_description method_description = + protocol_getMethodDescription(protocol, originalSelector, NO, YES); + + BOOL methodAdded = class_addMethod(klass, + originalSelector, + swizzledImplementation, + method_description.types); + if (!methodAdded) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRemoteNotificationsProxyMethodNotAdded, + @"Could not add method for %@ to class %@", + NSStringFromSelector(originalSelector), + NSStringFromClass(klass)); + } + } + [self trackSwizzledSelector:originalSelector ofClass:klass]; +} + +- (void)unswizzleSelector:(SEL)selector inClass:(Class)klass { + + Method swizzledMethod = class_getInstanceMethod(klass, selector); + if (!swizzledMethod) { + // This class doesn't seem to have this selector as an instance method? Bail out. + return; + } + + IMP original_imp = [self originalImplementationForSelector:selector]; + if (original_imp) { + // Restore the original implementation as the current implementation + method_setImplementation(swizzledMethod, original_imp); + [self removeImplementationForSelector:selector]; + } else { + // This class originally did not have an implementation for this selector. + + // We can't actually remove methods in Objective C 2.0, but we could set + // its method to something non-existent. This should give us the same + // behavior as if the method was not implemented. + // See: http://stackoverflow.com/a/8276527/9849 + + IMP nonExistantMethodImplementation = [self nonExistantMethodImplementationForClass:klass]; + method_setImplementation(swizzledMethod, nonExistantMethodImplementation); + } +} + +#pragma mark - Reflection Helpers + +// This is useful to generate from a stable, "known missing" selector, as the IMP can be compared +// in case we are setting an implementation for a class that was previously "unswizzled" into a +// non-existant implementation. +- (IMP)nonExistantMethodImplementationForClass:(Class)klass { + SEL nonExistantSelector = NSSelectorFromString(@"aNonExistantMethod"); + IMP nonExistantMethodImplementation = class_getMethodImplementation(klass, nonExistantSelector); + return nonExistantMethodImplementation; +} + +// A safe, non-leaky way return a property object by its name +id getNamedPropertyFromObject(id object, NSString *propertyName, Class klass) { + SEL selector = NSSelectorFromString(propertyName); + if (![object respondsToSelector:selector]) { + return nil; + } + if (!klass) { + klass = [NSObject class]; + } + // Suppress clang warning about leaks in performSelector + // The alternative way to perform this is to invoke + // the method as a block (see http://stackoverflow.com/a/20058585), + // but this approach sometimes returns incomplete objects. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id property = [object performSelector:selector]; +#pragma clang diagnostic pop + if (![property isKindOfClass:klass]) { + return nil; + } + return property; +} + +#pragma mark - Swizzled Methods + +void FCM_swizzle_appDidReceiveRemoteNotification(id self, + SEL _cmd, + UIApplication *app, + NSDictionary *userInfo) { + [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; + + IMP original_imp = + [[FIRMessagingRemoteNotificationsProxy sharedProxy] originalImplementationForSelector:_cmd]; + if (original_imp) { + ((void (*)(id, SEL, UIApplication *, NSDictionary *))original_imp)(self, + _cmd, + app, + userInfo); + } +} + +void FCM_swizzle_appDidReceiveRemoteNotificationWithHandler( + id self, SEL _cmd, UIApplication *app, NSDictionary *userInfo, + void (^handler)(UIBackgroundFetchResult)) { + + [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; + + IMP original_imp = + [[FIRMessagingRemoteNotificationsProxy sharedProxy] originalImplementationForSelector:_cmd]; + if (original_imp) { + ((void (*)(id, SEL, UIApplication *, NSDictionary *, + void (^)(UIBackgroundFetchResult)))original_imp)( + self, _cmd, app, userInfo, handler); + } +} + +/** + * Swizzle the notification handler for iOS 10+ devices. + * Signature of original handler is as below: + * - (void)userNotificationCenter:(UNUserNotificationCenter *)center + * willPresentNotification:(UNNotification *)notification + * withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler + * In order to make FCM SDK compile and compatible with iOS SDKs before iOS 10, hide the + * parameter types from the swizzling implementation. + */ +void FCM_swizzle_willPresentNotificationWithHandler( + id self, SEL _cmd, id center, id notification, void (^handler)(NSUInteger)) { + + FIRMessagingRemoteNotificationsProxy *proxy = [FIRMessagingRemoteNotificationsProxy sharedProxy]; + IMP original_imp = [proxy originalImplementationForSelector:_cmd]; + + void (^callOriginalMethodIfAvailable)(void) = ^{ + if (original_imp) { + ((void (*)(id, SEL, id, id, void (^)(NSUInteger)))original_imp)( + self, _cmd, center, notification, handler); + } + return; + }; + + Class notificationCenterClass = NSClassFromString(@"UNUserNotificationCenter"); + Class notificationClass = NSClassFromString(@"UNNotification"); + if (!notificationCenterClass || !notificationClass) { + // Can't find UserNotifications framework. Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + } + + if (!center || ![center isKindOfClass:[notificationCenterClass class]]) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + if (!notification || ![notification isKindOfClass:[notificationClass class]]) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + if (!handler) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + // Attempt to access the user info + id notificationUserInfo = userInfoFromNotification(notification); + + if (!notificationUserInfo) { + // Could not access notification.request.content.userInfo. + callOriginalMethodIfAvailable(); + return; + } + + [[FIRMessaging messaging] appDidReceiveMessage:notificationUserInfo]; + // Execute the original implementation. + callOriginalMethodIfAvailable(); +} + +/** + * Swizzle the notification handler for iOS 10+ devices. + * Signature of original handler is as below: + * - (void)userNotificationCenter:(UNUserNotificationCenter *)center + * didReceiveNotificationResponse:(UNNotificationResponse *)response + * withCompletionHandler:(void (^)(void))completionHandler + * In order to make FCM SDK compile and compatible with iOS SDKs before iOS 10, hide the + * parameter types from the swizzling implementation. + */ +void FCM_swizzle_didReceiveNotificationResponseWithHandler( + id self, SEL _cmd, id center, id response, void (^handler)(void)) { + + FIRMessagingRemoteNotificationsProxy *proxy = [FIRMessagingRemoteNotificationsProxy sharedProxy]; + IMP original_imp = [proxy originalImplementationForSelector:_cmd]; + + void (^callOriginalMethodIfAvailable)(void) = ^{ + if (original_imp) { + ((void (*)(id, SEL, id, id, void (^)(void)))original_imp)( + self, _cmd, center, response, handler); + } + return; + }; + + Class notificationCenterClass = NSClassFromString(@"UNUserNotificationCenter"); + Class responseClass = NSClassFromString(@"UNNotificationResponse"); + if (!center || ![center isKindOfClass:[notificationCenterClass class]]) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + if (!response || ![response isKindOfClass:[responseClass class]]) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + if (!handler) { + // Invalid parameter type from the original method. + // Do not swizzle, just execute the original method. + callOriginalMethodIfAvailable(); + return; + } + + // Try to access the response.notification property + SEL notificationSelector = NSSelectorFromString(@"notification"); + if (![response respondsToSelector:notificationSelector]) { + // Cannot access the .notification property. + callOriginalMethodIfAvailable(); + return; + } + id notificationClass = NSClassFromString(@"UNNotification"); + id notification = getNamedPropertyFromObject(response, @"notification", notificationClass); + + // With a notification object, use the common code to reach deep into notification + // (notification.request.content.userInfo) + id notificationUserInfo = userInfoFromNotification(notification); + if (!notificationUserInfo) { + // Could not access notification.request.content.userInfo. + callOriginalMethodIfAvailable(); + return; + } + + [[FIRMessaging messaging] appDidReceiveMessage:notificationUserInfo]; + // Execute the original implementation. + callOriginalMethodIfAvailable(); +} + +id userInfoFromNotification(id notification) { + + // Select the userInfo field from UNNotification.request.content.userInfo. + SEL requestSelector = NSSelectorFromString(@"request"); + if (![notification respondsToSelector:requestSelector]) { + // Cannot access the request property. + return nil; + } + Class requestClass = NSClassFromString(@"UNNotificationRequest"); + id notificationRequest = getNamedPropertyFromObject(notification, @"request", requestClass); + + SEL notificationContentSelector = NSSelectorFromString(@"content"); + if (!notificationRequest + || ![notificationRequest respondsToSelector:notificationContentSelector]) { + // Cannot access the content property. + return nil; + } + Class contentClass = NSClassFromString(@"UNNotificationContent"); + id notificationContent = getNamedPropertyFromObject(notificationRequest, + @"content", + contentClass); + + SEL notificationUserInfoSelector = NSSelectorFromString(@"userInfo"); + if (!notificationContent + || ![notificationContent respondsToSelector:notificationUserInfoSelector]) { + // Cannot access the userInfo property. + return nil; + } + id notificationUserInfo = getNamedPropertyFromObject(notificationContent, + @"userInfo", + [NSDictionary class]); + + if (!notificationUserInfo) { + // This is not the expected notification handler. + return nil; + } + + return notificationUserInfo; +} + +void FCM_swizzle_messagingDidReceiveMessage(id self, SEL _cmd, FIRMessaging *message, + FIRMessagingRemoteMessage *remoteMessage) { + [[FIRMessaging messaging] appDidReceiveMessage:remoteMessage.appData]; + + IMP original_imp = + [[FIRMessagingRemoteNotificationsProxy sharedProxy] originalImplementationForSelector:_cmd]; + if (original_imp) { + ((void (*)(id, SEL, FIRMessaging *, FIRMessagingRemoteMessage *))original_imp)( + self, _cmd, message, remoteMessage); + } +} + +void FCM_swizzle_appDidFailToRegisterForRemoteNotifications(id self, + SEL _cmd, + UIApplication *app, + NSError *error) { + // Log the fact that we failed to register for remote notifications + FIRMessagingLoggerError(kFIRMessagingMessageCodeRemoteNotificationsProxyAPNSFailed, + @"Error in " + @"application:didFailToRegisterForRemoteNotificationsWithError: %@", + error.localizedDescription); + IMP original_imp = + [[FIRMessagingRemoteNotificationsProxy sharedProxy] originalImplementationForSelector:_cmd]; + if (original_imp) { + ((void (*)(id, SEL, UIApplication *, NSError *))original_imp)(self, _cmd, app, error); + } +} + +void FCM_swizzle_appDidRegisterForRemoteNotifications(id self, + SEL _cmd, + UIApplication *app, + NSData *deviceToken) { + // Pass the APNSToken along to FIRMessaging (and auto-detect the token type) + [FIRMessaging messaging].APNSToken = deviceToken; + + IMP original_imp = + [[FIRMessagingRemoteNotificationsProxy sharedProxy] originalImplementationForSelector:_cmd]; + if (original_imp) { + ((void (*)(id, SEL, UIApplication *, NSData *))original_imp)(self, _cmd, app, deviceToken); + } +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.h new file mode 100644 index 0000000..09f1d44 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.h @@ -0,0 +1,201 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRMessagingPersistentSyncMessage; + +// table data handlers +/** + * Handle message stored in the outgoing RMQ messages table. + * + * @param rmqId The rmqID of the message. + * @param tag The message tag. + * @param data The data stored in the message. + */ +typedef void(^FCMOutgoingRmqMessagesTableHandler)(int64_t rmqId, int8_t tag, NSData *data); + +/// Outgoing messages RMQ table +extern NSString *const kTableOutgoingRmqMessages; +/// Server to device RMQ table +extern NSString *const kTableS2DRmqIds; + +@interface FIRMessagingRmq2PersistentStore : NSObject + +/** + * Initialize and open the RMQ database on the client. + * + * @param databaseName The name for RMQ database. + * + * @return A store used to persist messages on the client. + */ +- (instancetype)initWithDatabaseName:(NSString *)databaseName; + +/** + * Save outgoing message in RMQ. + * + * @param rmqId The rmqID for the message. + * @param tag The tag of the message proto. + * @param data The data being sent in the message. + * @param error The error if any while saving the message to the persistent store. + * + * @return YES if the message was successfully saved to the persistent store else NO. + */ +- (BOOL)saveMessageWithRmqId:(int64_t)rmqId + tag:(int8_t)tag + data:(NSData *)data + error:(NSError **)error; + +/** + * Add unacked server to device message with a given rmqID to the persistent store. + * + * @param rmqId The rmqID of the message that was not acked by the cient. + * + * @return YES if the save was successful else NO. + */ +- (BOOL)saveUnackedS2dMessageWithRmqId:(NSString *)rmqId; + +/** + * Update the last RMQ ID that was sent by the client. + * + * @param rmqID The latest rmqID sent by the device. + * + * @return YES if the last rmqID was successfully saved else NO. + */ +- (BOOL)updateLastOutgoingRmqId:(int64_t)rmqID; + +#pragma mark - Query + +/** + * Query the highest rmqID saved in the Outgoing messages table. + * + * @return The highest rmqID amongst all the messages in the Outgoing RMQ table. If no message + * was ever persisted return 0. + */ +- (int64_t)queryHighestRmqId; + +/** + * The last rmqID that was saved on the client. + * + * @return The last rmqID that was saved. If no rmqID was ever persisted return 0. + */ +- (int64_t)queryLastRmqId; + +/** + * Get a list of all unacked server to device messages stored on the client. + * + * @return List of all unacked s2d messages in the persistent store. + */ +- (NSArray *)unackedS2dRmqIds; + +/** + * Iterate over all outgoing messages in the RMQ table. + * + * @param handler The handler invoked with each message in the outgoing RMQ table. + */ +- (void)scanOutgoingRmqMessagesWithHandler:(FCMOutgoingRmqMessagesTableHandler)handler; + +#pragma mark - Delete + +/** + * Delete messages with given rmqID's from a table. + * + * @param tableName The table name from which to delete the rmq messages. + * @param rmqIds The rmqID's of the messages to be deleted. + * + * @return The number of messages that were successfully deleted. + */ +- (int)deleteMessagesFromTable:(NSString *)tableName + withRmqIds:(NSArray *)rmqIds; + +/** + * Remove database from the device. + * + * @param dbName The database name to be deleted. + */ ++ (void)removeDatabase:(NSString *)dbName; + +#pragma mark - Sync Messages + +/** + * Save sync message to persistent store to check for duplicates. + * + * @param rmqID The rmqID of the message to save. + * @param expirationTime The expiration time of the message to save. + * @param apnsReceived YES if the message was received via APNS else NO. + * @param mcsReceived YES if the message was received via MCS else NO. + * @param error The error if any while saving the message to store. + * + * @return YES if the message was saved successfully else NO. + */ +- (BOOL)saveSyncMessageWithRmqID:(NSString *)rmqID + expirationTime:(int64_t)expirationTime + apnsReceived:(BOOL)apnsReceived + mcsReceived:(BOOL)mcsReceived + error:(NSError **)error; + +/** + * Update sync message received via APNS. + * + * @param rmqID The rmqID of the sync message. + * @param error The error if any while updating the sync message in persistence. + * + * @return YES if the update was successful else NO. + */ +- (BOOL)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID + error:(NSError **)error; + +/** + * Update sync message received via MCS. + * + * @param rmqID The rmqID of the sync message. + * @param error The error if any while updating the sync message in persistence. + * + * @return YES if the update was successful else NO. + */ +- (BOOL)updateSyncMessageViaMCSWithRmqID:(NSString *)rmqID + error:(NSError **)error; + +/** + * Query sync message table for a given rmqID. + * + * @param rmqID The rmqID to search for in SYNC_RMQ. + * + * @return The sync message that was persisted with `rmqID`. If no such message was persisted + * return nil. + */ +- (FIRMessagingPersistentSyncMessage *)querySyncMessageWithRmqID:(NSString *)rmqID; + +/** + * Delete sync message with rmqID. + * + * @param rmqID The rmqID of the message to delete. + * + * @return YES if a sync message with rmqID was found and deleted successfully else NO. + */ +- (BOOL)deleteSyncMessageWithRmqID:(NSString *)rmqID; + +/** + * Delete the expired sync messages from persisten store. Also deletes messages that have been + * delivered both via APNS and MCS. + * + * @param error The error if any while deleting the messages. + * + * @return The total number of messages that were deleted from the persistent store. + */ +- (int)deleteExpiredOrFinishedSyncMessages:(NSError **)error; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.m new file mode 100644 index 0000000..dc6e6c9 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmq2PersistentStore.m @@ -0,0 +1,807 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingRmq2PersistentStore.h" + +#import + +#import "FIRMessagingConstants.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPersistentSyncMessage.h" +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" +#import "Protos/GtalkCore.pbobjc.h" + +#ifndef _FIRMessagingRmqLogAndExit +#define _FIRMessagingRmqLogAndExit(stmt, return_value) \ +do { \ +[self logErrorAndFinalizeStatement:stmt]; \ +return return_value; \ +} while(0) +#endif + +typedef enum : NSUInteger { + FIRMessagingRmqDirectoryUnknown, + FIRMessagingRmqDirectoryDocuments, + FIRMessagingRmqDirectoryApplicationSupport, +} FIRMessagingRmqDirectory; + +static NSString *const kFCMRmqStoreTag = @"FIRMessagingRmqStore:"; + +// table names +NSString *const kTableOutgoingRmqMessages = @"outgoingRmqMessages"; +NSString *const kTableLastRmqId = @"lastrmqid"; +NSString *const kOldTableS2DRmqIds = @"s2dRmqIds"; +NSString *const kTableS2DRmqIds = @"s2dRmqIds_1"; + +// Used to prevent de-duping of sync messages received both via APNS and MCS. +NSString *const kTableSyncMessages = @"incomingSyncMessages"; + +static NSString *const kTablePrefix = @""; + +// create tables +static NSString *const kCreateTableOutgoingRmqMessages = + @"create TABLE IF NOT EXISTS %@%@ " + @"(_id INTEGER PRIMARY KEY, " + @"rmq_id INTEGER, " + @"type INTEGER, " + @"ts INTEGER, " + @"data BLOB)"; + +static NSString *const kCreateTableLastRmqId = + @"create TABLE IF NOT EXISTS %@%@ " + @"(_id INTEGER PRIMARY KEY, " + @"rmq_id INTEGER)"; + +static NSString *const kCreateTableS2DRmqIds = + @"create TABLE IF NOT EXISTS %@%@ " + @"(_id INTEGER PRIMARY KEY, " + @"rmq_id TEXT)"; + +static NSString *const kCreateTableSyncMessages = + @"create TABLE IF NOT EXISTS %@%@ " + @"(_id INTEGER PRIMARY KEY, " + @"rmq_id TEXT, " + @"expiration_ts INTEGER, " + @"apns_recv INTEGER, " + @"mcs_recv INTEGER)"; + +static NSString *const kDropTableCommand = + @"drop TABLE if exists %@%@"; + +// table infos +static NSString *const kRmqIdColumn = @"rmq_id"; +static NSString *const kDataColumn = @"data"; +static NSString *const kProtobufTagColumn = @"type"; +static NSString *const kIdColumn = @"_id"; + +static NSString *const kOutgoingRmqMessagesColumns = @"rmq_id, type, data"; + +// Sync message columns +static NSString *const kSyncMessagesColumns = @"rmq_id, expiration_ts, apns_recv, mcs_recv"; +// Message time expiration in seconds since 1970 +static NSString *const kSyncMessageExpirationTimestampColumn = @"expiration_ts"; +static NSString *const kSyncMessageAPNSReceivedColumn = @"apns_recv"; +static NSString *const kSyncMessageMCSReceivedColumn = @"mcs_recv"; + +// table data handlers +typedef void(^FCMOutgoingRmqMessagesTableHandler)(int64_t rmqId, int8_t tag, NSData *data); + +// Utility to create an NSString from a sqlite3 result code +NSString * _Nonnull FIRMessagingStringFromSQLiteResult(int result) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + const char *errorStr = sqlite3_errstr(result); +#pragma pop + NSString *errorString = [NSString stringWithFormat:@"%d - %s", result, errorStr]; + return errorString; +} + +@interface FIRMessagingRmq2PersistentStore () { + sqlite3 *_database; +} + +@property(nonatomic, readwrite, strong) NSString *databaseName; +@property(nonatomic, readwrite, assign) FIRMessagingRmqDirectory currentDirectory; + +@end + +@implementation FIRMessagingRmq2PersistentStore + +- (instancetype)initWithDatabaseName:(NSString *)databaseName { + self = [super init]; + if (self) { + _databaseName = [databaseName copy]; + BOOL didMoveToApplicationSupport = + [self moveToApplicationSupportSubDirectory:kFIRMessagingApplicationSupportSubDirectory]; + + _currentDirectory = didMoveToApplicationSupport + ? FIRMessagingRmqDirectoryApplicationSupport + : FIRMessagingRmqDirectoryDocuments; + + [self openDatabase:_databaseName]; + } + return self; +} + +- (void)dealloc { + sqlite3_close(_database); +} + +- (BOOL)moveToApplicationSupportSubDirectory:(NSString *)subDirectoryName { + NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, + NSUserDomainMask, YES); + NSString *applicationSupportDirPath = directoryPaths.lastObject; + NSArray *components = @[applicationSupportDirPath, subDirectoryName]; + NSString *subDirectoryPath = [NSString pathWithComponents:components]; + BOOL hasSubDirectory; + + if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath + isDirectory:&hasSubDirectory]) { + // Cannot move to non-existent directory + return NO; + } + + if ([self doesFileExistInDirectory:FIRMessagingRmqDirectoryDocuments]) { + NSString *oldPlistPath = [[self class] pathForDatabase:self.databaseName + inDirectory:FIRMessagingRmqDirectoryDocuments]; + NSString *newPlistPath = [[self class] + pathForDatabase:self.databaseName + inDirectory:FIRMessagingRmqDirectoryApplicationSupport]; + + if ([self doesFileExistInDirectory:FIRMessagingRmqDirectoryApplicationSupport]) { + // File exists in both Documents and ApplicationSupport, delete the one in Documents + NSError *deleteError; + if (![[NSFileManager defaultManager] removeItemAtPath:oldPlistPath error:&deleteError]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore000, + @"Failed to delete old copy of %@.sqlite in Documents %@", + self.databaseName, deleteError); + } + return NO; + } + NSError *moveError; + if (![[NSFileManager defaultManager] moveItemAtPath:oldPlistPath + toPath:newPlistPath + error:&moveError]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore001, + @"Failed to move file %@ from %@ to %@. Error: %@", self.databaseName, + oldPlistPath, newPlistPath, moveError); + return NO; + } + } + // We moved the file if it existed, otherwise we didn't need to do anything + return YES; +} + +- (BOOL)doesFileExistInDirectory:(FIRMessagingRmqDirectory)directory { + NSString *path = [[self class] pathForDatabase:self.databaseName inDirectory:directory]; + return [[NSFileManager defaultManager] fileExistsAtPath:path]; +} + ++ (NSString *)pathForDatabase:(NSString *)dbName inDirectory:(FIRMessagingRmqDirectory)directory { + NSArray *paths; + NSArray *components; + NSString *dbNameWithExtension = [NSString stringWithFormat:@"%@.sqlite", dbName]; + NSString *errorMessage; + + switch (directory) { + case FIRMessagingRmqDirectoryDocuments: + paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + components = @[paths.lastObject, dbNameWithExtension]; + break; + + case FIRMessagingRmqDirectoryApplicationSupport: + paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, + NSUserDomainMask, + YES); + components = @[ + paths.lastObject, + kFIRMessagingApplicationSupportSubDirectory, + dbNameWithExtension + ]; + break; + + default: + errorMessage = [NSString stringWithFormat:@"Invalid directory type %lu", + (unsigned long)directory]; + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreInvalidRmqDirectory, + @"%@", + errorMessage); + NSAssert(NO, errorMessage); + break; + } + + return [NSString pathWithComponents:components]; +} + +- (void)createTableWithName:(NSString *)tableName command:(NSString *)command { + char *error; + NSString *createDatabase = [NSString stringWithFormat:command, kTablePrefix, tableName]; + if (sqlite3_exec(_database, [createDatabase UTF8String], NULL, NULL, &error) != SQLITE_OK) { + // remove db before failing + [self removeDatabase]; + NSString *errorMessage = [NSString stringWithFormat:@"Couldn't create table: %@ %@", + kCreateTableOutgoingRmqMessages, + [NSString stringWithCString:error encoding:NSUTF8StringEncoding]]; + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingTable, + @"%@", + errorMessage); + NSAssert(NO, errorMessage); + } +} + +- (void)dropTableWithName:(NSString *)tableName { + char *error; + NSString *dropTableSQL = [NSString stringWithFormat:kDropTableCommand, kTablePrefix, tableName]; + if (sqlite3_exec(_database, [dropTableSQL UTF8String], NULL, NULL, &error) != SQLITE_OK) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore002, + @"Failed to remove table %@", tableName); + } +} + +- (void)removeDatabase { + NSString *path = [[self class] pathForDatabase:self.databaseName + inDirectory:self.currentDirectory]; + [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; +} + ++ (void)removeDatabase:(NSString *)dbName { + NSString *documentsDirPath = [self pathForDatabase:dbName + inDirectory:FIRMessagingRmqDirectoryDocuments]; + NSString *applicationSupportDirPath = + [self pathForDatabase:dbName inDirectory:FIRMessagingRmqDirectoryApplicationSupport]; + [[NSFileManager defaultManager] removeItemAtPath:documentsDirPath error:nil]; + [[NSFileManager defaultManager] removeItemAtPath:applicationSupportDirPath error:nil]; +} + +- (void)openDatabase:(NSString *)dbName { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSString *path = [[self class] pathForDatabase:dbName inDirectory:self.currentDirectory]; + + BOOL didOpenDatabase = YES; + if (![fileManager fileExistsAtPath:path]) { + // We've to separate between different versions here because of backwards compatbility issues. + int result = sqlite3_open([path UTF8String], &_database); + if (result != SQLITE_OK) { + NSString *errorString = FIRMessagingStringFromSQLiteResult(result); + NSString *errorMessage = + [NSString stringWithFormat:@"Could not open existing RMQ database at path %@, error: %@", + path, + errorString]; + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorOpeningDatabase, + @"%@", + errorMessage); + NSAssert(NO, errorMessage); + return; + } + [self createTableWithName:kTableOutgoingRmqMessages + command:kCreateTableOutgoingRmqMessages]; + + [self createTableWithName:kTableLastRmqId command:kCreateTableLastRmqId]; + [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds]; + } else { + // Calling sqlite3_open should create the database, since the file doesn't exist. + int result = sqlite3_open([path UTF8String], &_database); + if (result != SQLITE_OK) { + NSString *errorString = FIRMessagingStringFromSQLiteResult(result); + NSString *errorMessage = + [NSString stringWithFormat:@"Could not create RMQ database at path %@, error: %@", + path, + errorString]; + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingDatabase, + @"%@", + errorMessage); + NSAssert(NO, errorMessage); + didOpenDatabase = NO; + } else { + [self updateDbWithStringRmqID]; + } + } + + if (didOpenDatabase) { + [self createTableWithName:kTableSyncMessages command:kCreateTableSyncMessages]; + } +} + +- (void)updateDbWithStringRmqID { + [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds]; + [self dropTableWithName:kOldTableS2DRmqIds]; +} + +#pragma mark - Insert + +- (BOOL)saveUnackedS2dMessageWithRmqId:(NSString *)rmqId { + NSString *insertFormat = @"INSERT INTO %@ (%@) VALUES (?)"; + NSString *insertSQL = [NSString stringWithFormat:insertFormat, + kTableS2DRmqIds, + kRmqIdColumn]; + sqlite3_stmt *insert_statement; + if (sqlite3_prepare_v2(_database, [insertSQL UTF8String], -1, &insert_statement, NULL) + != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_bind_text(insert_statement, + 1, + [rmqId UTF8String], + (int)[rmqId length], + SQLITE_STATIC) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_step(insert_statement) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + sqlite3_finalize(insert_statement); + return YES; +} + +- (BOOL)saveMessageWithRmqId:(int64_t)rmqId + tag:(int8_t)tag + data:(NSData *)data + error:(NSError **)error { + NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@) VALUES (?, ?, ?)"; + NSString *insertSQL = [NSString stringWithFormat:insertFormat, + kTableOutgoingRmqMessages, // table + kRmqIdColumn, kProtobufTagColumn, kDataColumn /* columns */]; + sqlite3_stmt *insert_statement; + if (sqlite3_prepare_v2(_database, [insertSQL UTF8String], -1, &insert_statement, NULL) + != SQLITE_OK) { + if (error) { + *error = [NSError errorWithDomain:[NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)] + code:sqlite3_errcode(_database) + userInfo:nil]; + } + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_bind_int64(insert_statement, 1, rmqId) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_bind_int(insert_statement, 2, tag) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_bind_blob(insert_statement, 3, [data bytes], (int)[data length], NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + if (sqlite3_step(insert_statement) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(insert_statement, NO); + } + + sqlite3_finalize(insert_statement); + return YES; +} + +- (int)deleteMessagesFromTable:(NSString *)tableName + withRmqIds:(NSArray *)rmqIds { + _FIRMessagingDevAssert([tableName isEqualToString:kTableOutgoingRmqMessages] || + [tableName isEqualToString:kTableLastRmqId] || + [tableName isEqualToString:kTableS2DRmqIds] || + [tableName isEqualToString:kTableSyncMessages], + @"%@: Invalid Table Name %@", kFCMRmqStoreTag, tableName); + + BOOL isRmqIDString = NO; + // RmqID is a string only for outgoing messages + if ([tableName isEqualToString:kTableS2DRmqIds] || + [tableName isEqualToString:kTableSyncMessages]) { + isRmqIDString = YES; + } + + NSMutableString *delete = [NSMutableString stringWithFormat:@"DELETE FROM %@ WHERE ", tableName]; + + NSString *toDeleteArgument = [NSString stringWithFormat:@"%@ = ? OR ", kRmqIdColumn]; + + int toDelete = (int)[rmqIds count]; + if (toDelete == 0) { + return 0; + } + int maxBatchSize = 100; + int start = 0; + int deleteCount = 0; + while (start < toDelete) { + + // construct the WHERE argument + int end = MIN(start + maxBatchSize, toDelete); + NSMutableString *whereArgument = [NSMutableString string]; + for (int i = start; i < end; i++) { + [whereArgument appendString:toDeleteArgument]; + } + // remove the last * OR * from argument + NSRange range = NSMakeRange([whereArgument length] -4, 4); + [whereArgument deleteCharactersInRange:range]; + NSString *deleteQuery = [NSString stringWithFormat:@"%@ %@", delete, whereArgument]; + + + // sqlite update + sqlite3_stmt *delete_statement; + if (sqlite3_prepare_v2(_database, [deleteQuery UTF8String], + -1, &delete_statement, NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(delete_statement, 0); + } + + // bind values + int rmqIndex = 0; + int placeholderIndex = 1; // placeholders in sqlite3 start with 1 + for (NSString *rmqId in rmqIds) { // objectAtIndex: is O(n) -- would make it slow + if (rmqIndex < start) { + rmqIndex++; + continue; + } else if (rmqIndex >= end) { + break; + } else { + if (isRmqIDString) { + if (sqlite3_bind_text(delete_statement, + placeholderIndex, + [rmqId UTF8String], + (int)[rmqId length], + SQLITE_STATIC) != SQLITE_OK) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore003, + @"Failed to bind rmqID %@", rmqId); + continue; + } + } else { + int64_t rmqIdValue = [rmqId longLongValue]; + sqlite3_bind_int64(delete_statement, placeholderIndex, rmqIdValue); + } + placeholderIndex++; + } + rmqIndex++; + } + if (sqlite3_step(delete_statement) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(delete_statement, deleteCount); + } + sqlite3_finalize(delete_statement); + deleteCount += sqlite3_changes(_database); + start = end; + } + + // if we are here all of our sqlite queries should have succeeded + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore004, + @"%@ Trying to delete %d s2D ID's, successfully deleted %d", + kFCMRmqStoreTag, toDelete, deleteCount); + return deleteCount; +} + +#pragma mark - Query + +- (int64_t)queryHighestRmqId { + NSString *queryFormat = @"SELECT %@ FROM %@ ORDER BY %@ DESC LIMIT %d"; + NSString *query = [NSString stringWithFormat:queryFormat, + kRmqIdColumn, // column + kTableOutgoingRmqMessages, // table + kRmqIdColumn, // order by column + 1]; // limit + + sqlite3_stmt *statement; + int64_t highestRmqId = 0; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(statement, highestRmqId); + } + if (sqlite3_step(statement) == SQLITE_ROW) { + highestRmqId = sqlite3_column_int64(statement, 0); + } + sqlite3_finalize(statement); + return highestRmqId; +} + +- (int64_t)queryLastRmqId { + NSString *queryFormat = @"SELECT %@ FROM %@ ORDER BY %@ DESC LIMIT %d"; + NSString *query = [NSString stringWithFormat:queryFormat, + kRmqIdColumn, // column + kTableLastRmqId, // table + kRmqIdColumn, // order by column + 1]; // limit + + sqlite3_stmt *statement; + int64_t lastRmqId = 0; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(statement, lastRmqId); + } + if (sqlite3_step(statement) == SQLITE_ROW) { + lastRmqId = sqlite3_column_int64(statement, 0); + } + sqlite3_finalize(statement); + return lastRmqId; +} + +- (BOOL)updateLastOutgoingRmqId:(int64_t)rmqID { + NSString *queryFormat = @"INSERT OR REPLACE INTO %@ (%@, %@) VALUES (?, ?)"; + NSString *query = [NSString stringWithFormat:queryFormat, + kTableLastRmqId, // table + kIdColumn, kRmqIdColumn]; // columns + sqlite3_stmt *statement; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(statement, NO); + } + if (sqlite3_bind_int(statement, 1, 1) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(statement, NO); + } + if (sqlite3_bind_int64(statement, 2, rmqID) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(statement, NO); + } + if (sqlite3_step(statement) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(statement, NO); + } + sqlite3_finalize(statement); + return YES; +} + +- (NSArray *)unackedS2dRmqIds { + NSString *queryFormat = @"SELECT %@ FROM %@ ORDER BY %@ ASC"; + NSString *query = [NSString stringWithFormat:queryFormat, + kRmqIdColumn, + kTableS2DRmqIds, + kRmqIdColumn]; + sqlite3_stmt *statement; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore005, + @"%@: Could not find s2d ids", kFCMRmqStoreTag); + _FIRMessagingRmqLogAndExit(statement, @[]); + } + NSMutableArray *rmqIDArray = [NSMutableArray array]; + while (sqlite3_step(statement) == SQLITE_ROW) { + const char *rmqID = (char *)sqlite3_column_text(statement, 0); + [rmqIDArray addObject:[NSString stringWithUTF8String:rmqID]]; + } + sqlite3_finalize(statement); + return rmqIDArray; +} + +#pragma mark - Scan + +- (void)scanOutgoingRmqMessagesWithHandler:(FCMOutgoingRmqMessagesTableHandler)handler { + static NSString *queryFormat = @"SELECT %@ FROM %@ WHERE %@ != 0 ORDER BY %@ ASC"; + NSString *query = [NSString stringWithFormat:queryFormat, + kOutgoingRmqMessagesColumns, // select (rmq_id, type, data) + kTableOutgoingRmqMessages, // from table + kRmqIdColumn, // where + kRmqIdColumn]; // order by + sqlite3_stmt *statement; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) { + [self logError]; + sqlite3_finalize(statement); + return; + } + // can query sqlite3 for this but this is fine + const int rmqIdColumnNumber = 0; + const int typeColumnNumber = 1; + const int dataColumnNumber = 2; + while (sqlite3_step(statement) == SQLITE_ROW) { + int64_t rmqId = sqlite3_column_int64(statement, rmqIdColumnNumber); + int8_t type = sqlite3_column_int(statement, typeColumnNumber); + const void *bytes = sqlite3_column_blob(statement, dataColumnNumber); + int length = sqlite3_column_bytes(statement, dataColumnNumber); + _FIRMessagingDevAssert(bytes != NULL, + @"%@ Message with no data being stored in Rmq", + kFCMRmqStoreTag); + NSData *data = [NSData dataWithBytes:bytes length:length]; + handler(rmqId, type, data); + } + sqlite3_finalize(statement); +} + +#pragma mark - Sync Messages + +- (FIRMessagingPersistentSyncMessage *)querySyncMessageWithRmqID:(NSString *)rmqID { + _FIRMessagingDevAssert([rmqID length], @"Invalid rmqID key %@ to search in SYNC_RMQ", rmqID); + + NSString *queryFormat = @"SELECT %@ FROM %@ WHERE %@ = '%@'"; + NSString *query = [NSString stringWithFormat:queryFormat, + kSyncMessagesColumns, // SELECT (rmq_id, expiration_ts, apns_recv, mcs_recv) + kTableSyncMessages, // FROM sync_rmq + kRmqIdColumn, // WHERE rmq_id + rmqID]; + + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) { + [self logError]; + sqlite3_finalize(stmt); + return nil; + } + + const int rmqIDColumn = 0; + const int expirationTimestampColumn = 1; + const int apnsReceivedColumn = 2; + const int mcsReceivedColumn = 3; + + int count = 0; + FIRMessagingPersistentSyncMessage *persistentMessage; + + while (sqlite3_step(stmt) == SQLITE_ROW) { + NSString *rmqID = + [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, rmqIDColumn)]; + int64_t expirationTimestamp = sqlite3_column_int64(stmt, expirationTimestampColumn); + BOOL apnsReceived = sqlite3_column_int(stmt, apnsReceivedColumn); + BOOL mcsReceived = sqlite3_column_int(stmt, mcsReceivedColumn); + + // create a new persistent message + persistentMessage = + [[FIRMessagingPersistentSyncMessage alloc] initWithRMQID:rmqID expirationTime:expirationTimestamp]; + persistentMessage.apnsReceived = apnsReceived; + persistentMessage.mcsReceived = mcsReceived; + + count++; + } + sqlite3_finalize(stmt); + + _FIRMessagingDevAssert(count <= 1, @"Found multiple messages in %@ with same RMQ ID", kTableSyncMessages); + return persistentMessage; +} + +- (BOOL)deleteSyncMessageWithRmqID:(NSString *)rmqID { + _FIRMessagingDevAssert([rmqID length], @"Invalid rmqID key %@ to delete in SYNC_RMQ", rmqID); + return [self deleteMessagesFromTable:kTableSyncMessages withRmqIds:@[rmqID]] > 0; +} + +- (int)deleteExpiredOrFinishedSyncMessages:(NSError *__autoreleasing *)error { + int64_t now = FIRMessagingCurrentTimestampInSeconds(); + NSString *deleteSQL = @"DELETE FROM %@ " + @"WHERE %@ < %lld OR " // expirationTime < now + @"(%@ = 1 AND %@ = 1)"; // apns_received = 1 AND mcs_received = 1 + NSString *query = [NSString stringWithFormat:deleteSQL, + kTableSyncMessages, + kSyncMessageExpirationTimestampColumn, + now, + kSyncMessageAPNSReceivedColumn, + kSyncMessageMCSReceivedColumn]; + + NSString *errorReason = @"Failed to save delete expired sync messages from store."; + + sqlite3_stmt *stmt; + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) { + if (error) { + *error = [NSError fcm_errorWithCode:sqlite3_errcode(_database) + userInfo:@{ @"error" : errorReason }]; + } + _FIRMessagingRmqLogAndExit(stmt, 0); + } + + if (sqlite3_step(stmt) != SQLITE_DONE) { + if (error) { + *error = [NSError fcm_errorWithCode:sqlite3_errcode(_database) + userInfo:@{ @"error" : errorReason }]; + } + _FIRMessagingRmqLogAndExit(stmt, 0); + } + + sqlite3_finalize(stmt); + int deleteCount = sqlite3_changes(_database); + return deleteCount; +} + +- (BOOL)saveSyncMessageWithRmqID:(NSString *)rmqID + expirationTime:(int64_t)expirationTime + apnsReceived:(BOOL)apnsReceived + mcsReceived:(BOOL)mcsReceived + error:(NSError **)error { + _FIRMessagingDevAssert([rmqID length], @"Invalid nil message to persist to SYNC_RMQ"); + + NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@, %@) VALUES (?, ?, ?, ?)"; + NSString *insertSQL = [NSString stringWithFormat:insertFormat, + kTableSyncMessages, // Table name + kRmqIdColumn, // rmq_id + kSyncMessageExpirationTimestampColumn, // expiration_ts + kSyncMessageAPNSReceivedColumn, // apns_recv + kSyncMessageMCSReceivedColumn /* mcs_recv */]; + + sqlite3_stmt *stmt; + + if (sqlite3_prepare_v2(_database, [insertSQL UTF8String], -1, &stmt, NULL) != SQLITE_OK) { + if (error) { + *error = [NSError fcm_errorWithCode:sqlite3_errcode(_database) + userInfo:@{ @"error" : @"Failed to save sync message to store." }]; + } + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_bind_int64(stmt, 2, expirationTime) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_bind_int(stmt, 3, apnsReceived ? 1 : 0) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_bind_int(stmt, 4, mcsReceived ? 1 : 0) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_step(stmt) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + sqlite3_finalize(stmt); + return YES; +} + +- (BOOL)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID + error:(NSError **)error { + return [self updateSyncMessageWithRmqID:rmqID + column:kSyncMessageAPNSReceivedColumn + value:YES + error:error]; +} + +- (BOOL)updateSyncMessageViaMCSWithRmqID:(NSString *)rmqID + error:(NSError *__autoreleasing *)error { + return [self updateSyncMessageWithRmqID:rmqID + column:kSyncMessageMCSReceivedColumn + value:YES + error:error]; +} + +- (BOOL)updateSyncMessageWithRmqID:(NSString *)rmqID + column:(NSString *)column + value:(BOOL)value + error:(NSError **)error { + _FIRMessagingDevAssert([column isEqualToString:kSyncMessageAPNSReceivedColumn] || + [column isEqualToString:kSyncMessageMCSReceivedColumn], + @"Invalid column name %@ for SYNC_RMQ", column); + NSString *queryFormat = @"UPDATE %@ " // Table name + @"SET %@ = %d " // column=value + @"WHERE %@ = ?"; // condition + NSString *query = [NSString stringWithFormat:queryFormat, + kTableSyncMessages, + column, + value ? 1 : 0, + kRmqIdColumn]; + sqlite3_stmt *stmt; + + if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) { + if (error) { + *error = [NSError fcm_errorWithCode:sqlite3_errcode(_database) + userInfo:@{ @"error" : @"Failed to update sync message"}]; + } + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + if (sqlite3_step(stmt) != SQLITE_DONE) { + _FIRMessagingRmqLogAndExit(stmt, NO); + } + + sqlite3_finalize(stmt); + return YES; + +} + +#pragma mark - Private + +- (NSString *)lastErrorMessage { + return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)]; +} + +- (int)lastErrorCode { + return sqlite3_errcode(_database); +} + +- (void)logError { + FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore006, + @"%@ error: code (%d) message: %@", kFCMRmqStoreTag, [self lastErrorCode], + [self lastErrorMessage]); +} + +- (void)logErrorAndFinalizeStatement:(sqlite3_stmt *)stmt { + [self logError]; + sqlite3_finalize(stmt); +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.h new file mode 100644 index 0000000..ba48b98 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.h @@ -0,0 +1,190 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class GtalkDataMessageStanza; +@class GPBMessage; + +@class FIRMessagingPersistentSyncMessage; + +/** + * Called on each raw message. + */ +typedef void(^FIRMessagingRmqMessageHandler)(int64_t rmqId, int8_t tag, NSData *data); + +/** + * Called on each DataMessageStanza. + */ +typedef void(^FIRMessagingDataMessageHandler)(int64_t rmqId, GtalkDataMessageStanza *stanza); + +/** + * Used to scan through the rmq and perform actions on messages as required. + */ +@protocol FIRMessagingRmqScanner + +/** + * Scan the RMQ for outgoing messages and process them as required. + */ +- (void)scanWithRmqMessageHandler:(FIRMessagingRmqMessageHandler)rmqMessageHandler + dataMessageHandler:(FIRMessagingDataMessageHandler)dataMessageHandler; + +@end + +/** + * This manages the RMQ persistent store. + * + * The store is used to store all the S2D id's that were received by the client and were ACK'ed + * by us but the server hasn't confirmed the ACK. We don't delete these id's until the server + * ACK's us that they have received them. + * + * We also store the upstream messages(d2s) that were sent by the client. + * + * Also store the lastRMQId that was sent by us so that for a new connection being setup we don't + * duplicate RMQ Id's for the new messages. + */ +@interface FIRMessagingRmqManager : NSObject + +// designated initializer +- (instancetype)initWithDatabaseName:(NSString *)databaseName; + +- (void)loadRmqId; + +/** + * Save an upstream message to RMQ. If the message send fails for some reason we would not + * lose the message since it would be saved in the RMQ. + * + * @param message The upstream message to be saved. + * @param error The error if any while saving the message else nil. + * + * @return YES if the message was successfully saved to RMQ else NO. + */ +- (BOOL)saveRmqMessage:(GPBMessage *)message error:(NSError **)error; + +/** + * Save Server to device message with the given RMQ-ID. + * + * @param rmqID The rmqID of the s2d message to save. + * + * @return YES if the save was successfull else NO. + */ +- (BOOL)saveS2dMessageWithRmqId:(NSString *)rmqID; + +/** + * A list of all unacked Server to device RMQ IDs. + * + * @return A list of unacked Server to Device RMQ ID's. All values are Strings. + */ +- (NSArray *)unackedS2dRmqIds; + +/** + * Removes the outgoing message from RMQ store. + * + * @param rmqId The rmqID to remove from the store. + * + * @return The number of messages deleted successfully. + */ +- (int)removeRmqMessagesWithRmqId:(NSString *)rmqId; + +/** + * Removes the messages with the given rmqIDs from RMQ store. + * + * @param rmqIds The lsit of rmqID's to remove from the store. + * + * @return The number of messages deleted successfully. + */ +- (int)removeRmqMessagesWithRmqIds:(NSArray *)rmqIds; + +/** + * Removes a list of downstream messages from the RMQ. + * + * @param s2dIds The list of messages ACK'ed by the server that we should remove + * from the RMQ store. + */ +- (void)removeS2dIds:(NSArray *)s2dIds; + +#pragma mark - Sync Messages + +/** + * Get persisted sync message with rmqID. + * + * @param rmqID The rmqID of the persisted sync message. + * + * @return A valid persistent sync message with the given rmqID if found in the RMQ else nil. + */ +- (FIRMessagingPersistentSyncMessage *)querySyncMessageWithRmqID:(NSString *)rmqID; + +/** + * Delete sync message with rmqID. + * + * @param rmqID The rmqID of the persisted sync message. + * + * @return YES if the message was successfully deleted else NO. + */ +- (BOOL)deleteSyncMessageWithRmqID:(NSString *)rmqID; + +/** + * Delete the expired sync messages from persisten store. Also deletes messages that have been + * delivered both via APNS and MCS. + * + * @param error The error if any while deleting the messages. + * + * @return The total number of messages that were deleted from the persistent store. + */ +- (int)deleteExpiredOrFinishedSyncMessages:(NSError **)error; + +/** + * Save sync message received by the device. + * + * @param rmqID The rmqID of the message received. + * @param expirationTime The expiration time of the sync message received. + * @param apnsReceived YES if the message was received via APNS else NO. + * @param mcsReceived YES if the message was received via MCS else NO. + * @param error The error if any while saving the sync message to persistent store. + * + * @return YES if the message save was successful else NO. + */ +- (BOOL)saveSyncMessageWithRmqID:(NSString *)rmqID + expirationTime:(int64_t)expirationTime + apnsReceived:(BOOL)apnsReceived + mcsReceived:(BOOL)mcsReceived + error:(NSError **)error; + +/** + * Update sync message received via APNS. + * + * @param rmqID The rmqID of the received message. + * @param error The error if any while updating the sync message. + * + * @return YES if the persistent sync message was successfully updated else NO. + */ +- (BOOL)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID error:(NSError **)error; + +/** + * Update sync message received via MCS. + * + * @param rmqID The rmqID of the received message. + * @param error The error if any while updating the sync message. + * + * @return YES if the persistent sync message was successfully updated else NO. + */ +- (BOOL)updateSyncMessageViaMCSWithRmqID:(NSString *)rmqID error:(NSError **)error; + +#pragma mark - Testing + ++ (void)removeDatabaseWithName:(NSString *)dbName; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.m new file mode 100644 index 0000000..449e3d6 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingRmqManager.m @@ -0,0 +1,264 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingRmqManager.h" + +#import + +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingRmq2PersistentStore.h" +#import "FIRMessagingUtilities.h" +#import "Protos/GtalkCore.pbobjc.h" + +#ifndef _FIRMessagingRmqLogAndExit +#define _FIRMessagingRmqLogAndExit(stmt, return_value) \ +do { \ + [self logErrorAndFinalizeStatement:stmt]; \ + return return_value; \ +} while(0) +#endif + +static NSString *const kFCMRmqTag = @"FIRMessagingRmq:"; + +@interface FIRMessagingRmqManager () + +@property(nonatomic, readwrite, strong) FIRMessagingRmq2PersistentStore *rmq2Store; +// map the category of an outgoing message with the number of messages for that category +// should always have two keys -- the app, gcm +@property(nonatomic, readwrite, strong) NSMutableDictionary *outstandingMessages; + +// Outgoing RMQ persistent id +@property(nonatomic, readwrite, assign) int64_t rmqId; + +@end + +@implementation FIRMessagingRmqManager + +- (instancetype)initWithDatabaseName:(NSString *)databaseName { + self = [super init]; + if (self) { + _FIRMessagingDevAssert([databaseName length] > 0, @"RMQ: Invalid rmq db name"); + _rmq2Store = [[FIRMessagingRmq2PersistentStore alloc] initWithDatabaseName:databaseName]; + _outstandingMessages = [NSMutableDictionary dictionaryWithCapacity:2]; + _rmqId = -1; + } + return self; +} + +- (void)loadRmqId { + if (self.rmqId >= 0) { + return; // already done + } + + [self loadInitialOutgoingPersistentId]; + if (self.outstandingMessages.count) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmqManager000, + @"%@: outstanding categories %ld", kFCMRmqTag, + _FIRMessaging_UL(self.outstandingMessages.count)); + } +} + +/** + * Initialize the 'initial RMQ': + * - max ID of any message in the queue + * - if the queue is empty, stored value in separate DB. + * + * Stream acks will remove from RMQ, when we remove the highest message we keep track + * of its ID. + */ +- (void)loadInitialOutgoingPersistentId { + + // we shouldn't always trust the lastRmqId stored in the LastRmqId table, because + // we only save to the LastRmqId table once in a while (after getting the lastRmqId sent + // by the server after reconnect, and after getting a rmq ack from the server). The + // rmq message with the highest rmq id tells the real story, so check against that first. + + int64_t rmqId = [self queryHighestRmqId]; + if (rmqId == 0) { + rmqId = [self querylastRmqId]; + } + self.rmqId = rmqId + 1; +} + +#pragma mark - Save + +/** + * Save a message to RMQ2. Will populate the rmq2 persistent ID. + */ +- (BOOL)saveRmqMessage:(GPBMessage *)message + error:(NSError **)error { + // send using rmq2manager + // the wire format of rmq2 id is a string. However, we keep it as a long internally + // in the database. So only convert the id to string when preparing for sending over + // the wire. + NSString *rmq2Id = FIRMessagingGetRmq2Id(message); + if (![rmq2Id length]) { + int64_t rmqId = [self nextRmqId]; + rmq2Id = [NSString stringWithFormat:@"%lld", rmqId]; + FIRMessagingSetRmq2Id(message, rmq2Id); + } + FIRMessagingProtoTag tag = FIRMessagingGetTagForProto(message); + return [self saveMessage:message withRmqId:[rmq2Id integerValue] tag:tag error:error]; +} + +- (BOOL)saveMessage:(GPBMessage *)message + withRmqId:(int64_t)rmqId + tag:(int8_t)tag + error:(NSError **)error { + NSData *data = [message data]; + return [self.rmq2Store saveMessageWithRmqId:rmqId tag:tag data:data error:error]; +} + +/** + * This is called when we delete the largest outgoing message from queue. + */ +- (void)saveLastOutgoingRmqId:(int64_t)rmqID { + [self.rmq2Store updateLastOutgoingRmqId:rmqID]; +} + +- (BOOL)saveS2dMessageWithRmqId:(NSString *)rmqID { + return [self.rmq2Store saveUnackedS2dMessageWithRmqId:rmqID]; +} + +#pragma mark - Query + +- (int64_t)queryHighestRmqId { + return [self.rmq2Store queryHighestRmqId]; +} + +- (int64_t)querylastRmqId { + return [self.rmq2Store queryLastRmqId]; +} + +- (NSArray *)unackedS2dRmqIds { + return [self.rmq2Store unackedS2dRmqIds]; +} + +#pragma mark - FIRMessagingRMQScanner protocol + +/** + * We don't have a 'getMessages' method - it would require loading in memory + * the entire content body of all messages. + * + * Instead we iterate and call 'resend' for each message. + * + * This is called: + * - on connect MCS, to resend any outstanding messages + * - init + */ +- (void)scanWithRmqMessageHandler:(FIRMessagingRmqMessageHandler)rmqMessageHandler + dataMessageHandler:(FIRMessagingDataMessageHandler)dataMessageHandler { + // no need to scan database with no callbacks + if (rmqMessageHandler || dataMessageHandler) { + [self.rmq2Store scanOutgoingRmqMessagesWithHandler:^(int64_t rmqId, int8_t tag, NSData *data) { + if (rmqMessageHandler != nil) { + rmqMessageHandler(rmqId, tag, data); + } + if (dataMessageHandler != nil && kFIRMessagingProtoTagDataMessageStanza == tag) { + GPBMessage *proto = + [FIRMessagingGetClassForTag((FIRMessagingProtoTag)tag) parseFromData:data error:NULL]; + GtalkDataMessageStanza *stanza = (GtalkDataMessageStanza *)proto; + dataMessageHandler(rmqId, stanza); + } + }]; + } +} + +#pragma mark - Remove + +- (void)ackReceivedForRmqId:(NSString *)rmqId { + // TODO: Optional book-keeping +} + +- (int)removeRmqMessagesWithRmqId:(NSString *)rmqId { + return [self removeRmqMessagesWithRmqIds:@[rmqId]]; +} + +- (int)removeRmqMessagesWithRmqIds:(NSArray *)rmqIds { + if (![rmqIds count]) { + return 0; + } + for (NSString *rmqId in rmqIds) { + [self ackReceivedForRmqId:rmqId]; + } + int64_t maxRmqId = -1; + for (NSString *rmqId in rmqIds) { + int64_t rmqIdValue = [rmqId longLongValue]; + if (rmqIdValue > maxRmqId) { + maxRmqId = rmqIdValue; + } + } + maxRmqId++; + if (maxRmqId >= self.rmqId) { + [self saveLastOutgoingRmqId:maxRmqId]; + } + return [self.rmq2Store deleteMessagesFromTable:kTableOutgoingRmqMessages withRmqIds:rmqIds]; +} + +- (void)removeS2dIds:(NSArray *)s2dIds { + [self.rmq2Store deleteMessagesFromTable:kTableS2DRmqIds withRmqIds:s2dIds]; +} + +#pragma mark - Sync Messages + +// TODO: RMQManager should also have a cache for all the sync messages +// so we don't hit the DB each time. +- (FIRMessagingPersistentSyncMessage *)querySyncMessageWithRmqID:(NSString *)rmqID { + return [self.rmq2Store querySyncMessageWithRmqID:rmqID]; +} + +- (BOOL)deleteSyncMessageWithRmqID:(NSString *)rmqID { + return [self.rmq2Store deleteSyncMessageWithRmqID:rmqID]; +} + +- (int)deleteExpiredOrFinishedSyncMessages:(NSError **)error { + return [self.rmq2Store deleteExpiredOrFinishedSyncMessages:error]; +} + +- (BOOL)saveSyncMessageWithRmqID:(NSString *)rmqID + expirationTime:(int64_t)expirationTime + apnsReceived:(BOOL)apnsReceived + mcsReceived:(BOOL)mcsReceived + error:(NSError *__autoreleasing *)error { + return [self.rmq2Store saveSyncMessageWithRmqID:rmqID + expirationTime:expirationTime + apnsReceived:apnsReceived + mcsReceived:mcsReceived + error:error]; +} + +- (BOOL)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID error:(NSError **)error { + return [self.rmq2Store updateSyncMessageViaAPNSWithRmqID:rmqID error:error]; +} + +- (BOOL)updateSyncMessageViaMCSWithRmqID:(NSString *)rmqID error:(NSError **)error { + return [self.rmq2Store updateSyncMessageViaMCSWithRmqID:rmqID error:error]; +} + +#pragma mark - Testing + ++ (void)removeDatabaseWithName:(NSString *)dbName { + [FIRMessagingRmq2PersistentStore removeDatabase:dbName]; +} + +#pragma mark - Private + +- (int64_t)nextRmqId { + return ++self.rmqId; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.h new file mode 100644 index 0000000..169f60e --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +typedef NS_ENUM(NSUInteger, FIRMessagingSecureSocketState){ + kFIRMessagingSecureSocketNotOpen = 0, + kFIRMessagingSecureSocketOpening, + kFIRMessagingSecureSocketOpen, + kFIRMessagingSecureSocketClosing, + kFIRMessagingSecureSocketClosed, + kFIRMessagingSecureSocketError +}; + +@class FIRMessagingSecureSocket; + +@protocol FIRMessagingSecureSocketDelegate + +- (void)secureSocket:(FIRMessagingSecureSocket *)socket + didReceiveData:(NSData *)data + withTag:(int8_t)tag; +- (void)secureSocket:(FIRMessagingSecureSocket *)socket + didSendProtoWithTag:(int8_t)tag + rmqId:(NSString *)rmqId; +- (void)secureSocketDidConnect:(FIRMessagingSecureSocket *)socket; +- (void)didDisconnectWithSecureSocket:(FIRMessagingSecureSocket *)socket; + +@end + +/** + * This manages the input/output streams connected to the MCS server. Used to receive data from + * the server and send to it over the wire. + */ +@interface FIRMessagingSecureSocket : NSObject + +@property(nonatomic, readwrite, weak) id delegate; +@property(nonatomic, readonly, assign) FIRMessagingSecureSocketState state; + +- (void)connectToHost:(NSString *)host port:(NSUInteger)port onRunLoop:(NSRunLoop *)runLoop; +- (void)disconnect; +- (void)sendData:(NSData *)data withTag:(int8_t)tag rmqId:(NSString *)rmqId; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.m new file mode 100644 index 0000000..46d4a70 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.m @@ -0,0 +1,444 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingSecureSocket.h" + +#import "GPBMessage.h" +#import "GPBCodedOutputStream.h" +#import "GPBUtilities.h" + +#import "FIRMessagingCodedInputStream.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPacketQueue.h" + +static const NSUInteger kMaxBufferLength = 1024 * 1024; // 1M +static const NSUInteger kBufferLengthIncrement = 16 * 1024; // 16k +static const uint8_t kVersion = 40; +static const uint8_t kInvalidTag = -1; + +typedef NS_ENUM(NSUInteger, FIRMessagingSecureSocketReadResult) { + kFIRMessagingSecureSocketReadResultNone, + kFIRMessagingSecureSocketReadResultIncomplete, + kFIRMessagingSecureSocketReadResultCorrupt, + kFIRMessagingSecureSocketReadResultSuccess +}; + +static int32_t LogicalRightShift32(int32_t value, int32_t spaces) { + return (int32_t)((uint32_t)(value) >> spaces); +} + +static NSUInteger SerializedSize(int32_t value) { + NSUInteger bytes = 0; + while (YES) { + if ((value & ~0x7F) == 0) { + bytes += sizeof(uint8_t); + return bytes; + } else { + bytes += sizeof(uint8_t); + value = LogicalRightShift32(value, 7); + } + } +} + +@interface FIRMessagingSecureSocket() + +@property(nonatomic, readwrite, assign) FIRMessagingSecureSocketState state; +@property(nonatomic, readwrite, strong) NSInputStream *inStream; +@property(nonatomic, readwrite, strong) NSOutputStream *outStream; + +@property(nonatomic, readwrite, strong) NSMutableData *inputBuffer; +@property(nonatomic, readwrite, assign) NSUInteger inputBufferLength; +@property(nonatomic, readwrite, strong) NSMutableData *outputBuffer; +@property(nonatomic, readwrite, assign) NSUInteger outputBufferLength; + +@property(nonatomic, readwrite, strong) FIRMessagingPacketQueue *packetQueue; +@property(nonatomic, readwrite, assign) BOOL isVersionSent; +@property(nonatomic, readwrite, assign) BOOL isVersionReceived; +@property(nonatomic, readwrite, assign) BOOL isInStreamOpen; +@property(nonatomic, readwrite, assign) BOOL isOutStreamOpen; + +@property(nonatomic, readwrite, strong) NSRunLoop *runLoop; +@property(nonatomic, readwrite, strong) NSString *currentRmqIdBeingSent; +@property(nonatomic, readwrite, assign) int8_t currentProtoTypeBeingSent; + +@end + +@implementation FIRMessagingSecureSocket + +- (instancetype)init { + self = [super init]; + if (self) { + _state = kFIRMessagingSecureSocketNotOpen; + _inputBuffer = [NSMutableData dataWithLength:kBufferLengthIncrement]; + _packetQueue = [[FIRMessagingPacketQueue alloc] init]; + _currentProtoTypeBeingSent = kInvalidTag; + } + return self; +} + +- (void)dealloc { + [self disconnect]; +} + +- (void)connectToHost:(NSString *)host + port:(NSUInteger)port + onRunLoop:(NSRunLoop *)runLoop { + _FIRMessagingDevAssert(host != nil, @"Invalid host"); + _FIRMessagingDevAssert(runLoop != nil, @"Invalid runloop"); + _FIRMessagingDevAssert(self.state == kFIRMessagingSecureSocketNotOpen, @"Socket is already connected"); + + if (!host || self.state != kFIRMessagingSecureSocketNotOpen) { + return; + } + + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket000, + @"Opening secure socket to FIRMessaging service"); + self.state = kFIRMessagingSecureSocketOpening; + self.runLoop = runLoop; + CFReadStreamRef inputStreamRef; + CFWriteStreamRef outputStreamRef; + CFStreamCreatePairWithSocketToHost(NULL, + (__bridge CFStringRef)host, + (int)port, + &inputStreamRef, + &outputStreamRef); + self.inStream = CFBridgingRelease(inputStreamRef); + self.outStream = CFBridgingRelease(outputStreamRef); + if (!self.inStream || !self.outStream) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket001, + @"Failed to initialize socket."); + return; + } + + self.isInStreamOpen = NO; + self.isOutStreamOpen = NO; + + BOOL isVOIPSocket = NO; + + [self openStream:self.outStream isVOIPStream:isVOIPSocket]; + [self openStream:self.inStream isVOIPStream:isVOIPSocket]; +} + +- (void)disconnect { + if (self.state == kFIRMessagingSecureSocketClosing) { + return; + } + if (!self.inStream && !self.outStream) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket002, + @"The socket is not open or already closed."); + _FIRMessagingDevAssert(self.state == kFIRMessagingSecureSocketClosed || self.state == kFIRMessagingSecureSocketNotOpen, + @"Socket is already disconnected."); + return; + } + + self.state = kFIRMessagingSecureSocketClosing; + if (self.inStream) { + [self closeStream:self.inStream]; + self.inStream = nil; + } + if (self.outStream) { + [self closeStream:self.outStream]; + self.outStream = nil; + } + self.state = kFIRMessagingSecureSocketClosed; + [self.delegate didDisconnectWithSecureSocket:self]; +} + +- (void)sendData:(NSData *)data withTag:(int8_t)tag rmqId:(NSString *)rmqId { + [self.packetQueue push:[FIRMessagingPacket packetWithTag:tag rmqId:rmqId data:data]]; + if ([self.outStream hasSpaceAvailable]) { + [self performWrite]; + } +} + +#pragma mark - NSStreamDelegate + +- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { + switch (eventCode) { + case NSStreamEventHasBytesAvailable: + if (self.state != kFIRMessagingSecureSocketOpen) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket003, + @"Try to read from socket that is not opened"); + return; + } + _FIRMessagingDevAssert(stream == self.inStream, @"Incorrect stream"); + if (![self performRead]) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket004, + @"Error occurred when reading incoming stream"); + [self disconnect]; + } + break; + case NSStreamEventEndEncountered: + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeSecureSocket005, @"%@ end encountered", + stream == self.inStream + ? @"Input stream" + : (stream == self.outStream ? @"Output stream" : @"Unknown stream")); + [self disconnect]; + break; + case NSStreamEventOpenCompleted: + if (stream == self.inStream) { + self.isInStreamOpen = YES; + } else if (stream == self.outStream) { + self.isOutStreamOpen = YES; + } + if (self.isInStreamOpen && self.isOutStreamOpen) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket006, + @"Secure socket to FIRMessaging service opened"); + self.state = kFIRMessagingSecureSocketOpen; + [self.delegate secureSocketDidConnect:self]; + } + break; + case NSStreamEventErrorOccurred: { + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeSecureSocket007, @"%@ error occurred", + stream == self.inStream + ? @"Input stream" + : (stream == self.outStream ? @"Output stream" : @"Unknown stream")); + [self disconnect]; + break; + } + case NSStreamEventHasSpaceAvailable: + if (self.state != kFIRMessagingSecureSocketOpen) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket008, + @"Try to write to socket that is not opened"); + return; + } + _FIRMessagingDevAssert(stream == self.outStream, @"Incorrect stream"); + [self performWrite]; + break; + default: + break; + } +} + +#pragma mark - Private + +- (void)openStream:(NSStream *)stream isVOIPStream:(BOOL)isVOIPStream { + _FIRMessagingDevAssert(stream != nil, @"Invalid stream"); + _FIRMessagingDevAssert(self.runLoop != nil, @"Invalid runloop"); + + if (stream) { + _FIRMessagingDevAssert([stream streamStatus] == NSStreamStatusNotOpen, @"Stream already open"); + if ([stream streamStatus] != NSStreamStatusNotOpen) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket009, + @"stream should not be open."); + return; + } + [stream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL + forKey:NSStreamSocketSecurityLevelKey]; + if (isVOIPStream) { + [stream setProperty:NSStreamNetworkServiceTypeVoIP + forKey:NSStreamNetworkServiceType]; + } + stream.delegate = self; + [stream scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode]; + [stream open]; + } +} + +- (void)closeStream:(NSStream *)stream { + _FIRMessagingDevAssert(stream != nil, @"Invalid stream"); + _FIRMessagingDevAssert(self.runLoop != nil, @"Invalid runloop"); + + if (stream) { + [stream close]; + [stream removeFromRunLoop:self.runLoop forMode:NSDefaultRunLoopMode]; + stream.delegate = nil; + } +} + +- (BOOL)performRead { + _FIRMessagingDevAssert(self.state == kFIRMessagingSecureSocketOpen, @"Socket should be open"); + + if (!self.isVersionReceived) { + self.isVersionReceived = YES; + uint8_t versionByte = 0; + NSInteger bytesRead = [self.inStream read:&versionByte maxLength:sizeof(uint8_t)]; + if (bytesRead != sizeof(uint8_t) || kVersion != versionByte) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket010, + @"Version do not match. Received %d, Expecting %d", versionByte, + kVersion); + return NO; + } + } + + while (YES) { + BOOL isInputBufferValid = [self.inputBuffer length] > 0; + _FIRMessagingDevAssert(isInputBufferValid, + @"Invalid input buffer size %lu. Used bytes length %lu, buffer content: %@", + _FIRMessaging_UL([self.inputBuffer length]), + _FIRMessaging_UL(self.inputBufferLength), + self.inputBuffer); + if (!isInputBufferValid) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket011, + @"Input buffer is not valid."); + return NO; + } + + if (![self.inStream hasBytesAvailable]) { + break; + } + + // try to read more data + uint8_t *unusedBufferPtr = (uint8_t *)self.inputBuffer.mutableBytes + self.inputBufferLength; + NSUInteger unusedBufferLength = [self.inputBuffer length] - self.inputBufferLength; + NSInteger bytesRead = [self.inStream read:unusedBufferPtr maxLength:unusedBufferLength]; + if (bytesRead <= 0) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket012, + @"Failed to read input stream. Bytes read %ld, Used buffer size %lu, " + @"Unused buffer size %lu", + _FIRMessaging_UL(bytesRead), _FIRMessaging_UL(self.inputBufferLength), + _FIRMessaging_UL(unusedBufferLength)); + break; + } + // did successfully read some more data + self.inputBufferLength += (NSUInteger)bytesRead; + + if ([self.inputBuffer length] <= self.inputBufferLength) { + // shouldn't be reading more than 1MB of data in one go + if ([self.inputBuffer length] + kBufferLengthIncrement > kMaxBufferLength) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket013, + @"Input buffer exceed 1M, disconnect socket"); + return NO; + } + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket014, + @"Input buffer limit exceeded. Used input buffer size %lu, " + @"Total input buffer size %lu. No unused buffer left. " + @"Increase buffer size.", + _FIRMessaging_UL(self.inputBufferLength), + _FIRMessaging_UL([self.inputBuffer length])); + [self.inputBuffer increaseLengthBy:kBufferLengthIncrement]; + _FIRMessagingDevAssert([self.inputBuffer length] > self.inputBufferLength, @"Invalid buffer size"); + } + + while (self.inputBufferLength > 0 && [self.inputBuffer length] > 0) { + _FIRMessagingDevAssert([self.inputBuffer length] >= self.inputBufferLength, + @"Buffer longer than length"); + NSRange inputRange = NSMakeRange(0, self.inputBufferLength); + size_t protoBytes = 0; + // read the actual proto data coming in + FIRMessagingSecureSocketReadResult readResult = + [self processCurrentInputBuffer:[self.inputBuffer subdataWithRange:inputRange] + outOffset:&protoBytes]; + // Corrupt data encountered, stop processing. + if (readResult == kFIRMessagingSecureSocketReadResultCorrupt) { + return NO; + // Incomplete data, keep trying to read by loading more from the stream. + } else if (readResult == kFIRMessagingSecureSocketReadResultIncomplete) { + break; + } + _FIRMessagingDevAssert(self.inputBufferLength >= protoBytes, @"More bytes than buffer can handle"); + // we have read (0, protoBytes) of data in the inputBuffer + if (protoBytes == self.inputBufferLength) { + // did completely read the buffer data can be reset for further processing + self.inputBufferLength = 0; + } else { + // delete processed bytes while maintaining the buffer size. + NSUInteger prevLength __unused = [self.inputBuffer length]; + // delete the processed bytes + [self.inputBuffer replaceBytesInRange:NSMakeRange(0, protoBytes) withBytes:NULL length:0]; + // reallocate more data + [self.inputBuffer increaseLengthBy:protoBytes]; + _FIRMessagingDevAssert([self.inputBuffer length] == prevLength, + @"Invalid input buffer size %lu. Used bytes length %lu, " + @"buffer content: %@", + _FIRMessaging_UL([self.inputBuffer length]), + _FIRMessaging_UL(self.inputBufferLength), + self.inputBuffer); + self.inputBufferLength -= protoBytes; + } + } + } + return YES; +} + +- (FIRMessagingSecureSocketReadResult)processCurrentInputBuffer:(NSData *)readData + outOffset:(size_t *)outOffset { + *outOffset = 0; + + FIRMessagingCodedInputStream *input = [[FIRMessagingCodedInputStream alloc] initWithData:readData]; + int8_t rawTag; + if (![input readTag:&rawTag]) { + return kFIRMessagingSecureSocketReadResultIncomplete; + } + int32_t length; + if (![input readLength:&length]) { + return kFIRMessagingSecureSocketReadResultIncomplete; + } + // NOTE tag can be zero for |HeartbeatPing|, and length can be zero for |Close| proto + _FIRMessagingDevAssert(rawTag >= 0 && length >= 0, @"Invalid tag or length"); + if (rawTag < 0 || length < 0) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket015, @"Buffer data corrupted."); + return kFIRMessagingSecureSocketReadResultCorrupt; + } + NSData *data = [input readDataWithLength:(uint32_t)length]; + if (data == nil) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSecureSocket016, + @"Incomplete data, buffered data length %ld, expected length %d", + _FIRMessaging_UL(self.inputBufferLength), length); + return kFIRMessagingSecureSocketReadResultIncomplete; + } + [self.delegate secureSocket:self didReceiveData:data withTag:rawTag]; + *outOffset = input.offset; + return kFIRMessagingSecureSocketReadResultSuccess; +} + +- (void)performWrite { + _FIRMessagingDevAssert(self.state == kFIRMessagingSecureSocketOpen, @"Invalid socket state"); + + if (!self.isVersionSent) { + self.isVersionSent = YES; + uint8_t versionByte = kVersion; + [self.outStream write:&versionByte maxLength:sizeof(uint8_t)]; + } + + while (!self.packetQueue.isEmpty && self.outStream.hasSpaceAvailable) { + if (self.outputBuffer.length == 0) { + // serialize new packets only when the output buffer is flushed. + FIRMessagingPacket *packet = [self.packetQueue pop]; + self.currentRmqIdBeingSent = packet.rmqId; + self.currentProtoTypeBeingSent = packet.tag; + NSUInteger length = SerializedSize(packet.tag) + + SerializedSize((int)packet.data.length) + packet.data.length; + self.outputBuffer = [NSMutableData dataWithLength:length]; + GPBCodedOutputStream *output = [GPBCodedOutputStream streamWithData:self.outputBuffer]; + [output writeRawVarint32:packet.tag]; + [output writeBytesNoTag:packet.data]; + self.outputBufferLength = 0; + } + + // flush the output buffer. + NSInteger written = [self.outStream write:self.outputBuffer.bytes + self.outputBufferLength + maxLength:self.outputBuffer.length - self.outputBufferLength]; + if (written <= 0) { + continue; + } + self.outputBufferLength += (NSUInteger)written; + if (self.outputBufferLength >= self.outputBuffer.length) { + self.outputBufferLength = 0; + self.outputBuffer = nil; + [self.delegate secureSocket:self + didSendProtoWithTag:self.currentProtoTypeBeingSent + rmqId:self.currentRmqIdBeingSent]; + self.currentRmqIdBeingSent = nil; + self.currentProtoTypeBeingSent = kInvalidTag; + } + } +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.h new file mode 100644 index 0000000..3d30bdb --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.h @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRMessagingRmqManager; + +/** + * Handle sync messages being received both via MCS and APNS. + */ +@interface FIRMessagingSyncMessageManager : NSObject + +/** + * Initialize sync message manager. + * + * @param rmqManager The RMQ manager on the client. + * + * @return Sync message manager. + */ +- (instancetype)initWithRmqManager:(FIRMessagingRmqManager *)rmqManager; + +/** + * Remove expired sync message from persistent store. Also removes messages that have + * been received both via APNS and MCS. + */ +- (void)removeExpiredSyncMessages; + +/** + * App did recive a sync message via APNS. + * + * @param message The sync message received. + * + * @return YES if the message is a duplicate of an already received sync message else NO. + */ +- (BOOL)didReceiveAPNSSyncMessage:(NSDictionary *)message; + +/** + * App did receive a sync message via MCS. + * + * @param message The sync message received. + * + * @return YES if the message is a duplicate of an already received sync message else NO. + */ +- (BOOL)didReceiveMCSSyncMessage:(NSDictionary *)message; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.m new file mode 100644 index 0000000..1257b02 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingSyncMessageManager.m @@ -0,0 +1,147 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingSyncMessageManager.h" + +#import "FIRMessagingConstants.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingPersistentSyncMessage.h" +#import "FIRMessagingRmqManager.h" +#import "FIRMessagingUtilities.h" + +static const int64_t kDefaultSyncMessageTTL = 4 * 7 * 24 * 60 * 60; // 4 weeks +// 4 MB of free space is required to persist Sync messages +static const uint64_t kMinFreeDiskSpaceInMB = 1; + +@interface FIRMessagingSyncMessageManager() + +@property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmqManager; + +@end + +@implementation FIRMessagingSyncMessageManager + +- (instancetype)init { + FIRMessagingInvalidateInitializer(); +} + +- (instancetype)initWithRmqManager:(FIRMessagingRmqManager *)rmqManager { + _FIRMessagingDevAssert(rmqManager, @"Invalid nil rmq manager while initalizing sync message manager"); + self = [super init]; + if (self) { + _rmqManager = rmqManager; + } + return self; +} + +- (void)removeExpiredSyncMessages { + NSError *error; + int deleteCount = [self.rmqManager deleteExpiredOrFinishedSyncMessages:&error]; + if (error) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager000, + @"Error while deleting expired sync messages %@", error); + } else if (deleteCount > 0) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSyncMessageManager001, + @"Successfully deleted %d sync messages from store", deleteCount); + } +} + +- (BOOL)didReceiveAPNSSyncMessage:(NSDictionary *)message { + return [self didReceiveSyncMessage:message viaAPNS:YES viaMCS:NO]; +} + +- (BOOL)didReceiveMCSSyncMessage:(NSDictionary *)message { + return [self didReceiveSyncMessage:message viaAPNS:NO viaMCS:YES]; +} + +- (BOOL)didReceiveSyncMessage:(NSDictionary *)message + viaAPNS:(BOOL)viaAPNS + viaMCS:(BOOL)viaMCS { + NSString *rmqID = message[kFIRMessagingMessageIDKey]; + _FIRMessagingDevAssert([rmqID length], @"Invalid nil rmqID for message"); + if (![rmqID length]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager002, + @"Invalid nil rmqID for sync message."); + return NO; + } + + FIRMessagingPersistentSyncMessage *persistentMessage = + [self.rmqManager querySyncMessageWithRmqID:rmqID]; + + NSError *error; + if (!persistentMessage) { + + // Do not persist the new message if we don't have enough disk space + uint64_t freeDiskSpace = FIRMessagingGetFreeDiskSpaceInMB(); + if (freeDiskSpace < kMinFreeDiskSpaceInMB) { + return NO; + } + + int64_t expirationTime = [[self class] expirationTimeForSyncMessage:message]; + if (![self.rmqManager saveSyncMessageWithRmqID:rmqID + expirationTime:expirationTime + apnsReceived:viaAPNS + mcsReceived:viaMCS + error:&error]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager003, + @"Failed to save sync message with rmqID %@", rmqID); + } else { + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager004, + @"Added sync message to cache: %@", rmqID); + } + return NO; + } + + if (viaAPNS && !persistentMessage.apnsReceived) { + persistentMessage.apnsReceived = YES; + if (![self.rmqManager updateSyncMessageViaAPNSWithRmqID:rmqID error:&error]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager005, + @"Failed to update APNS state for sync message %@", rmqID); + } + } else if (viaMCS && !persistentMessage.mcsReceived) { + persistentMessage.mcsReceived = YES; + if (![self.rmqManager updateSyncMessageViaMCSWithRmqID:rmqID error:&error]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager006, + @"Failed to update MCS state for sync message %@", rmqID); + } + } + + // Received message via both ways we can safely delete it. + if (persistentMessage.apnsReceived && persistentMessage.mcsReceived) { + if (![self.rmqManager deleteSyncMessageWithRmqID:rmqID]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager007, + @"Failed to delete sync message %@", rmqID); + } else { + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager008, + @"Successfully deleted sync message from cache %@", rmqID); + } + } + + // Already received this message either via MCS or APNS. + return YES; +} + ++ (int64_t)expirationTimeForSyncMessage:(NSDictionary *)message { + int64_t ttl = kDefaultSyncMessageTTL; + if (message[kFIRMessagingMessageSyncMessageTTLKey]) { + ttl = [message[kFIRMessagingMessageSyncMessageTTLKey] longLongValue]; + } + int64_t currentTime = FIRMessagingCurrentTimestampInSeconds(); + return currentTime + ttl; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.h new file mode 100644 index 0000000..ea98e6d --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRMessaging.h" +#import "FIRMessagingCheckinService.h" +#import "FIRMessagingTopicsCommon.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * An asynchronous NSOperation subclass which performs a single network request for a topic + * subscription operation. Once completed, it calls its provided completion handler. + */ +@interface FIRMessagingTopicOperation : NSOperation + +@property(nonatomic, readonly, copy) NSString *topic; +@property(nonatomic, readonly, assign) FIRMessagingTopicAction action; +@property(nonatomic, readonly, copy) NSString *token; +@property(nonatomic, readonly, copy, nullable) NSDictionary *options; +@property(nonatomic, readonly, strong) FIRMessagingCheckinService *checkinService; + +- (instancetype)initWithTopic:(NSString *)topic + action:(FIRMessagingTopicAction)action + token:(NSString *)token + options:(nullable NSDictionary *)options + checkinService:(FIRMessagingCheckinService *)checkinService + completion:(FIRMessagingTopicOperationCompletion)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.m new file mode 100644 index 0000000..6703178 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicOperation.m @@ -0,0 +1,263 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingTopicOperation.h" + +#import "FIRMessagingCheckinService.h" +#import "FIRMessagingDefines.h" +#import "FIRMessagingLogger.h" +#import "FIRMessagingUtilities.h" +#import "NSError+FIRMessaging.h" + +#define DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS 0 + +static NSString *const kFIRMessagingSubscribeServerHost = + @"https://iid.googleapis.com/iid/register"; + +NSString *FIRMessagingSubscriptionsServer() { + static NSString *serverHost = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSDictionary *environment = [[NSProcessInfo processInfo] environment]; + NSString *customServerHost = environment[@"FCM_SERVER_ENDPOINT"]; + if (customServerHost.length) { + serverHost = customServerHost; + } else { + serverHost = kFIRMessagingSubscribeServerHost; + } + }); + return serverHost; +} + +@interface FIRMessagingTopicOperation () { + BOOL _isFinished; + BOOL _isExecuting; +} + +@property(nonatomic, readwrite, copy) NSString *topic; +@property(nonatomic, readwrite, assign) FIRMessagingTopicAction action; +@property(nonatomic, readwrite, copy) NSString *token; +@property(nonatomic, readwrite, copy) NSDictionary *options; +@property(nonatomic, readwrite, strong) FIRMessagingCheckinService *checkinService; +@property(nonatomic, readwrite, copy) FIRMessagingTopicOperationCompletion completion; + +@property(atomic, strong) NSURLSessionDataTask *dataTask; + +@end + +@implementation FIRMessagingTopicOperation + ++ (NSURLSession *)sharedSession { + static NSURLSession *subscriptionOperationSharedSession; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; + config.timeoutIntervalForResource = 60.0f; // 1 minute + subscriptionOperationSharedSession = [NSURLSession sessionWithConfiguration:config]; + subscriptionOperationSharedSession.sessionDescription = @"com.google.fcm.topics.session"; + }); + return subscriptionOperationSharedSession; +} + +- (instancetype)initWithTopic:(NSString *)topic + action:(FIRMessagingTopicAction)action + token:(NSString *)token + options:(NSDictionary *)options + checkinService:(FIRMessagingCheckinService *)checkinService + completion:(FIRMessagingTopicOperationCompletion)completion { + if (self = [super init]) { + _topic = topic; + _action = action; + _token = token; + _options = options; + _checkinService = checkinService; + _completion = completion; + + _isExecuting = NO; + _isFinished = NO; + } + return self; +} + +- (void)dealloc { + _topic = nil; + _token = nil; + _checkinService = nil; + _completion = nil; +} + +- (BOOL)isAsynchronous { + return YES; +} + +- (BOOL)isExecuting { + return _isExecuting; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _isExecuting = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isFinished { + return _isFinished; +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _isFinished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)start { + if (self.isCancelled) { + NSError *error = + [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled]; + [self finishWithError:error]; + return; + } + + [self setExecuting:YES]; + + [self performSubscriptionChange]; +} + +- (void)finishWithError:(NSError *)error { + // Add a check to prevent this finish from being called more than once. + if (self.isFinished) { + return; + } + self.dataTask = nil; + if (self.completion) { + self.completion(error); + } + + [self setExecuting:NO]; + [self setFinished:YES]; +} + +- (void)cancel { + [super cancel]; + [self.dataTask cancel]; + NSError *error = [NSError errorWithFCMErrorCode:kFIRMessagingErrorCodePubSubOperationIsCancelled]; + [self finishWithError:error]; +} + +- (void)performSubscriptionChange { + + NSURL *url = [NSURL URLWithString:FIRMessagingSubscriptionsServer()]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + NSString *appIdentifier = FIRMessagingAppIdentifier(); + NSString *deviceAuthID = self.checkinService.deviceAuthID; + NSString *secretToken = self.checkinService.secretToken; + NSString *authString = [NSString stringWithFormat:@"AidLogin %@:%@", deviceAuthID, secretToken]; + [request setValue:authString forHTTPHeaderField:@"Authorization"]; + [request setValue:appIdentifier forHTTPHeaderField:@"app"]; + [request setValue:self.checkinService.versionInfo forHTTPHeaderField:@"info"]; + + // Topic can contain special characters (like `%`) so encode the value. + NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet]; + NSString *encodedTopic = + [self.topic stringByAddingPercentEncodingWithAllowedCharacters:characterSet]; + if (encodedTopic == nil) { + // The transformation was somehow not possible, so use the original topic. + FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicOptionTopicEncodingFailed, + @"Unable to encode the topic '%@' during topic subscription change. " + @"Please ensure that the topic name contains only valid characters.", + self.topic); + encodedTopic = self.topic; + } + + NSMutableString *content = [NSMutableString stringWithFormat: + @"sender=%@&app=%@&device=%@&" + @"app_ver=%@&X-gcm.topic=%@&X-scope=%@", + self.token, + appIdentifier, + deviceAuthID, + FIRMessagingCurrentAppVersion(), + encodedTopic, + encodedTopic]; + + if (self.action == FIRMessagingTopicActionUnsubscribe) { + [content appendString:@"&delete=true"]; + } + + FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTopicOption000, @"Topic subscription request: %@", + content); + + request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding]; + [request setHTTPMethod:@"POST"]; + +#if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS + NSDate *start = [NSDate date]; +#endif + + FIRMessaging_WEAKIFY(self) + void(^requestHandler)(NSData *, NSURLResponse *, NSError *) = + ^(NSData *data, NSURLResponse *URLResponse, NSError *error) { + FIRMessaging_STRONGIFY(self) + if (error) { + // Our operation could have been cancelled, which would result in our data task's error being + // NSURLErrorCancelled + if (error.code == NSURLErrorCancelled) { + // We would only have been cancelled in the -cancel method, which will call finish for us + // so just return and do nothing. + return; + } + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption001, + @"Device registration HTTP fetch error. Error Code: %ld", + _FIRMessaging_L(error.code)); + [self finishWithError:error]; + return; + } + NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (response.length == 0) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOperationEmptyResponse, + @"Invalid registration response - zero length."); + [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]]; + return; + } + NSArray *parts = [response componentsSeparatedByString:@"="]; + _FIRMessagingDevAssert(parts.count, @"Invalid registration response"); + if (![parts[0] isEqualToString:@"token"] || parts.count <= 1) { + FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTopicOption002, + @"Invalid registration response %@", response); + [self finishWithError:[NSError errorWithFCMErrorCode:kFIRMessagingErrorCodeUnknown]]; + return; + } +#if DEBUG_LOG_SUBSCRIPTION_OPERATION_DURATIONS + NSTimeInterval duration = -[start timeIntervalSinceNow]; + FIRMessagingLoggerDebug(@"%@ change took %.2fs", self.topic, duration); +#endif + [self finishWithError:nil]; + + }; + + NSURLSession *urlSession = [FIRMessagingTopicOperation sharedSession]; + + self.dataTask = [urlSession dataTaskWithRequest:request completionHandler:requestHandler]; + NSString *description; + if (_action == FIRMessagingTopicActionSubscribe) { + description = [NSString stringWithFormat:@"com.google.fcm.topics.subscribe: %@", _topic]; + } else { + description = [NSString stringWithFormat:@"com.google.fcm.topics.unsubscribe: %@", _topic]; + } + self.dataTask.taskDescription = description; + [self.dataTask resume]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicsCommon.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicsCommon.h new file mode 100644 index 0000000..030b3ff --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingTopicsCommon.h @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Represents the action taken on a subscription topic. + */ +typedef NS_ENUM(NSInteger, FIRMessagingTopicAction) { + FIRMessagingTopicActionSubscribe, + FIRMessagingTopicActionUnsubscribe +}; + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.h new file mode 100644 index 0000000..206ff07 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.h @@ -0,0 +1,58 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +typedef NS_ENUM(int8_t, FIRMessagingProtoTag) { + kFIRMessagingProtoTagInvalid = -1, + kFIRMessagingProtoTagHeartbeatPing = 0, + kFIRMessagingProtoTagHeartbeatAck = 1, + kFIRMessagingProtoTagLoginRequest = 2, + kFIRMessagingProtoTagLoginResponse = 3, + kFIRMessagingProtoTagClose = 4, + kFIRMessagingProtoTagIqStanza = 7, + kFIRMessagingProtoTagDataMessageStanza = 8, +}; + +@class GPBMessage; + +#pragma mark - Protocol Buffers + +FOUNDATION_EXPORT FIRMessagingProtoTag FIRMessagingGetTagForProto(GPBMessage *protoClass); +FOUNDATION_EXPORT Class FIRMessagingGetClassForTag(FIRMessagingProtoTag tag); + +#pragma mark - MCS + +FOUNDATION_EXPORT NSString *FIRMessagingGetRmq2Id(GPBMessage *proto); +FOUNDATION_EXPORT void FIRMessagingSetRmq2Id(GPBMessage *proto, NSString *pID); +FOUNDATION_EXPORT int FIRMessagingGetLastStreamId(GPBMessage *proto); +FOUNDATION_EXPORT void FIRMessagingSetLastStreamId(GPBMessage *proto, int sid); + +#pragma mark - Time + +FOUNDATION_EXPORT int64_t FIRMessagingCurrentTimestampInSeconds(void); +FOUNDATION_EXPORT int64_t FIRMessagingCurrentTimestampInMilliseconds(void); + +#pragma mark - App Info + +FOUNDATION_EXPORT NSString *FIRMessagingCurrentAppVersion(void); +FOUNDATION_EXPORT NSString *FIRMessagingAppIdentifier(void); + +#pragma mark - Others + +FOUNDATION_EXPORT uint64_t FIRMessagingGetFreeDiskSpaceInMB(void); +FOUNDATION_EXPORT UIApplication *FIRMessagingUIApplication(void); + diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.m new file mode 100644 index 0000000..fa3a233 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingUtilities.m @@ -0,0 +1,188 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingUtilities.h" + +#import "Protos/GtalkCore.pbobjc.h" + +#import "FIRMessagingLogger.h" + +#import + +// Convert the macro to a string +#define STR_EXPAND(x) #x +#define STR(x) STR_EXPAND(x) + +static const uint64_t kBytesToMegabytesDivisor = 1024 * 1024LL; + +#pragma mark - Protocol Buffers + +FIRMessagingProtoTag FIRMessagingGetTagForProto(GPBMessage *proto) { + if ([proto isKindOfClass:[GtalkHeartbeatPing class]]) { + return kFIRMessagingProtoTagHeartbeatPing; + } else if ([proto isKindOfClass:[GtalkHeartbeatAck class]]) { + return kFIRMessagingProtoTagHeartbeatAck; + } else if ([proto isKindOfClass:[GtalkLoginRequest class]]) { + return kFIRMessagingProtoTagLoginRequest; + } else if ([proto isKindOfClass:[GtalkLoginResponse class]]) { + return kFIRMessagingProtoTagLoginResponse; + } else if ([proto isKindOfClass:[GtalkClose class]]) { + return kFIRMessagingProtoTagClose; + } else if ([proto isKindOfClass:[GtalkIqStanza class]]) { + return kFIRMessagingProtoTagIqStanza; + } else if ([proto isKindOfClass:[GtalkDataMessageStanza class]]) { + return kFIRMessagingProtoTagDataMessageStanza; + } + return kFIRMessagingProtoTagInvalid; +} + +Class FIRMessagingGetClassForTag(FIRMessagingProtoTag tag) { + switch (tag) { + case kFIRMessagingProtoTagHeartbeatPing: + return GtalkHeartbeatPing.class; + case kFIRMessagingProtoTagHeartbeatAck: + return GtalkHeartbeatAck.class; + case kFIRMessagingProtoTagLoginRequest: + return GtalkLoginRequest.class; + case kFIRMessagingProtoTagLoginResponse: + return GtalkLoginResponse.class; + case kFIRMessagingProtoTagClose: + return GtalkClose.class; + case kFIRMessagingProtoTagIqStanza: + return GtalkIqStanza.class; + case kFIRMessagingProtoTagDataMessageStanza: + return GtalkDataMessageStanza.class; + case kFIRMessagingProtoTagInvalid: + return NSNull.class; + } + return NSNull.class; +} + +#pragma mark - MCS + +NSString *FIRMessagingGetRmq2Id(GPBMessage *proto) { + if ([proto isKindOfClass:[GtalkIqStanza class]]) { + if (((GtalkIqStanza *)proto).hasPersistentId) { + return ((GtalkIqStanza *)proto).persistentId; + } + } else if ([proto isKindOfClass:[GtalkDataMessageStanza class]]) { + if (((GtalkDataMessageStanza *)proto).hasPersistentId) { + return ((GtalkDataMessageStanza *)proto).persistentId; + } + } + return nil; +} + +void FIRMessagingSetRmq2Id(GPBMessage *proto, NSString *pID) { + if ([proto isKindOfClass:[GtalkIqStanza class]]) { + ((GtalkIqStanza *)proto).persistentId = pID; + } else if ([proto isKindOfClass:[GtalkDataMessageStanza class]]) { + ((GtalkDataMessageStanza *)proto).persistentId = pID; + } +} + +int FIRMessagingGetLastStreamId(GPBMessage *proto) { + if ([proto isKindOfClass:[GtalkIqStanza class]]) { + if (((GtalkIqStanza *)proto).hasLastStreamIdReceived) { + return ((GtalkIqStanza *)proto).lastStreamIdReceived; + } + } else if ([proto isKindOfClass:[GtalkDataMessageStanza class]]) { + if (((GtalkDataMessageStanza *)proto).hasLastStreamIdReceived) { + return ((GtalkDataMessageStanza *)proto).lastStreamIdReceived; + } + } else if ([proto isKindOfClass:[GtalkHeartbeatPing class]]) { + if (((GtalkHeartbeatPing *)proto).hasLastStreamIdReceived) { + return ((GtalkHeartbeatPing *)proto).lastStreamIdReceived; + } + } else if ([proto isKindOfClass:[GtalkHeartbeatAck class]]) { + if (((GtalkHeartbeatAck *)proto).hasLastStreamIdReceived) { + return ((GtalkHeartbeatAck *)proto).lastStreamIdReceived; + } + } + return -1; +} + +void FIRMessagingSetLastStreamId(GPBMessage *proto, int sid) { + if ([proto isKindOfClass:[GtalkIqStanza class]]) { + ((GtalkIqStanza *)proto).lastStreamIdReceived = sid; + } else if ([proto isKindOfClass:[GtalkDataMessageStanza class]]) { + ((GtalkDataMessageStanza *)proto).lastStreamIdReceived = sid; + } else if ([proto isKindOfClass:[GtalkHeartbeatPing class]]) { + ((GtalkHeartbeatPing *)proto).lastStreamIdReceived = sid; + } else if ([proto isKindOfClass:[GtalkHeartbeatAck class]]) { + ((GtalkHeartbeatAck *)proto).lastStreamIdReceived = sid; + } +} + +#pragma mark - Time + +int64_t FIRMessagingCurrentTimestampInSeconds(void) { + return (int64_t)[[NSDate date] timeIntervalSince1970]; +} + +int64_t FIRMessagingCurrentTimestampInMilliseconds(void) { + return (int64_t)(FIRMessagingCurrentTimestampInSeconds() * 1000.0); +} + +#pragma mark - App Info + +NSString *FIRMessagingCurrentAppVersion(void) { + NSString *version = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"]; + if (![version length]) { + FIRMessagingLoggerError(kFIRMessagingMessageCodeUtilities000, + @"Could not find current app version"); + return @""; + } + return version; +} + +NSString *FIRMessagingAppIdentifier(void) { + return [[NSBundle mainBundle] bundleIdentifier]; +} + +uint64_t FIRMessagingGetFreeDiskSpaceInMB(void) { + NSError *error; + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + + NSDictionary *attributesMap = + [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] + error:&error]; + if (attributesMap) { + uint64_t totalSizeInBytes __unused = [attributesMap[NSFileSystemSize] longLongValue]; + uint64_t freeSizeInBytes = [attributesMap[NSFileSystemFreeSize] longLongValue]; + FIRMessagingLoggerDebug( + kFIRMessagingMessageCodeUtilities001, @"Device has capacity %llu MB with %llu MB free.", + totalSizeInBytes / kBytesToMegabytesDivisor, freeSizeInBytes / kBytesToMegabytesDivisor); + return ((double)freeSizeInBytes) / kBytesToMegabytesDivisor; + } else { + FIRMessagingLoggerError(kFIRMessagingMessageCodeUtilities002, + @"Error in retreiving device's free memory %@", error); + return 0; + } +} + +UIApplication *FIRMessagingUIApplication(void) { + static Class applicationClass = nil; + // iOS App extensions should not call [UIApplication sharedApplication], even if UIApplication + // responds to it. + if (![GULAppEnvironmentUtil isAppExtension]) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + return [applicationClass sharedApplication]; +} diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.h new file mode 100644 index 0000000..cd292af --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/** + * Parsing utility for FIRMessaging Library versions. FIRMessaging Library follows semantic versioning. + * This provides utilities to parse the library versions to enable features and do + * updates based on appropriate library versions. + * + * Some example semantic versions are 1.0.1, 2.1.0, 2.1.1, 2.2.0-alpha1, 2.2.1-beta1 + */ + +FOUNDATION_EXPORT NSString *FIRMessagingCurrentLibraryVersion(void); +/// Returns the current Major version of FIRMessaging library. +FOUNDATION_EXPORT int FIRMessagingCurrentLibraryVersionMajor(void); +/// Returns the current Minor version of FIRMessaging library. +FOUNDATION_EXPORT int FIRMessagingCurrentLibraryVersionMinor(void); +/// Returns the current Patch version of FIRMessaging library. +FOUNDATION_EXPORT int FIRMessagingCurrentLibraryVersionPatch(void); +/// Returns YES if current library version is `beta` else NO. +FOUNDATION_EXPORT BOOL FIRMessagingCurrentLibraryVersionIsBeta(void); diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.m new file mode 100644 index 0000000..1a3333c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessagingVersionUtilities.m @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessagingVersionUtilities.h" + +#import "FIRMessagingDefines.h" + +// Convert the macro to a string +#define STR_EXPAND(x) #x +#define STR(x) STR_EXPAND(x) + +static NSString *const kSemanticVersioningSeparator = @"."; +static NSString *const kBetaVersionPrefix = @"-beta"; + +static NSString *libraryVersion; +static int majorVersion; +static int minorVersion; +static int patchVersion; +static int betaVersion; + +void FIRMessagingParseCurrentLibraryVersion(void) { + static NSArray *allVersions; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSMutableString *daylightVersion = [NSMutableString stringWithUTF8String:STR(FIRMessaging_LIB_VERSION)]; + // Parse versions + // major, minor, patch[-beta#] + allVersions = [daylightVersion componentsSeparatedByString:kSemanticVersioningSeparator]; + _FIRMessagingDevAssert(allVersions.count == 3, @"Invalid versioning of FIRMessaging library"); + if (allVersions.count == 3) { + majorVersion = [allVersions[0] intValue]; + minorVersion = [allVersions[1] intValue]; + + // Parse patch and beta versions + NSArray *patchAndBetaVersion = + [allVersions[2] componentsSeparatedByString:kBetaVersionPrefix]; + _FIRMessagingDevAssert(patchAndBetaVersion.count <= 2, @"Invalid versioning of FIRMessaging library"); + if (patchAndBetaVersion.count == 2) { + patchVersion = [patchAndBetaVersion[0] intValue]; + betaVersion = [patchAndBetaVersion[1] intValue]; + } else if (patchAndBetaVersion.count == 1) { + patchVersion = [patchAndBetaVersion[0] intValue]; + } + } + + // Copy library version + libraryVersion = [daylightVersion copy]; + }); +} + +NSString *FIRMessagingCurrentLibraryVersion(void) { + FIRMessagingParseCurrentLibraryVersion(); + return libraryVersion; +} + +int FIRMessagingCurrentLibraryVersionMajor(void) { + FIRMessagingParseCurrentLibraryVersion(); + return majorVersion; +} + +int FIRMessagingCurrentLibraryVersionMinor(void) { + FIRMessagingParseCurrentLibraryVersion(); + return minorVersion; +} + +int FIRMessagingCurrentLibraryVersionPatch(void) { + FIRMessagingParseCurrentLibraryVersion(); + return patchVersion; +} + +BOOL FIRMessagingCurrentLibraryVersionIsBeta(void) { + FIRMessagingParseCurrentLibraryVersion(); + return betaVersion > 0; +} diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging_Private.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging_Private.h new file mode 100644 index 0000000..0a95a50 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging_Private.h @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" + +@class FIRMessagingClient; +@class FIRMessagingPubSub; + +typedef NS_ENUM(int8_t, FIRMessagingNetworkStatus) { + kFIRMessagingReachabilityNotReachable = 0, + kFIRMessagingReachabilityReachableViaWiFi, + kFIRMessagingReachabilityReachableViaWWAN, +}; + +FOUNDATION_EXPORT NSString *const kFIRMessagingPlistAutoInitEnabled; +FOUNDATION_EXPORT NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled; +FOUNDATION_EXPORT NSString *const kFIRMessagingUserDefaultsKeyUseMessagingDelegate; +FOUNDATION_EXPORT NSString *const kFIRMessagingPlistUseMessagingDelegate; + +@interface FIRMessagingRemoteMessage () + +@property(nonatomic, copy) NSString *messageID; +@property(nonatomic, strong) NSDictionary *appData; + +@end + +@interface FIRMessaging () + +#pragma mark - Private API + +- (NSString *)defaultFcmToken; +- (FIRMessagingClient *)client; +- (FIRMessagingPubSub *)pubsub; + +// Create a sample message to be sent over the wire using FIRMessaging. Look at +// FIRMessagingService.h to see what each param signifies. ++ (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message + to:(NSString *)to + withID:(NSString *)msgID + timeToLive:(int64_t)ttl + delay:(int)delay; + +- (BOOL)isNetworkAvailable; +- (FIRMessagingNetworkStatus)networkType; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FirebaseMessaging.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FirebaseMessaging.h new file mode 100644 index 0000000..ef081c9 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/FirebaseMessaging.h @@ -0,0 +1,17 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/InternalHeaders/FIRMessagingInternalUtilities.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/InternalHeaders/FIRMessagingInternalUtilities.h new file mode 100644 index 0000000..d6a1639 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/InternalHeaders/FIRMessagingInternalUtilities.h @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// @file FIRMessagingInternalUtilities.h +/// +/// Internal Class Names and Methods that other libs can query at runtime. + +/// FIRMessaging Class that responds to the FIRMessaging SDK version selector. +/// Verify at runtime if the class exists and implements the +/// required method. +static NSString *const kFIRMessagingSDKClassString = @"FIRMessaging"; + +/// FIRMessaging selector that returns the current FIRMessaging library version. +static NSString *const kFIRMessagingSDKVersionSelectorString = @"FIRMessagingSDKVersion"; + +/// FIRMessaging selector that returns the current device locale. +static NSString *const kFIRMessagingSDKLocaleSelectorString = @"FIRMessagingSDKCurrentLocale"; diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.h new file mode 100644 index 0000000..fe14451 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface NSDictionary (FIRMessaging) + +/** + * Returns a string representation for the given dictionary. Assumes that all + * keys and values are strings. + * + * @return A string representation of all keys and values in the dictionary. + * The returned string is not pretty-printed. + */ +- (NSString *)fcm_string; + +/** + * Check if the dictionary has any non-string keys or values. + * + * @return YES if the dictionary has any non-string keys or values else NO. + */ +- (BOOL)fcm_hasNonStringKeysOrValues; + +/** + * Trims all (key, value) pair in a dictionary that are not strings. + * + * @return A new copied dictionary with all the non-string keys or values + * removed from the original dictionary. + */ +- (NSDictionary *)fcm_trimNonStringValues; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.m new file mode 100644 index 0000000..8df22ab --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSDictionary+FIRMessaging.m @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "NSDictionary+FIRMessaging.h" + +@implementation NSDictionary (FIRMessaging) + +- (NSString *)fcm_string { + NSMutableString *dictAsString = [NSMutableString string]; + NSString *separator = @"|"; + for (id key in self) { + id value = self[key]; + if ([key isKindOfClass:[NSString class]] && [value isKindOfClass:[NSString class]]) { + [dictAsString appendFormat:@"%@:%@%@", key, value, separator]; + } + } + // remove the last separator + if ([dictAsString length]) { + [dictAsString deleteCharactersInRange:NSMakeRange(dictAsString.length - 1, 1)]; + } + return [dictAsString copy]; +} + +- (BOOL)fcm_hasNonStringKeysOrValues { + for (id key in self) { + id value = self[key]; + if (![key isKindOfClass:[NSString class]] || ![value isKindOfClass:[NSString class]]) { + return YES; + } + } + return NO; +} + +- (NSDictionary *)fcm_trimNonStringValues { + NSMutableDictionary *trimDictionary = + [NSMutableDictionary dictionaryWithCapacity:self.count]; + for (id key in self) { + id value = self[key]; + if ([key isKindOfClass:[NSString class]] && [value isKindOfClass:[NSString class]]) { + trimDictionary[(NSString *)key] = value; + } + } + return trimDictionary; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.h new file mode 100644 index 0000000..ae25b5b --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.h @@ -0,0 +1,69 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +FOUNDATION_EXPORT NSString *const kFIRMessagingDomain; + +typedef NS_ENUM(NSUInteger, FIRMessagingInternalErrorCode) { + // Unknown error. + kFIRMessagingErrorCodeUnknown = 0, + + // HTTP related errors. + kFIRMessagingErrorCodeAuthentication = 1, + kFIRMessagingErrorCodeNoAccess = 2, + kFIRMessagingErrorCodeTimeout = 3, + kFIRMessagingErrorCodeNetwork = 4, + + // Another operation is in progress. + kFIRMessagingErrorCodeOperationInProgress = 5, + + // Failed to perform device check in. + kFIRMessagingErrorCodeRegistrarFailedToCheckIn = 6, + + kFIRMessagingErrorCodeInvalidRequest = 7, + + // FIRMessaging generic errors + kFIRMessagingErrorCodeMissingDeviceID = 501, + + // upstream send errors + kFIRMessagingErrorServiceNotAvailable = 1001, + kFIRMessagingErrorInvalidParameters = 1002, + kFIRMessagingErrorMissingTo = 1003, + kFIRMessagingErrorSave = 1004, + kFIRMessagingErrorSizeExceeded = 1005, + // Future Send Errors + + // MCS errors + // Already connected with MCS + kFIRMessagingErrorCodeAlreadyConnected = 2001, + + // PubSub errors + kFIRMessagingErrorCodePubSubAlreadySubscribed = 3001, + kFIRMessagingErrorCodePubSubAlreadyUnsubscribed = 3002, + kFIRMessagingErrorCodePubSubInvalidTopic = 3003, + kFIRMessagingErrorCodePubSubFIRMessagingNotSetup = 3004, + kFIRMessagingErrorCodePubSubOperationIsCancelled = 3005, +}; + +@interface NSError (FIRMessaging) + +@property(nonatomic, readonly) FIRMessagingInternalErrorCode fcmErrorCode; + ++ (NSError *)errorWithFCMErrorCode:(FIRMessagingInternalErrorCode)fcmErrorCode; ++ (NSError *)fcm_errorWithCode:(NSInteger)code userInfo:(NSDictionary *)userInfo; + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.m new file mode 100644 index 0000000..e4b8736 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/NSError+FIRMessaging.m @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "NSError+FIRMessaging.h" + +NSString *const kFIRMessagingDomain = @"com.google.fcm"; + +@implementation NSError (FIRMessaging) + +- (FIRMessagingInternalErrorCode)fcmErrorCode { + return (FIRMessagingInternalErrorCode)self.code; +} + ++ (NSError *)errorWithFCMErrorCode:(FIRMessagingInternalErrorCode)fcmErrorCode { + return [NSError errorWithDomain:kFIRMessagingDomain code:fcmErrorCode userInfo:nil]; +} + ++ (NSError *)fcm_errorWithCode:(NSInteger)code userInfo:(NSDictionary *)userInfo { + return [NSError errorWithDomain:kFIRMessagingDomain code:code userInfo:userInfo]; +} + +@end diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.h new file mode 100644 index 0000000..46d2d9c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.h @@ -0,0 +1,1374 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: buzz/mobile/proto/gtalk_core.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +@class GtalkAppData; +@class GtalkCellTower; +@class GtalkClientEvent; +@class GtalkErrorInfo; +@class GtalkExtension; +@class GtalkHeartbeatConfig; +@class GtalkHeartbeatStat; +@class GtalkPresenceStanza; +@class GtalkSetting; + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Enum GtalkLoginRequest_AuthService + +typedef GPB_ENUM(GtalkLoginRequest_AuthService) { + GtalkLoginRequest_AuthService_Mail = 0, + GtalkLoginRequest_AuthService_AndroidCloudToDeviceMessage = 1, + GtalkLoginRequest_AuthService_AndroidId = 2, +}; + +GPBEnumDescriptor *GtalkLoginRequest_AuthService_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkLoginRequest_AuthService_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkMessageStanza_MessageType + +typedef GPB_ENUM(GtalkMessageStanza_MessageType) { + GtalkMessageStanza_MessageType_Normal = 0, + GtalkMessageStanza_MessageType_Chat = 1, + GtalkMessageStanza_MessageType_Groupchat = 2, + GtalkMessageStanza_MessageType_Headline = 3, + GtalkMessageStanza_MessageType_Error = 4, +}; + +GPBEnumDescriptor *GtalkMessageStanza_MessageType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkMessageStanza_MessageType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkPresenceStanza_PresenceType + +typedef GPB_ENUM(GtalkPresenceStanza_PresenceType) { + GtalkPresenceStanza_PresenceType_Unavailable = 0, + GtalkPresenceStanza_PresenceType_Subscribe = 1, + GtalkPresenceStanza_PresenceType_Subscribed = 2, + GtalkPresenceStanza_PresenceType_Unsubscribe = 3, + GtalkPresenceStanza_PresenceType_Unsubscribed = 4, + GtalkPresenceStanza_PresenceType_Probe = 5, + GtalkPresenceStanza_PresenceType_Error = 6, +}; + +GPBEnumDescriptor *GtalkPresenceStanza_PresenceType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkPresenceStanza_PresenceType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkPresenceStanza_ShowType + +typedef GPB_ENUM(GtalkPresenceStanza_ShowType) { + GtalkPresenceStanza_ShowType_Away = 0, + GtalkPresenceStanza_ShowType_Chat = 1, + GtalkPresenceStanza_ShowType_Dnd = 2, + GtalkPresenceStanza_ShowType_Xa = 3, +}; + +GPBEnumDescriptor *GtalkPresenceStanza_ShowType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkPresenceStanza_ShowType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkPresenceStanza_ClientType + +typedef GPB_ENUM(GtalkPresenceStanza_ClientType) { + GtalkPresenceStanza_ClientType_Mobile = 0, + GtalkPresenceStanza_ClientType_Android = 1, +}; + +GPBEnumDescriptor *GtalkPresenceStanza_ClientType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkPresenceStanza_ClientType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkPresenceStanza_CapabilitiesFlags + +typedef GPB_ENUM(GtalkPresenceStanza_CapabilitiesFlags) { + GtalkPresenceStanza_CapabilitiesFlags_HasVoiceV1 = 1, + GtalkPresenceStanza_CapabilitiesFlags_HasVideoV1 = 2, + GtalkPresenceStanza_CapabilitiesFlags_HasCameraV1 = 4, + GtalkPresenceStanza_CapabilitiesFlags_HasPmucV1 = 8, +}; + +GPBEnumDescriptor *GtalkPresenceStanza_CapabilitiesFlags_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkPresenceStanza_CapabilitiesFlags_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkBatchPresenceStanza_Type + +typedef GPB_ENUM(GtalkBatchPresenceStanza_Type) { + GtalkBatchPresenceStanza_Type_Get = 0, + GtalkBatchPresenceStanza_Type_Set = 1, +}; + +GPBEnumDescriptor *GtalkBatchPresenceStanza_Type_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkBatchPresenceStanza_Type_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkIqStanza_IqType + +typedef GPB_ENUM(GtalkIqStanza_IqType) { + GtalkIqStanza_IqType_Get = 0, + GtalkIqStanza_IqType_Set = 1, + GtalkIqStanza_IqType_Result = 2, + GtalkIqStanza_IqType_Error = 3, +}; + +GPBEnumDescriptor *GtalkIqStanza_IqType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkIqStanza_IqType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkClientEvent_Type + +typedef GPB_ENUM(GtalkClientEvent_Type) { + GtalkClientEvent_Type_Unknown = 0, + GtalkClientEvent_Type_DiscardedEvents = 1, + GtalkClientEvent_Type_FailedConnection = 2, + GtalkClientEvent_Type_SuccessfulConnection = 3, + GtalkClientEvent_Type_McsReconnectRequest = 4, + GtalkClientEvent_Type_FailedSocketCreationMcsReconnect = 5, + GtalkClientEvent_Type_McsReconnectLimited = 6, +}; + +GPBEnumDescriptor *GtalkClientEvent_Type_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkClientEvent_Type_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkClientEvent_McsReconnectAction + +typedef GPB_ENUM(GtalkClientEvent_McsReconnectAction) { + GtalkClientEvent_McsReconnectAction_None = 0, + GtalkClientEvent_McsReconnectAction_NotConnected = 1, + GtalkClientEvent_McsReconnectAction_TooSoon = 2, +}; + +GPBEnumDescriptor *GtalkClientEvent_McsReconnectAction_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkClientEvent_McsReconnectAction_IsValidValue(int32_t value); + +#pragma mark - GtalkGtalkCoreRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GtalkGtalkCoreRoot : GPBRootObject +@end + +#pragma mark - GtalkHeartbeatPing + +typedef GPB_ENUM(GtalkHeartbeatPing_FieldNumber) { + GtalkHeartbeatPing_FieldNumber_StreamId = 1, + GtalkHeartbeatPing_FieldNumber_LastStreamIdReceived = 2, + GtalkHeartbeatPing_FieldNumber_Status = 3, + GtalkHeartbeatPing_FieldNumber_CellTower = 4, + GtalkHeartbeatPing_FieldNumber_IntervalMs = 5, +}; + +@interface GtalkHeartbeatPing : GPBMessage + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int64_t status; + +@property(nonatomic, readwrite) BOOL hasStatus; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkCellTower *cellTower DEPRECATED_ATTRIBUTE; +/** Test to see if @c cellTower has been set. */ +@property(nonatomic, readwrite) BOOL hasCellTower DEPRECATED_ATTRIBUTE; + + +@property(nonatomic, readwrite) int32_t intervalMs; + +@property(nonatomic, readwrite) BOOL hasIntervalMs; +@end + +#pragma mark - GtalkHeartbeatAck + +typedef GPB_ENUM(GtalkHeartbeatAck_FieldNumber) { + GtalkHeartbeatAck_FieldNumber_StreamId = 1, + GtalkHeartbeatAck_FieldNumber_LastStreamIdReceived = 2, + GtalkHeartbeatAck_FieldNumber_Status = 3, + GtalkHeartbeatAck_FieldNumber_CellTower = 4, + GtalkHeartbeatAck_FieldNumber_IntervalMs = 5, +}; + +@interface GtalkHeartbeatAck : GPBMessage + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int64_t status; + +@property(nonatomic, readwrite) BOOL hasStatus; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkCellTower *cellTower DEPRECATED_ATTRIBUTE; +/** Test to see if @c cellTower has been set. */ +@property(nonatomic, readwrite) BOOL hasCellTower DEPRECATED_ATTRIBUTE; + + +@property(nonatomic, readwrite) int32_t intervalMs; + +@property(nonatomic, readwrite) BOOL hasIntervalMs; +@end + +#pragma mark - GtalkErrorInfo + +typedef GPB_ENUM(GtalkErrorInfo_FieldNumber) { + GtalkErrorInfo_FieldNumber_Code = 1, + GtalkErrorInfo_FieldNumber_Message = 2, + GtalkErrorInfo_FieldNumber_Type = 3, + GtalkErrorInfo_FieldNumber_Extension = 4, +}; + +@interface GtalkErrorInfo : GPBMessage + + +@property(nonatomic, readwrite) int32_t code; + +@property(nonatomic, readwrite) BOOL hasCode; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *message; +/** Test to see if @c message has been set. */ +@property(nonatomic, readwrite) BOOL hasMessage; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *type; +/** Test to see if @c type has been set. */ +@property(nonatomic, readwrite) BOOL hasType; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkExtension *extension; +/** Test to see if @c extension has been set. */ +@property(nonatomic, readwrite) BOOL hasExtension; + +@end + +#pragma mark - GtalkSetting + +typedef GPB_ENUM(GtalkSetting_FieldNumber) { + GtalkSetting_FieldNumber_Name = 1, + GtalkSetting_FieldNumber_Value = 2, +}; + +@interface GtalkSetting : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; +/** Test to see if @c name has been set. */ +@property(nonatomic, readwrite) BOOL hasName; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *value; +/** Test to see if @c value has been set. */ +@property(nonatomic, readwrite) BOOL hasValue; + +@end + +#pragma mark - GtalkHeartbeatStat + +typedef GPB_ENUM(GtalkHeartbeatStat_FieldNumber) { + GtalkHeartbeatStat_FieldNumber_Ip = 1, + GtalkHeartbeatStat_FieldNumber_Timeout = 2, + GtalkHeartbeatStat_FieldNumber_IntervalMs = 3, +}; + +@interface GtalkHeartbeatStat : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *ip; +/** Test to see if @c ip has been set. */ +@property(nonatomic, readwrite) BOOL hasIp; + + +@property(nonatomic, readwrite) BOOL timeout; + +@property(nonatomic, readwrite) BOOL hasTimeout; + +@property(nonatomic, readwrite) int32_t intervalMs; + +@property(nonatomic, readwrite) BOOL hasIntervalMs; +@end + +#pragma mark - GtalkHeartbeatConfig + +typedef GPB_ENUM(GtalkHeartbeatConfig_FieldNumber) { + GtalkHeartbeatConfig_FieldNumber_UploadStat = 1, + GtalkHeartbeatConfig_FieldNumber_Ip = 2, + GtalkHeartbeatConfig_FieldNumber_IntervalMs = 3, +}; + +@interface GtalkHeartbeatConfig : GPBMessage + + +@property(nonatomic, readwrite) BOOL uploadStat; + +@property(nonatomic, readwrite) BOOL hasUploadStat; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *ip; +/** Test to see if @c ip has been set. */ +@property(nonatomic, readwrite) BOOL hasIp; + + +@property(nonatomic, readwrite) int32_t intervalMs; + +@property(nonatomic, readwrite) BOOL hasIntervalMs; +@end + +#pragma mark - GtalkLoginRequest + +typedef GPB_ENUM(GtalkLoginRequest_FieldNumber) { + GtalkLoginRequest_FieldNumber_Id_p = 1, + GtalkLoginRequest_FieldNumber_Domain = 2, + GtalkLoginRequest_FieldNumber_User = 3, + GtalkLoginRequest_FieldNumber_Resource = 4, + GtalkLoginRequest_FieldNumber_AuthToken = 5, + GtalkLoginRequest_FieldNumber_DeviceId = 6, + GtalkLoginRequest_FieldNumber_LastRmqId = 7, + GtalkLoginRequest_FieldNumber_SettingArray = 8, + GtalkLoginRequest_FieldNumber_ReceivedPersistentIdArray = 10, + GtalkLoginRequest_FieldNumber_IncludeStreamIds = 11, + GtalkLoginRequest_FieldNumber_HeartbeatStat = 13, + GtalkLoginRequest_FieldNumber_UseRmq2 = 14, + GtalkLoginRequest_FieldNumber_AccountId = 15, + GtalkLoginRequest_FieldNumber_AuthService = 16, + GtalkLoginRequest_FieldNumber_NetworkType = 17, + GtalkLoginRequest_FieldNumber_Status = 18, + GtalkLoginRequest_FieldNumber_TokenVersionInfo = 19, + GtalkLoginRequest_FieldNumber_CellTower = 20, + GtalkLoginRequest_FieldNumber_GcmStartTimeMs = 21, + GtalkLoginRequest_FieldNumber_ClientEventArray = 22, + GtalkLoginRequest_FieldNumber_OnFallback = 23, + GtalkLoginRequest_FieldNumber_NoPendingUpstream = 24, + GtalkLoginRequest_FieldNumber_ReconnectRequestId = 25, +}; + +@interface GtalkLoginRequest : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *domain; +/** Test to see if @c domain has been set. */ +@property(nonatomic, readwrite) BOOL hasDomain; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *user; +/** Test to see if @c user has been set. */ +@property(nonatomic, readwrite) BOOL hasUser; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *resource; +/** Test to see if @c resource has been set. */ +@property(nonatomic, readwrite) BOOL hasResource; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *authToken; +/** Test to see if @c authToken has been set. */ +@property(nonatomic, readwrite) BOOL hasAuthToken; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *deviceId; +/** Test to see if @c deviceId has been set. */ +@property(nonatomic, readwrite) BOOL hasDeviceId; + + +@property(nonatomic, readwrite) int64_t lastRmqId; + +@property(nonatomic, readwrite) BOOL hasLastRmqId; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *settingArray; +/** The number of items in @c settingArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger settingArray_Count; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *receivedPersistentIdArray; +/** The number of items in @c receivedPersistentIdArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger receivedPersistentIdArray_Count; + + +@property(nonatomic, readwrite) BOOL includeStreamIds; + +@property(nonatomic, readwrite) BOOL hasIncludeStreamIds; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkHeartbeatStat *heartbeatStat; +/** Test to see if @c heartbeatStat has been set. */ +@property(nonatomic, readwrite) BOOL hasHeartbeatStat; + + +@property(nonatomic, readwrite) BOOL useRmq2; + +@property(nonatomic, readwrite) BOOL hasUseRmq2; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; + +@property(nonatomic, readwrite) GtalkLoginRequest_AuthService authService; + +@property(nonatomic, readwrite) BOOL hasAuthService; + +@property(nonatomic, readwrite) int32_t networkType; + +@property(nonatomic, readwrite) BOOL hasNetworkType; + +@property(nonatomic, readwrite) int64_t status; + +@property(nonatomic, readwrite) BOOL hasStatus; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *tokenVersionInfo; +/** Test to see if @c tokenVersionInfo has been set. */ +@property(nonatomic, readwrite) BOOL hasTokenVersionInfo; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkCellTower *cellTower DEPRECATED_ATTRIBUTE; +/** Test to see if @c cellTower has been set. */ +@property(nonatomic, readwrite) BOOL hasCellTower DEPRECATED_ATTRIBUTE; + + +@property(nonatomic, readwrite) uint64_t gcmStartTimeMs; + +@property(nonatomic, readwrite) BOOL hasGcmStartTimeMs; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *clientEventArray; +/** The number of items in @c clientEventArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger clientEventArray_Count; + + +@property(nonatomic, readwrite) BOOL onFallback; + +@property(nonatomic, readwrite) BOOL hasOnFallback; + +@property(nonatomic, readwrite) BOOL noPendingUpstream; + +@property(nonatomic, readwrite) BOOL hasNoPendingUpstream; + +@property(nonatomic, readwrite) int32_t reconnectRequestId; + +@property(nonatomic, readwrite) BOOL hasReconnectRequestId; +@end + +#pragma mark - GtalkLoginResponse + +typedef GPB_ENUM(GtalkLoginResponse_FieldNumber) { + GtalkLoginResponse_FieldNumber_Id_p = 1, + GtalkLoginResponse_FieldNumber_Jid = 2, + GtalkLoginResponse_FieldNumber_Error = 3, + GtalkLoginResponse_FieldNumber_SettingArray = 4, + GtalkLoginResponse_FieldNumber_StreamId = 5, + GtalkLoginResponse_FieldNumber_LastStreamIdReceived = 6, + GtalkLoginResponse_FieldNumber_HeartbeatConfig = 7, + GtalkLoginResponse_FieldNumber_ServerTimestamp = 8, +}; + +@interface GtalkLoginResponse : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *jid; +/** Test to see if @c jid has been set. */ +@property(nonatomic, readwrite) BOOL hasJid; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *settingArray; +/** The number of items in @c settingArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger settingArray_Count; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkHeartbeatConfig *heartbeatConfig; +/** Test to see if @c heartbeatConfig has been set. */ +@property(nonatomic, readwrite) BOOL hasHeartbeatConfig; + + +@property(nonatomic, readwrite) int64_t serverTimestamp; + +@property(nonatomic, readwrite) BOOL hasServerTimestamp; +@end + +#pragma mark - GtalkBindAccountRequest + +typedef GPB_ENUM(GtalkBindAccountRequest_FieldNumber) { + GtalkBindAccountRequest_FieldNumber_Id_p = 1, + GtalkBindAccountRequest_FieldNumber_Domain = 2, + GtalkBindAccountRequest_FieldNumber_User = 3, + GtalkBindAccountRequest_FieldNumber_Resource = 4, + GtalkBindAccountRequest_FieldNumber_AuthToken = 5, + GtalkBindAccountRequest_FieldNumber_PersistentId = 6, + GtalkBindAccountRequest_FieldNumber_StreamId = 7, + GtalkBindAccountRequest_FieldNumber_LastStreamIdReceived = 8, + GtalkBindAccountRequest_FieldNumber_AccountId = 9, +}; + +@interface GtalkBindAccountRequest : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *domain; +/** Test to see if @c domain has been set. */ +@property(nonatomic, readwrite) BOOL hasDomain; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *user; +/** Test to see if @c user has been set. */ +@property(nonatomic, readwrite) BOOL hasUser; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *resource; +/** Test to see if @c resource has been set. */ +@property(nonatomic, readwrite) BOOL hasResource; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *authToken; +/** Test to see if @c authToken has been set. */ +@property(nonatomic, readwrite) BOOL hasAuthToken; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; +@end + +#pragma mark - GtalkBindAccountResponse + +typedef GPB_ENUM(GtalkBindAccountResponse_FieldNumber) { + GtalkBindAccountResponse_FieldNumber_Id_p = 1, + GtalkBindAccountResponse_FieldNumber_Jid = 2, + GtalkBindAccountResponse_FieldNumber_Error = 3, + GtalkBindAccountResponse_FieldNumber_StreamId = 4, + GtalkBindAccountResponse_FieldNumber_LastStreamIdReceived = 5, +}; + +@interface GtalkBindAccountResponse : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *jid; +/** Test to see if @c jid has been set. */ +@property(nonatomic, readwrite) BOOL hasJid; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; +@end + +#pragma mark - GtalkStreamErrorStanza + +typedef GPB_ENUM(GtalkStreamErrorStanza_FieldNumber) { + GtalkStreamErrorStanza_FieldNumber_Type = 1, + GtalkStreamErrorStanza_FieldNumber_Text = 2, +}; + +@interface GtalkStreamErrorStanza : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *type; +/** Test to see if @c type has been set. */ +@property(nonatomic, readwrite) BOOL hasType; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *text; +/** Test to see if @c text has been set. */ +@property(nonatomic, readwrite) BOOL hasText; + +@end + +#pragma mark - GtalkClose + +@interface GtalkClose : GPBMessage + +@end + +#pragma mark - GtalkExtension + +typedef GPB_ENUM(GtalkExtension_FieldNumber) { + GtalkExtension_FieldNumber_Id_p = 1, + GtalkExtension_FieldNumber_Data_p = 2, +}; + +@interface GtalkExtension : GPBMessage + + +@property(nonatomic, readwrite) int32_t id_p; + +@property(nonatomic, readwrite) BOOL hasId_p; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *data_p; +/** Test to see if @c data_p has been set. */ +@property(nonatomic, readwrite) BOOL hasData_p; + +@end + +#pragma mark - GtalkMessageStanza + +typedef GPB_ENUM(GtalkMessageStanza_FieldNumber) { + GtalkMessageStanza_FieldNumber_RmqId = 1, + GtalkMessageStanza_FieldNumber_Type = 2, + GtalkMessageStanza_FieldNumber_Id_p = 3, + GtalkMessageStanza_FieldNumber_From = 4, + GtalkMessageStanza_FieldNumber_To = 5, + GtalkMessageStanza_FieldNumber_Subject = 6, + GtalkMessageStanza_FieldNumber_Body = 7, + GtalkMessageStanza_FieldNumber_Thread = 8, + GtalkMessageStanza_FieldNumber_Error = 9, + GtalkMessageStanza_FieldNumber_ExtensionArray = 10, + GtalkMessageStanza_FieldNumber_Nosave = 11, + GtalkMessageStanza_FieldNumber_Timestamp = 12, + GtalkMessageStanza_FieldNumber_PersistentId = 13, + GtalkMessageStanza_FieldNumber_StreamId = 14, + GtalkMessageStanza_FieldNumber_LastStreamIdReceived = 15, + GtalkMessageStanza_FieldNumber_Read = 16, + GtalkMessageStanza_FieldNumber_AccountId = 17, +}; + +@interface GtalkMessageStanza : GPBMessage + + +@property(nonatomic, readwrite) int64_t rmqId; + +@property(nonatomic, readwrite) BOOL hasRmqId; + +@property(nonatomic, readwrite) GtalkMessageStanza_MessageType type; + +@property(nonatomic, readwrite) BOOL hasType; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *from; +/** Test to see if @c from has been set. */ +@property(nonatomic, readwrite) BOOL hasFrom; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *to; +/** Test to see if @c to has been set. */ +@property(nonatomic, readwrite) BOOL hasTo; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *subject; +/** Test to see if @c subject has been set. */ +@property(nonatomic, readwrite) BOOL hasSubject; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *body; +/** Test to see if @c body has been set. */ +@property(nonatomic, readwrite) BOOL hasBody; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *thread; +/** Test to see if @c thread has been set. */ +@property(nonatomic, readwrite) BOOL hasThread; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *extensionArray; +/** The number of items in @c extensionArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger extensionArray_Count; + + +@property(nonatomic, readwrite) BOOL nosave; + +@property(nonatomic, readwrite) BOOL hasNosave; + +@property(nonatomic, readwrite) int64_t timestamp; + +@property(nonatomic, readwrite) BOOL hasTimestamp; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL read; + +@property(nonatomic, readwrite) BOOL hasRead; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; +@end + +#pragma mark - GtalkPresenceStanza + +typedef GPB_ENUM(GtalkPresenceStanza_FieldNumber) { + GtalkPresenceStanza_FieldNumber_RmqId = 1, + GtalkPresenceStanza_FieldNumber_Type = 2, + GtalkPresenceStanza_FieldNumber_Id_p = 3, + GtalkPresenceStanza_FieldNumber_From = 4, + GtalkPresenceStanza_FieldNumber_To = 5, + GtalkPresenceStanza_FieldNumber_Show = 6, + GtalkPresenceStanza_FieldNumber_Status = 7, + GtalkPresenceStanza_FieldNumber_Priority = 8, + GtalkPresenceStanza_FieldNumber_Error = 9, + GtalkPresenceStanza_FieldNumber_ExtensionArray = 10, + GtalkPresenceStanza_FieldNumber_Client = 11, + GtalkPresenceStanza_FieldNumber_AvatarHash = 12, + GtalkPresenceStanza_FieldNumber_PersistentId = 13, + GtalkPresenceStanza_FieldNumber_StreamId = 14, + GtalkPresenceStanza_FieldNumber_LastStreamIdReceived = 15, + GtalkPresenceStanza_FieldNumber_CapabilitiesFlags = 16, + GtalkPresenceStanza_FieldNumber_AccountId = 17, +}; + +@interface GtalkPresenceStanza : GPBMessage + + +@property(nonatomic, readwrite) int64_t rmqId; + +@property(nonatomic, readwrite) BOOL hasRmqId; + +@property(nonatomic, readwrite) GtalkPresenceStanza_PresenceType type; + +@property(nonatomic, readwrite) BOOL hasType; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *from; +/** Test to see if @c from has been set. */ +@property(nonatomic, readwrite) BOOL hasFrom; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *to; +/** Test to see if @c to has been set. */ +@property(nonatomic, readwrite) BOOL hasTo; + + +@property(nonatomic, readwrite) GtalkPresenceStanza_ShowType show; + +@property(nonatomic, readwrite) BOOL hasShow; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *status; +/** Test to see if @c status has been set. */ +@property(nonatomic, readwrite) BOOL hasStatus; + + +@property(nonatomic, readwrite) int32_t priority; + +@property(nonatomic, readwrite) BOOL hasPriority; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *extensionArray; +/** The number of items in @c extensionArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger extensionArray_Count; + + +@property(nonatomic, readwrite) GtalkPresenceStanza_ClientType client; + +@property(nonatomic, readwrite) BOOL hasClient; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *avatarHash; +/** Test to see if @c avatarHash has been set. */ +@property(nonatomic, readwrite) BOOL hasAvatarHash; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int32_t capabilitiesFlags; + +@property(nonatomic, readwrite) BOOL hasCapabilitiesFlags; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; +@end + +#pragma mark - GtalkBatchPresenceStanza + +typedef GPB_ENUM(GtalkBatchPresenceStanza_FieldNumber) { + GtalkBatchPresenceStanza_FieldNumber_Id_p = 1, + GtalkBatchPresenceStanza_FieldNumber_To = 2, + GtalkBatchPresenceStanza_FieldNumber_PresenceArray = 3, + GtalkBatchPresenceStanza_FieldNumber_PersistentId = 4, + GtalkBatchPresenceStanza_FieldNumber_StreamId = 5, + GtalkBatchPresenceStanza_FieldNumber_LastStreamIdReceived = 6, + GtalkBatchPresenceStanza_FieldNumber_AccountId = 7, + GtalkBatchPresenceStanza_FieldNumber_Type = 8, + GtalkBatchPresenceStanza_FieldNumber_Error = 9, +}; + +@interface GtalkBatchPresenceStanza : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *to; +/** Test to see if @c to has been set. */ +@property(nonatomic, readwrite) BOOL hasTo; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *presenceArray; +/** The number of items in @c presenceArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger presenceArray_Count; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; + +@property(nonatomic, readwrite) GtalkBatchPresenceStanza_Type type; + +@property(nonatomic, readwrite) BOOL hasType; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + +@end + +#pragma mark - GtalkIqStanza + +typedef GPB_ENUM(GtalkIqStanza_FieldNumber) { + GtalkIqStanza_FieldNumber_RmqId = 1, + GtalkIqStanza_FieldNumber_Type = 2, + GtalkIqStanza_FieldNumber_Id_p = 3, + GtalkIqStanza_FieldNumber_From = 4, + GtalkIqStanza_FieldNumber_To = 5, + GtalkIqStanza_FieldNumber_Error = 6, + GtalkIqStanza_FieldNumber_Extension = 7, + GtalkIqStanza_FieldNumber_PersistentId = 8, + GtalkIqStanza_FieldNumber_StreamId = 9, + GtalkIqStanza_FieldNumber_LastStreamIdReceived = 10, + GtalkIqStanza_FieldNumber_AccountId = 11, + GtalkIqStanza_FieldNumber_Status = 12, +}; + +@interface GtalkIqStanza : GPBMessage + + +@property(nonatomic, readwrite) int64_t rmqId; + +@property(nonatomic, readwrite) BOOL hasRmqId; + +@property(nonatomic, readwrite) GtalkIqStanza_IqType type; + +@property(nonatomic, readwrite) BOOL hasType; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *from; +/** Test to see if @c from has been set. */ +@property(nonatomic, readwrite) BOOL hasFrom; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *to; +/** Test to see if @c to has been set. */ +@property(nonatomic, readwrite) BOOL hasTo; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkErrorInfo *error; +/** Test to see if @c error has been set. */ +@property(nonatomic, readwrite) BOOL hasError; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkExtension *extension; +/** Test to see if @c extension has been set. */ +@property(nonatomic, readwrite) BOOL hasExtension; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite) int64_t accountId; + +@property(nonatomic, readwrite) BOOL hasAccountId; + +@property(nonatomic, readwrite) int64_t status; + +@property(nonatomic, readwrite) BOOL hasStatus; +@end + +#pragma mark - GtalkAppData + +typedef GPB_ENUM(GtalkAppData_FieldNumber) { + GtalkAppData_FieldNumber_Key = 1, + GtalkAppData_FieldNumber_Value = 2, +}; + +@interface GtalkAppData : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *key; +/** Test to see if @c key has been set. */ +@property(nonatomic, readwrite) BOOL hasKey; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *value; +/** Test to see if @c value has been set. */ +@property(nonatomic, readwrite) BOOL hasValue; + +@end + +#pragma mark - GtalkDataMessageStanza + +typedef GPB_ENUM(GtalkDataMessageStanza_FieldNumber) { + GtalkDataMessageStanza_FieldNumber_RmqId = 1, + GtalkDataMessageStanza_FieldNumber_Id_p = 2, + GtalkDataMessageStanza_FieldNumber_From = 3, + GtalkDataMessageStanza_FieldNumber_To = 4, + GtalkDataMessageStanza_FieldNumber_Category = 5, + GtalkDataMessageStanza_FieldNumber_Token = 6, + GtalkDataMessageStanza_FieldNumber_AppDataArray = 7, + GtalkDataMessageStanza_FieldNumber_FromTrustedServer = 8, + GtalkDataMessageStanza_FieldNumber_PersistentId = 9, + GtalkDataMessageStanza_FieldNumber_StreamId = 10, + GtalkDataMessageStanza_FieldNumber_LastStreamIdReceived = 11, + GtalkDataMessageStanza_FieldNumber_Permission = 12, + GtalkDataMessageStanza_FieldNumber_RegId = 13, + GtalkDataMessageStanza_FieldNumber_PkgSignature = 14, + GtalkDataMessageStanza_FieldNumber_ClientId = 15, + GtalkDataMessageStanza_FieldNumber_DeviceUserId = 16, + GtalkDataMessageStanza_FieldNumber_Ttl = 17, + GtalkDataMessageStanza_FieldNumber_Sent = 18, + GtalkDataMessageStanza_FieldNumber_Queued = 19, + GtalkDataMessageStanza_FieldNumber_Status = 20, + GtalkDataMessageStanza_FieldNumber_RawData = 21, + GtalkDataMessageStanza_FieldNumber_MaxDelay = 22, + GtalkDataMessageStanza_FieldNumber_ActualDelay = 23, + GtalkDataMessageStanza_FieldNumber_ImmediateAck = 24, + GtalkDataMessageStanza_FieldNumber_DeliveryReceiptRequested = 25, + GtalkDataMessageStanza_FieldNumber_ExternalMessageId = 26, + GtalkDataMessageStanza_FieldNumber_Flags = 27, + GtalkDataMessageStanza_FieldNumber_CellTower = 28, + GtalkDataMessageStanza_FieldNumber_Priority = 29, +}; + +@interface GtalkDataMessageStanza : GPBMessage + + +@property(nonatomic, readwrite) int64_t rmqId; + +@property(nonatomic, readwrite) BOOL hasRmqId; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *from; +/** Test to see if @c from has been set. */ +@property(nonatomic, readwrite) BOOL hasFrom; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *to; +/** Test to see if @c to has been set. */ +@property(nonatomic, readwrite) BOOL hasTo; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *category; +/** Test to see if @c category has been set. */ +@property(nonatomic, readwrite) BOOL hasCategory; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *token; +/** Test to see if @c token has been set. */ +@property(nonatomic, readwrite) BOOL hasToken; + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *appDataArray; +/** The number of items in @c appDataArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger appDataArray_Count; + + +@property(nonatomic, readwrite) BOOL fromTrustedServer; + +@property(nonatomic, readwrite) BOOL hasFromTrustedServer; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *persistentId; +/** Test to see if @c persistentId has been set. */ +@property(nonatomic, readwrite) BOOL hasPersistentId; + + +@property(nonatomic, readwrite) int32_t streamId; + +@property(nonatomic, readwrite) BOOL hasStreamId; + +@property(nonatomic, readwrite) int32_t lastStreamIdReceived; + +@property(nonatomic, readwrite) BOOL hasLastStreamIdReceived; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *permission; +/** Test to see if @c permission has been set. */ +@property(nonatomic, readwrite) BOOL hasPermission; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *regId; +/** Test to see if @c regId has been set. */ +@property(nonatomic, readwrite) BOOL hasRegId; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *pkgSignature; +/** Test to see if @c pkgSignature has been set. */ +@property(nonatomic, readwrite) BOOL hasPkgSignature; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *clientId; +/** Test to see if @c clientId has been set. */ +@property(nonatomic, readwrite) BOOL hasClientId; + + +@property(nonatomic, readwrite) int64_t deviceUserId; + +@property(nonatomic, readwrite) BOOL hasDeviceUserId; + +@property(nonatomic, readwrite) int32_t ttl; + +@property(nonatomic, readwrite) BOOL hasTtl; + +@property(nonatomic, readwrite) int64_t sent; + +@property(nonatomic, readwrite) BOOL hasSent; + +@property(nonatomic, readwrite) int32_t queued; + +@property(nonatomic, readwrite) BOOL hasQueued; + +@property(nonatomic, readwrite) int64_t status; + +@property(nonatomic, readwrite) BOOL hasStatus; + +@property(nonatomic, readwrite, copy, null_resettable) NSData *rawData; +/** Test to see if @c rawData has been set. */ +@property(nonatomic, readwrite) BOOL hasRawData; + + +@property(nonatomic, readwrite) int32_t maxDelay; + +@property(nonatomic, readwrite) BOOL hasMaxDelay; + +@property(nonatomic, readwrite) int32_t actualDelay; + +@property(nonatomic, readwrite) BOOL hasActualDelay; + +@property(nonatomic, readwrite) BOOL immediateAck; + +@property(nonatomic, readwrite) BOOL hasImmediateAck; + +@property(nonatomic, readwrite) BOOL deliveryReceiptRequested; + +@property(nonatomic, readwrite) BOOL hasDeliveryReceiptRequested; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *externalMessageId; +/** Test to see if @c externalMessageId has been set. */ +@property(nonatomic, readwrite) BOOL hasExternalMessageId; + + +@property(nonatomic, readwrite) int64_t flags; + +@property(nonatomic, readwrite) BOOL hasFlags; + +@property(nonatomic, readwrite, strong, null_resettable) GtalkCellTower *cellTower DEPRECATED_ATTRIBUTE; +/** Test to see if @c cellTower has been set. */ +@property(nonatomic, readwrite) BOOL hasCellTower DEPRECATED_ATTRIBUTE; + + +@property(nonatomic, readwrite) int32_t priority; + +@property(nonatomic, readwrite) BOOL hasPriority; +@end + +#pragma mark - GtalkTalkMetadata + +typedef GPB_ENUM(GtalkTalkMetadata_FieldNumber) { + GtalkTalkMetadata_FieldNumber_Foreground = 1, +}; + +@interface GtalkTalkMetadata : GPBMessage + + +@property(nonatomic, readwrite) BOOL foreground; + +@property(nonatomic, readwrite) BOOL hasForeground; +@end + +#pragma mark - GtalkCellTower + +typedef GPB_ENUM(GtalkCellTower_FieldNumber) { + GtalkCellTower_FieldNumber_Id_p = 1, + GtalkCellTower_FieldNumber_KnownCongestionStatus = 2, +}; + +DEPRECATED_ATTRIBUTE +@interface GtalkCellTower : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p; +/** Test to see if @c id_p has been set. */ +@property(nonatomic, readwrite) BOOL hasId_p; + + +@property(nonatomic, readwrite) int32_t knownCongestionStatus; + +@property(nonatomic, readwrite) BOOL hasKnownCongestionStatus; +@end + +#pragma mark - GtalkClientEvent + +typedef GPB_ENUM(GtalkClientEvent_FieldNumber) { + GtalkClientEvent_FieldNumber_Type = 1, + GtalkClientEvent_FieldNumber_NumberDiscardedEvents = 100, + GtalkClientEvent_FieldNumber_NetworkType = 200, + GtalkClientEvent_FieldNumber_NetworkPort = 201, + GtalkClientEvent_FieldNumber_TimeConnectionStartedMs = 202, + GtalkClientEvent_FieldNumber_TimeConnectionEndedMs = 203, + GtalkClientEvent_FieldNumber_ErrorCode = 204, + GtalkClientEvent_FieldNumber_TimeConnectionEstablishedMs = 300, + GtalkClientEvent_FieldNumber_McsReconnectAction = 400, +}; + +@interface GtalkClientEvent : GPBMessage + + +@property(nonatomic, readwrite) GtalkClientEvent_Type type; + +@property(nonatomic, readwrite) BOOL hasType; + +@property(nonatomic, readwrite) uint32_t numberDiscardedEvents; + +@property(nonatomic, readwrite) BOOL hasNumberDiscardedEvents; + +@property(nonatomic, readwrite) int32_t networkType; + +@property(nonatomic, readwrite) BOOL hasNetworkType; + +@property(nonatomic, readwrite) int32_t networkPort; + +@property(nonatomic, readwrite) BOOL hasNetworkPort; + +@property(nonatomic, readwrite) uint64_t timeConnectionStartedMs; + +@property(nonatomic, readwrite) BOOL hasTimeConnectionStartedMs; + +@property(nonatomic, readwrite) uint64_t timeConnectionEndedMs; + +@property(nonatomic, readwrite) BOOL hasTimeConnectionEndedMs; + +@property(nonatomic, readwrite) int32_t errorCode; + +@property(nonatomic, readwrite) BOOL hasErrorCode; + +@property(nonatomic, readwrite) uint64_t timeConnectionEstablishedMs; + +@property(nonatomic, readwrite) BOOL hasTimeConnectionEstablishedMs; + +@property(nonatomic, readwrite) GtalkClientEvent_McsReconnectAction mcsReconnectAction; + +@property(nonatomic, readwrite) BOOL hasMcsReconnectAction; +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.m new file mode 100644 index 0000000..06c9134 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkCore.pbobjc.m @@ -0,0 +1,3017 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: buzz/mobile/proto/gtalk_core.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + + #import "GtalkCore.pbobjc.h" +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GtalkGtalkCoreRoot + +@implementation GtalkGtalkCoreRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GtalkGtalkCoreRoot_FileDescriptor + +static GPBFileDescriptor *GtalkGtalkCoreRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"mobilegtalk" + objcPrefix:@"Gtalk" + syntax:GPBFileSyntaxProto2]; + } + return descriptor; +} + +#pragma mark - GtalkHeartbeatPing + +@implementation GtalkHeartbeatPing + +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasStatus, status; +@dynamic hasCellTower, cellTower; +@dynamic hasIntervalMs, intervalMs; + +typedef struct GtalkHeartbeatPing__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + int32_t intervalMs; + GtalkCellTower *cellTower; + int64_t status; +} GtalkHeartbeatPing__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatPing_FieldNumber_StreamId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkHeartbeatPing__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatPing_FieldNumber_LastStreamIdReceived, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkHeartbeatPing__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatPing_FieldNumber_Status, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkHeartbeatPing__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "cellTower", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkCellTower), + .number = GtalkHeartbeatPing_FieldNumber_CellTower, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkHeartbeatPing__storage_, cellTower), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "intervalMs", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatPing_FieldNumber_IntervalMs, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkHeartbeatPing__storage_, intervalMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkHeartbeatPing class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkHeartbeatPing__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkHeartbeatAck + +@implementation GtalkHeartbeatAck + +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasStatus, status; +@dynamic hasCellTower, cellTower; +@dynamic hasIntervalMs, intervalMs; + +typedef struct GtalkHeartbeatAck__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + int32_t intervalMs; + GtalkCellTower *cellTower; + int64_t status; +} GtalkHeartbeatAck__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatAck_FieldNumber_StreamId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkHeartbeatAck__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatAck_FieldNumber_LastStreamIdReceived, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkHeartbeatAck__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatAck_FieldNumber_Status, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkHeartbeatAck__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "cellTower", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkCellTower), + .number = GtalkHeartbeatAck_FieldNumber_CellTower, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkHeartbeatAck__storage_, cellTower), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "intervalMs", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatAck_FieldNumber_IntervalMs, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkHeartbeatAck__storage_, intervalMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkHeartbeatAck class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkHeartbeatAck__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkErrorInfo + +@implementation GtalkErrorInfo + +@dynamic hasCode, code; +@dynamic hasMessage, message; +@dynamic hasType, type; +@dynamic hasExtension, extension; + +typedef struct GtalkErrorInfo__storage_ { + uint32_t _has_storage_[1]; + int32_t code; + NSString *message; + NSString *type; + GtalkExtension *extension; +} GtalkErrorInfo__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "code", + .dataTypeSpecific.className = NULL, + .number = GtalkErrorInfo_FieldNumber_Code, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkErrorInfo__storage_, code), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeInt32, + }, + { + .name = "message", + .dataTypeSpecific.className = NULL, + .number = GtalkErrorInfo_FieldNumber_Message, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkErrorInfo__storage_, message), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "type", + .dataTypeSpecific.className = NULL, + .number = GtalkErrorInfo_FieldNumber_Type, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkErrorInfo__storage_, type), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "extension", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkExtension), + .number = GtalkErrorInfo_FieldNumber_Extension, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkErrorInfo__storage_, extension), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkErrorInfo class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkErrorInfo__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkSetting + +@implementation GtalkSetting + +@dynamic hasName, name; +@dynamic hasValue, value; + +typedef struct GtalkSetting__storage_ { + uint32_t _has_storage_[1]; + NSString *name; + NSString *value; +} GtalkSetting__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GtalkSetting_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkSetting__storage_, name), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GtalkSetting_FieldNumber_Value, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkSetting__storage_, value), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkSetting class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkSetting__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkHeartbeatStat + +@implementation GtalkHeartbeatStat + +@dynamic hasIp, ip; +@dynamic hasTimeout, timeout; +@dynamic hasIntervalMs, intervalMs; + +typedef struct GtalkHeartbeatStat__storage_ { + uint32_t _has_storage_[1]; + int32_t intervalMs; + NSString *ip; +} GtalkHeartbeatStat__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "ip", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatStat_FieldNumber_Ip, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkHeartbeatStat__storage_, ip), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "timeout", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatStat_FieldNumber_Timeout, + .hasIndex = 1, + .offset = 2, // Stored in _has_storage_ to save space. + .flags = GPBFieldRequired, + .dataType = GPBDataTypeBool, + }, + { + .name = "intervalMs", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatStat_FieldNumber_IntervalMs, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkHeartbeatStat__storage_, intervalMs), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkHeartbeatStat class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkHeartbeatStat__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkHeartbeatConfig + +@implementation GtalkHeartbeatConfig + +@dynamic hasUploadStat, uploadStat; +@dynamic hasIp, ip; +@dynamic hasIntervalMs, intervalMs; + +typedef struct GtalkHeartbeatConfig__storage_ { + uint32_t _has_storage_[1]; + int32_t intervalMs; + NSString *ip; +} GtalkHeartbeatConfig__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "uploadStat", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatConfig_FieldNumber_UploadStat, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "ip", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatConfig_FieldNumber_Ip, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkHeartbeatConfig__storage_, ip), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "intervalMs", + .dataTypeSpecific.className = NULL, + .number = GtalkHeartbeatConfig_FieldNumber_IntervalMs, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkHeartbeatConfig__storage_, intervalMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkHeartbeatConfig class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkHeartbeatConfig__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkLoginRequest + +@implementation GtalkLoginRequest + +@dynamic hasId_p, id_p; +@dynamic hasDomain, domain; +@dynamic hasUser, user; +@dynamic hasResource, resource; +@dynamic hasAuthToken, authToken; +@dynamic hasDeviceId, deviceId; +@dynamic hasLastRmqId, lastRmqId; +@dynamic settingArray, settingArray_Count; +@dynamic receivedPersistentIdArray, receivedPersistentIdArray_Count; +@dynamic hasIncludeStreamIds, includeStreamIds; +@dynamic hasHeartbeatStat, heartbeatStat; +@dynamic hasUseRmq2, useRmq2; +@dynamic hasAccountId, accountId; +@dynamic hasAuthService, authService; +@dynamic hasNetworkType, networkType; +@dynamic hasStatus, status; +@dynamic hasTokenVersionInfo, tokenVersionInfo; +@dynamic hasCellTower, cellTower; +@dynamic hasGcmStartTimeMs, gcmStartTimeMs; +@dynamic clientEventArray, clientEventArray_Count; +@dynamic hasOnFallback, onFallback; +@dynamic hasNoPendingUpstream, noPendingUpstream; +@dynamic hasReconnectRequestId, reconnectRequestId; + +typedef struct GtalkLoginRequest__storage_ { + uint32_t _has_storage_[1]; + GtalkLoginRequest_AuthService authService; + int32_t networkType; + int32_t reconnectRequestId; + NSString *id_p; + NSString *domain; + NSString *user; + NSString *resource; + NSString *authToken; + NSString *deviceId; + NSMutableArray *settingArray; + NSMutableArray *receivedPersistentIdArray; + GtalkHeartbeatStat *heartbeatStat; + NSString *tokenVersionInfo; + GtalkCellTower *cellTower; + NSMutableArray *clientEventArray; + int64_t lastRmqId; + int64_t accountId; + int64_t status; + uint64_t gcmStartTimeMs; +} GtalkLoginRequest__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "domain", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_Domain, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, domain), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "user", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_User, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, user), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "resource", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_Resource, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, resource), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "authToken", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_AuthToken, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, authToken), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "deviceId", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_DeviceId, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, deviceId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "lastRmqId", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_LastRmqId, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, lastRmqId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "settingArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkSetting), + .number = GtalkLoginRequest_FieldNumber_SettingArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, settingArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "receivedPersistentIdArray", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_ReceivedPersistentIdArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, receivedPersistentIdArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + { + .name = "includeStreamIds", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_IncludeStreamIds, + .hasIndex = 7, + .offset = 8, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "heartbeatStat", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkHeartbeatStat), + .number = GtalkLoginRequest_FieldNumber_HeartbeatStat, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, heartbeatStat), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "useRmq2", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_UseRmq2, + .hasIndex = 10, + .offset = 11, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_AccountId, + .hasIndex = 12, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "authService", + .dataTypeSpecific.enumDescFunc = GtalkLoginRequest_AuthService_EnumDescriptor, + .number = GtalkLoginRequest_FieldNumber_AuthService, + .hasIndex = 13, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, authService), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "networkType", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_NetworkType, + .hasIndex = 14, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, networkType), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_Status, + .hasIndex = 15, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "tokenVersionInfo", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_TokenVersionInfo, + .hasIndex = 16, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, tokenVersionInfo), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "cellTower", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkCellTower), + .number = GtalkLoginRequest_FieldNumber_CellTower, + .hasIndex = 17, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, cellTower), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "gcmStartTimeMs", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_GcmStartTimeMs, + .hasIndex = 18, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, gcmStartTimeMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt64, + }, + { + .name = "clientEventArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkClientEvent), + .number = GtalkLoginRequest_FieldNumber_ClientEventArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, clientEventArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "onFallback", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_OnFallback, + .hasIndex = 19, + .offset = 20, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "noPendingUpstream", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_NoPendingUpstream, + .hasIndex = 21, + .offset = 22, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "reconnectRequestId", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginRequest_FieldNumber_ReconnectRequestId, + .hasIndex = 23, + .offset = (uint32_t)offsetof(GtalkLoginRequest__storage_, reconnectRequestId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkLoginRequest class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkLoginRequest__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkLoginRequest_AuthService + +GPBEnumDescriptor *GtalkLoginRequest_AuthService_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Mail\000AndroidCloudToDeviceMessage\000Android" + "Id\000"; + static const int32_t values[] = { + GtalkLoginRequest_AuthService_Mail, + GtalkLoginRequest_AuthService_AndroidCloudToDeviceMessage, + GtalkLoginRequest_AuthService_AndroidId, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkLoginRequest_AuthService) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkLoginRequest_AuthService_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkLoginRequest_AuthService_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkLoginRequest_AuthService_Mail: + case GtalkLoginRequest_AuthService_AndroidCloudToDeviceMessage: + case GtalkLoginRequest_AuthService_AndroidId: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkLoginResponse + +@implementation GtalkLoginResponse + +@dynamic hasId_p, id_p; +@dynamic hasJid, jid; +@dynamic hasError, error; +@dynamic settingArray, settingArray_Count; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasHeartbeatConfig, heartbeatConfig; +@dynamic hasServerTimestamp, serverTimestamp; + +typedef struct GtalkLoginResponse__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + NSString *id_p; + NSString *jid; + GtalkErrorInfo *error; + NSMutableArray *settingArray; + GtalkHeartbeatConfig *heartbeatConfig; + int64_t serverTimestamp; +} GtalkLoginResponse__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginResponse_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "jid", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginResponse_FieldNumber_Jid, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, jid), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkLoginResponse_FieldNumber_Error, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "settingArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkSetting), + .number = GtalkLoginResponse_FieldNumber_SettingArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, settingArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginResponse_FieldNumber_StreamId, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginResponse_FieldNumber_LastStreamIdReceived, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "heartbeatConfig", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkHeartbeatConfig), + .number = GtalkLoginResponse_FieldNumber_HeartbeatConfig, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, heartbeatConfig), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "serverTimestamp", + .dataTypeSpecific.className = NULL, + .number = GtalkLoginResponse_FieldNumber_ServerTimestamp, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkLoginResponse__storage_, serverTimestamp), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkLoginResponse class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkLoginResponse__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkBindAccountRequest + +@implementation GtalkBindAccountRequest + +@dynamic hasId_p, id_p; +@dynamic hasDomain, domain; +@dynamic hasUser, user; +@dynamic hasResource, resource; +@dynamic hasAuthToken, authToken; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasAccountId, accountId; + +typedef struct GtalkBindAccountRequest__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + NSString *id_p; + NSString *domain; + NSString *user; + NSString *resource; + NSString *authToken; + NSString *persistentId; + int64_t accountId; +} GtalkBindAccountRequest__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "domain", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_Domain, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, domain), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "user", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_User, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, user), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "resource", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_Resource, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, resource), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "authToken", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_AuthToken, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, authToken), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_PersistentId, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_StreamId, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_LastStreamIdReceived, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountRequest_FieldNumber_AccountId, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkBindAccountRequest__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkBindAccountRequest class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkBindAccountRequest__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkBindAccountResponse + +@implementation GtalkBindAccountResponse + +@dynamic hasId_p, id_p; +@dynamic hasJid, jid; +@dynamic hasError, error; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; + +typedef struct GtalkBindAccountResponse__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + NSString *id_p; + NSString *jid; + GtalkErrorInfo *error; +} GtalkBindAccountResponse__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountResponse_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkBindAccountResponse__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "jid", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountResponse_FieldNumber_Jid, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkBindAccountResponse__storage_, jid), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkBindAccountResponse_FieldNumber_Error, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkBindAccountResponse__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountResponse_FieldNumber_StreamId, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkBindAccountResponse__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkBindAccountResponse_FieldNumber_LastStreamIdReceived, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkBindAccountResponse__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkBindAccountResponse class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkBindAccountResponse__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkStreamErrorStanza + +@implementation GtalkStreamErrorStanza + +@dynamic hasType, type; +@dynamic hasText, text; + +typedef struct GtalkStreamErrorStanza__storage_ { + uint32_t _has_storage_[1]; + NSString *type; + NSString *text; +} GtalkStreamErrorStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "type", + .dataTypeSpecific.className = NULL, + .number = GtalkStreamErrorStanza_FieldNumber_Type, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkStreamErrorStanza__storage_, type), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "text", + .dataTypeSpecific.className = NULL, + .number = GtalkStreamErrorStanza_FieldNumber_Text, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkStreamErrorStanza__storage_, text), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkStreamErrorStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkStreamErrorStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkClose + +@implementation GtalkClose + + +typedef struct GtalkClose__storage_ { + uint32_t _has_storage_[1]; +} GtalkClose__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkClose class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:NULL + fieldCount:0 + storageSize:sizeof(GtalkClose__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkExtension + +@implementation GtalkExtension + +@dynamic hasId_p, id_p; +@dynamic hasData_p, data_p; + +typedef struct GtalkExtension__storage_ { + uint32_t _has_storage_[1]; + int32_t id_p; + NSString *data_p; +} GtalkExtension__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkExtension_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkExtension__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeInt32, + }, + { + .name = "data_p", + .dataTypeSpecific.className = NULL, + .number = GtalkExtension_FieldNumber_Data_p, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkExtension__storage_, data_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkExtension class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkExtension__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkMessageStanza + +@implementation GtalkMessageStanza + +@dynamic hasRmqId, rmqId; +@dynamic hasType, type; +@dynamic hasId_p, id_p; +@dynamic hasFrom, from; +@dynamic hasTo, to; +@dynamic hasSubject, subject; +@dynamic hasBody, body; +@dynamic hasThread, thread; +@dynamic hasError, error; +@dynamic extensionArray, extensionArray_Count; +@dynamic hasNosave, nosave; +@dynamic hasTimestamp, timestamp; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasRead, read; +@dynamic hasAccountId, accountId; + +typedef struct GtalkMessageStanza__storage_ { + uint32_t _has_storage_[1]; + GtalkMessageStanza_MessageType type; + int32_t streamId; + int32_t lastStreamIdReceived; + NSString *id_p; + NSString *from; + NSString *to; + NSString *subject; + NSString *body; + NSString *thread; + GtalkErrorInfo *error; + NSMutableArray *extensionArray; + NSString *persistentId; + int64_t rmqId; + int64_t timestamp; + int64_t accountId; +} GtalkMessageStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "rmqId", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_RmqId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, rmqId), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeInt64, + }, + { + .name = "type", + .dataTypeSpecific.enumDescFunc = GtalkMessageStanza_MessageType_EnumDescriptor, + .number = GtalkMessageStanza_FieldNumber_Type, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, type), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Id_p, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, id_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "from", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_From, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, from), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "to", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_To, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, to), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "subject", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Subject, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, subject), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "body", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Body, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, body), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "thread", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Thread, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, thread), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkMessageStanza_FieldNumber_Error, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "extensionArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkExtension), + .number = GtalkMessageStanza_FieldNumber_ExtensionArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, extensionArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "nosave", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Nosave, + .hasIndex = 9, + .offset = 10, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "timestamp", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Timestamp, + .hasIndex = 11, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, timestamp), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_PersistentId, + .hasIndex = 12, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_StreamId, + .hasIndex = 13, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_LastStreamIdReceived, + .hasIndex = 14, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "read", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_Read, + .hasIndex = 15, + .offset = 16, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkMessageStanza_FieldNumber_AccountId, + .hasIndex = 17, + .offset = (uint32_t)offsetof(GtalkMessageStanza__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkMessageStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkMessageStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\001\001\005\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkMessageStanza_MessageType + +GPBEnumDescriptor *GtalkMessageStanza_MessageType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Normal\000Chat\000Groupchat\000Headline\000Error\000"; + static const int32_t values[] = { + GtalkMessageStanza_MessageType_Normal, + GtalkMessageStanza_MessageType_Chat, + GtalkMessageStanza_MessageType_Groupchat, + GtalkMessageStanza_MessageType_Headline, + GtalkMessageStanza_MessageType_Error, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkMessageStanza_MessageType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkMessageStanza_MessageType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkMessageStanza_MessageType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkMessageStanza_MessageType_Normal: + case GtalkMessageStanza_MessageType_Chat: + case GtalkMessageStanza_MessageType_Groupchat: + case GtalkMessageStanza_MessageType_Headline: + case GtalkMessageStanza_MessageType_Error: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkPresenceStanza + +@implementation GtalkPresenceStanza + +@dynamic hasRmqId, rmqId; +@dynamic hasType, type; +@dynamic hasId_p, id_p; +@dynamic hasFrom, from; +@dynamic hasTo, to; +@dynamic hasShow, show; +@dynamic hasStatus, status; +@dynamic hasPriority, priority; +@dynamic hasError, error; +@dynamic extensionArray, extensionArray_Count; +@dynamic hasClient, client; +@dynamic hasAvatarHash, avatarHash; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasCapabilitiesFlags, capabilitiesFlags; +@dynamic hasAccountId, accountId; + +typedef struct GtalkPresenceStanza__storage_ { + uint32_t _has_storage_[1]; + GtalkPresenceStanza_PresenceType type; + GtalkPresenceStanza_ShowType show; + int32_t priority; + GtalkPresenceStanza_ClientType client; + int32_t streamId; + int32_t lastStreamIdReceived; + int32_t capabilitiesFlags; + NSString *id_p; + NSString *from; + NSString *to; + NSString *status; + GtalkErrorInfo *error; + NSMutableArray *extensionArray; + NSString *avatarHash; + NSString *persistentId; + int64_t rmqId; + int64_t accountId; +} GtalkPresenceStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "rmqId", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_RmqId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, rmqId), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeInt64, + }, + { + .name = "type", + .dataTypeSpecific.enumDescFunc = GtalkPresenceStanza_PresenceType_EnumDescriptor, + .number = GtalkPresenceStanza_FieldNumber_Type, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, type), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_Id_p, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, id_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "from", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_From, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, from), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "to", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_To, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, to), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "show", + .dataTypeSpecific.enumDescFunc = GtalkPresenceStanza_ShowType_EnumDescriptor, + .number = GtalkPresenceStanza_FieldNumber_Show, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, show), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_Status, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "priority", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_Priority, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, priority), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkPresenceStanza_FieldNumber_Error, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "extensionArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkExtension), + .number = GtalkPresenceStanza_FieldNumber_ExtensionArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, extensionArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "client", + .dataTypeSpecific.enumDescFunc = GtalkPresenceStanza_ClientType_EnumDescriptor, + .number = GtalkPresenceStanza_FieldNumber_Client, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, client), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "avatarHash", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_AvatarHash, + .hasIndex = 10, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, avatarHash), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_PersistentId, + .hasIndex = 11, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_StreamId, + .hasIndex = 12, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_LastStreamIdReceived, + .hasIndex = 13, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "capabilitiesFlags", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_CapabilitiesFlags, + .hasIndex = 14, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, capabilitiesFlags), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkPresenceStanza_FieldNumber_AccountId, + .hasIndex = 15, + .offset = (uint32_t)offsetof(GtalkPresenceStanza__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkPresenceStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkPresenceStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\001\001\005\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkPresenceStanza_PresenceType + +GPBEnumDescriptor *GtalkPresenceStanza_PresenceType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Unavailable\000Subscribe\000Subscribed\000Unsubsc" + "ribe\000Unsubscribed\000Probe\000Error\000"; + static const int32_t values[] = { + GtalkPresenceStanza_PresenceType_Unavailable, + GtalkPresenceStanza_PresenceType_Subscribe, + GtalkPresenceStanza_PresenceType_Subscribed, + GtalkPresenceStanza_PresenceType_Unsubscribe, + GtalkPresenceStanza_PresenceType_Unsubscribed, + GtalkPresenceStanza_PresenceType_Probe, + GtalkPresenceStanza_PresenceType_Error, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkPresenceStanza_PresenceType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkPresenceStanza_PresenceType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkPresenceStanza_PresenceType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkPresenceStanza_PresenceType_Unavailable: + case GtalkPresenceStanza_PresenceType_Subscribe: + case GtalkPresenceStanza_PresenceType_Subscribed: + case GtalkPresenceStanza_PresenceType_Unsubscribe: + case GtalkPresenceStanza_PresenceType_Unsubscribed: + case GtalkPresenceStanza_PresenceType_Probe: + case GtalkPresenceStanza_PresenceType_Error: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkPresenceStanza_ShowType + +GPBEnumDescriptor *GtalkPresenceStanza_ShowType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Away\000Chat\000Dnd\000Xa\000"; + static const int32_t values[] = { + GtalkPresenceStanza_ShowType_Away, + GtalkPresenceStanza_ShowType_Chat, + GtalkPresenceStanza_ShowType_Dnd, + GtalkPresenceStanza_ShowType_Xa, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkPresenceStanza_ShowType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkPresenceStanza_ShowType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkPresenceStanza_ShowType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkPresenceStanza_ShowType_Away: + case GtalkPresenceStanza_ShowType_Chat: + case GtalkPresenceStanza_ShowType_Dnd: + case GtalkPresenceStanza_ShowType_Xa: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkPresenceStanza_ClientType + +GPBEnumDescriptor *GtalkPresenceStanza_ClientType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Mobile\000Android\000"; + static const int32_t values[] = { + GtalkPresenceStanza_ClientType_Mobile, + GtalkPresenceStanza_ClientType_Android, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkPresenceStanza_ClientType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkPresenceStanza_ClientType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkPresenceStanza_ClientType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkPresenceStanza_ClientType_Mobile: + case GtalkPresenceStanza_ClientType_Android: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkPresenceStanza_CapabilitiesFlags + +GPBEnumDescriptor *GtalkPresenceStanza_CapabilitiesFlags_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "HasVoiceV1\000HasVideoV1\000HasCameraV1\000HasPmu" + "cV1\000"; + static const int32_t values[] = { + GtalkPresenceStanza_CapabilitiesFlags_HasVoiceV1, + GtalkPresenceStanza_CapabilitiesFlags_HasVideoV1, + GtalkPresenceStanza_CapabilitiesFlags_HasCameraV1, + GtalkPresenceStanza_CapabilitiesFlags_HasPmucV1, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkPresenceStanza_CapabilitiesFlags) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkPresenceStanza_CapabilitiesFlags_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkPresenceStanza_CapabilitiesFlags_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkPresenceStanza_CapabilitiesFlags_HasVoiceV1: + case GtalkPresenceStanza_CapabilitiesFlags_HasVideoV1: + case GtalkPresenceStanza_CapabilitiesFlags_HasCameraV1: + case GtalkPresenceStanza_CapabilitiesFlags_HasPmucV1: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkBatchPresenceStanza + +@implementation GtalkBatchPresenceStanza + +@dynamic hasId_p, id_p; +@dynamic hasTo, to; +@dynamic presenceArray, presenceArray_Count; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasAccountId, accountId; +@dynamic hasType, type; +@dynamic hasError, error; + +typedef struct GtalkBatchPresenceStanza__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + GtalkBatchPresenceStanza_Type type; + NSString *id_p; + NSString *to; + NSMutableArray *presenceArray; + NSString *persistentId; + GtalkErrorInfo *error; + int64_t accountId; +} GtalkBatchPresenceStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, id_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "to", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_To, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, to), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "presenceArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkPresenceStanza), + .number = GtalkBatchPresenceStanza_FieldNumber_PresenceArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, presenceArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_PersistentId, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_StreamId, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_LastStreamIdReceived, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkBatchPresenceStanza_FieldNumber_AccountId, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "type", + .dataTypeSpecific.enumDescFunc = GtalkBatchPresenceStanza_Type_EnumDescriptor, + .number = GtalkBatchPresenceStanza_FieldNumber_Type, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, type), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkBatchPresenceStanza_FieldNumber_Error, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkBatchPresenceStanza__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkBatchPresenceStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkBatchPresenceStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkBatchPresenceStanza_Type + +GPBEnumDescriptor *GtalkBatchPresenceStanza_Type_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Get\000Set\000"; + static const int32_t values[] = { + GtalkBatchPresenceStanza_Type_Get, + GtalkBatchPresenceStanza_Type_Set, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkBatchPresenceStanza_Type) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkBatchPresenceStanza_Type_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkBatchPresenceStanza_Type_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkBatchPresenceStanza_Type_Get: + case GtalkBatchPresenceStanza_Type_Set: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkIqStanza + +@implementation GtalkIqStanza + +@dynamic hasRmqId, rmqId; +@dynamic hasType, type; +@dynamic hasId_p, id_p; +@dynamic hasFrom, from; +@dynamic hasTo, to; +@dynamic hasError, error; +@dynamic hasExtension, extension; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasAccountId, accountId; +@dynamic hasStatus, status; + +typedef struct GtalkIqStanza__storage_ { + uint32_t _has_storage_[1]; + GtalkIqStanza_IqType type; + int32_t streamId; + int32_t lastStreamIdReceived; + NSString *id_p; + NSString *from; + NSString *to; + GtalkErrorInfo *error; + GtalkExtension *extension; + NSString *persistentId; + int64_t rmqId; + int64_t accountId; + int64_t status; +} GtalkIqStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "rmqId", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_RmqId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, rmqId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "type", + .dataTypeSpecific.enumDescFunc = GtalkIqStanza_IqType_EnumDescriptor, + .number = GtalkIqStanza_FieldNumber_Type, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, type), + .flags = (GPBFieldFlags)(GPBFieldRequired | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_Id_p, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "from", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_From, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, from), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "to", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_To, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, to), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "error", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkErrorInfo), + .number = GtalkIqStanza_FieldNumber_Error, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, error), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "extension", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkExtension), + .number = GtalkIqStanza_FieldNumber_Extension, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, extension), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_PersistentId, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_StreamId, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_LastStreamIdReceived, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "accountId", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_AccountId, + .hasIndex = 10, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, accountId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkIqStanza_FieldNumber_Status, + .hasIndex = 11, + .offset = (uint32_t)offsetof(GtalkIqStanza__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkIqStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkIqStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkIqStanza_IqType + +GPBEnumDescriptor *GtalkIqStanza_IqType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Get\000Set\000Result\000Error\000"; + static const int32_t values[] = { + GtalkIqStanza_IqType_Get, + GtalkIqStanza_IqType_Set, + GtalkIqStanza_IqType_Result, + GtalkIqStanza_IqType_Error, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkIqStanza_IqType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkIqStanza_IqType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkIqStanza_IqType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkIqStanza_IqType_Get: + case GtalkIqStanza_IqType_Set: + case GtalkIqStanza_IqType_Result: + case GtalkIqStanza_IqType_Error: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkAppData + +@implementation GtalkAppData + +@dynamic hasKey, key; +@dynamic hasValue, value; + +typedef struct GtalkAppData__storage_ { + uint32_t _has_storage_[1]; + NSString *key; + NSString *value; +} GtalkAppData__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "key", + .dataTypeSpecific.className = NULL, + .number = GtalkAppData_FieldNumber_Key, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkAppData__storage_, key), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GtalkAppData_FieldNumber_Value, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkAppData__storage_, value), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkAppData class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkAppData__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkDataMessageStanza + +@implementation GtalkDataMessageStanza + +@dynamic hasRmqId, rmqId; +@dynamic hasId_p, id_p; +@dynamic hasFrom, from; +@dynamic hasTo, to; +@dynamic hasCategory, category; +@dynamic hasToken, token; +@dynamic appDataArray, appDataArray_Count; +@dynamic hasFromTrustedServer, fromTrustedServer; +@dynamic hasPersistentId, persistentId; +@dynamic hasStreamId, streamId; +@dynamic hasLastStreamIdReceived, lastStreamIdReceived; +@dynamic hasPermission, permission; +@dynamic hasRegId, regId; +@dynamic hasPkgSignature, pkgSignature; +@dynamic hasClientId, clientId; +@dynamic hasDeviceUserId, deviceUserId; +@dynamic hasTtl, ttl; +@dynamic hasSent, sent; +@dynamic hasQueued, queued; +@dynamic hasStatus, status; +@dynamic hasRawData, rawData; +@dynamic hasMaxDelay, maxDelay; +@dynamic hasActualDelay, actualDelay; +@dynamic hasImmediateAck, immediateAck; +@dynamic hasDeliveryReceiptRequested, deliveryReceiptRequested; +@dynamic hasExternalMessageId, externalMessageId; +@dynamic hasFlags, flags; +@dynamic hasCellTower, cellTower; +@dynamic hasPriority, priority; + +typedef struct GtalkDataMessageStanza__storage_ { + uint32_t _has_storage_[1]; + int32_t streamId; + int32_t lastStreamIdReceived; + int32_t ttl; + int32_t queued; + int32_t maxDelay; + int32_t actualDelay; + int32_t priority; + NSString *id_p; + NSString *from; + NSString *to; + NSString *category; + NSString *token; + NSMutableArray *appDataArray; + NSString *persistentId; + NSString *permission; + NSString *regId; + NSString *pkgSignature; + NSString *clientId; + NSData *rawData; + NSString *externalMessageId; + GtalkCellTower *cellTower; + int64_t rmqId; + int64_t deviceUserId; + int64_t sent; + int64_t status; + int64_t flags; +} GtalkDataMessageStanza__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "rmqId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_RmqId, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, rmqId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Id_p, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, id_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "from", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_From, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, from), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "to", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_To, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, to), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "category", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Category, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, category), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "token", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Token, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, token), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "appDataArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkAppData), + .number = GtalkDataMessageStanza_FieldNumber_AppDataArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, appDataArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "fromTrustedServer", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_FromTrustedServer, + .hasIndex = 6, + .offset = 7, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "persistentId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_PersistentId, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, persistentId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "streamId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_StreamId, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, streamId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "lastStreamIdReceived", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_LastStreamIdReceived, + .hasIndex = 10, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, lastStreamIdReceived), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "permission", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Permission, + .hasIndex = 11, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, permission), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "regId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_RegId, + .hasIndex = 12, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, regId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "pkgSignature", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_PkgSignature, + .hasIndex = 13, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, pkgSignature), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "clientId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_ClientId, + .hasIndex = 14, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, clientId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "deviceUserId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_DeviceUserId, + .hasIndex = 15, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, deviceUserId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "ttl", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Ttl, + .hasIndex = 16, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, ttl), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "sent", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Sent, + .hasIndex = 17, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, sent), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "queued", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Queued, + .hasIndex = 18, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, queued), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Status, + .hasIndex = 19, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "rawData", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_RawData, + .hasIndex = 20, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, rawData), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBytes, + }, + { + .name = "maxDelay", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_MaxDelay, + .hasIndex = 21, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, maxDelay), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "actualDelay", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_ActualDelay, + .hasIndex = 22, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, actualDelay), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "immediateAck", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_ImmediateAck, + .hasIndex = 23, + .offset = 24, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "deliveryReceiptRequested", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_DeliveryReceiptRequested, + .hasIndex = 25, + .offset = 26, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "externalMessageId", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_ExternalMessageId, + .hasIndex = 27, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, externalMessageId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "flags", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Flags, + .hasIndex = 28, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, flags), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "cellTower", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkCellTower), + .number = GtalkDataMessageStanza_FieldNumber_CellTower, + .hasIndex = 29, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, cellTower), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "priority", + .dataTypeSpecific.className = NULL, + .number = GtalkDataMessageStanza_FieldNumber_Priority, + .hasIndex = 30, + .offset = (uint32_t)offsetof(GtalkDataMessageStanza__storage_, priority), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkDataMessageStanza class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkDataMessageStanza__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkTalkMetadata + +@implementation GtalkTalkMetadata + +@dynamic hasForeground, foreground; + +typedef struct GtalkTalkMetadata__storage_ { + uint32_t _has_storage_[1]; +} GtalkTalkMetadata__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "foreground", + .dataTypeSpecific.className = NULL, + .number = GtalkTalkMetadata_FieldNumber_Foreground, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkTalkMetadata class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkTalkMetadata__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkCellTower + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +@implementation GtalkCellTower + +@dynamic hasId_p, id_p; +@dynamic hasKnownCongestionStatus, knownCongestionStatus; + +typedef struct GtalkCellTower__storage_ { + uint32_t _has_storage_[1]; + int32_t knownCongestionStatus; + NSString *id_p; +} GtalkCellTower__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkCellTower_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkCellTower__storage_, id_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "knownCongestionStatus", + .dataTypeSpecific.className = NULL, + .number = GtalkCellTower_FieldNumber_KnownCongestionStatus, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkCellTower__storage_, knownCongestionStatus), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkCellTower class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkCellTower__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma clang diagnostic pop + +#pragma mark - GtalkClientEvent + +@implementation GtalkClientEvent + +@dynamic hasType, type; +@dynamic hasNumberDiscardedEvents, numberDiscardedEvents; +@dynamic hasNetworkType, networkType; +@dynamic hasNetworkPort, networkPort; +@dynamic hasTimeConnectionStartedMs, timeConnectionStartedMs; +@dynamic hasTimeConnectionEndedMs, timeConnectionEndedMs; +@dynamic hasErrorCode, errorCode; +@dynamic hasTimeConnectionEstablishedMs, timeConnectionEstablishedMs; +@dynamic hasMcsReconnectAction, mcsReconnectAction; + +typedef struct GtalkClientEvent__storage_ { + uint32_t _has_storage_[1]; + GtalkClientEvent_Type type; + uint32_t numberDiscardedEvents; + int32_t networkType; + int32_t networkPort; + int32_t errorCode; + GtalkClientEvent_McsReconnectAction mcsReconnectAction; + uint64_t timeConnectionStartedMs; + uint64_t timeConnectionEndedMs; + uint64_t timeConnectionEstablishedMs; +} GtalkClientEvent__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "type", + .dataTypeSpecific.enumDescFunc = GtalkClientEvent_Type_EnumDescriptor, + .number = GtalkClientEvent_FieldNumber_Type, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, type), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "numberDiscardedEvents", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_NumberDiscardedEvents, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, numberDiscardedEvents), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt32, + }, + { + .name = "networkType", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_NetworkType, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, networkType), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "networkPort", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_NetworkPort, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, networkPort), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "timeConnectionStartedMs", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_TimeConnectionStartedMs, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, timeConnectionStartedMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt64, + }, + { + .name = "timeConnectionEndedMs", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_TimeConnectionEndedMs, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, timeConnectionEndedMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt64, + }, + { + .name = "errorCode", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_ErrorCode, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, errorCode), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "timeConnectionEstablishedMs", + .dataTypeSpecific.className = NULL, + .number = GtalkClientEvent_FieldNumber_TimeConnectionEstablishedMs, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, timeConnectionEstablishedMs), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt64, + }, + { + .name = "mcsReconnectAction", + .dataTypeSpecific.enumDescFunc = GtalkClientEvent_McsReconnectAction_EnumDescriptor, + .number = GtalkClientEvent_FieldNumber_McsReconnectAction, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkClientEvent__storage_, mcsReconnectAction), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkClientEvent class] + rootClass:[GtalkGtalkCoreRoot class] + file:GtalkGtalkCoreRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkClientEvent__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkClientEvent_Type + +GPBEnumDescriptor *GtalkClientEvent_Type_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Unknown\000DiscardedEvents\000FailedConnection" + "\000SuccessfulConnection\000McsReconnectReques" + "t\000FailedSocketCreationMcsReconnect\000McsRe" + "connectLimited\000"; + static const int32_t values[] = { + GtalkClientEvent_Type_Unknown, + GtalkClientEvent_Type_DiscardedEvents, + GtalkClientEvent_Type_FailedConnection, + GtalkClientEvent_Type_SuccessfulConnection, + GtalkClientEvent_Type_McsReconnectRequest, + GtalkClientEvent_Type_FailedSocketCreationMcsReconnect, + GtalkClientEvent_Type_McsReconnectLimited, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkClientEvent_Type) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkClientEvent_Type_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkClientEvent_Type_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkClientEvent_Type_Unknown: + case GtalkClientEvent_Type_DiscardedEvents: + case GtalkClientEvent_Type_FailedConnection: + case GtalkClientEvent_Type_SuccessfulConnection: + case GtalkClientEvent_Type_McsReconnectRequest: + case GtalkClientEvent_Type_FailedSocketCreationMcsReconnect: + case GtalkClientEvent_Type_McsReconnectLimited: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkClientEvent_McsReconnectAction + +GPBEnumDescriptor *GtalkClientEvent_McsReconnectAction_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "None\000NotConnected\000TooSoon\000"; + static const int32_t values[] = { + GtalkClientEvent_McsReconnectAction_None, + GtalkClientEvent_McsReconnectAction_NotConnected, + GtalkClientEvent_McsReconnectAction_TooSoon, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkClientEvent_McsReconnectAction) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkClientEvent_McsReconnectAction_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkClientEvent_McsReconnectAction_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkClientEvent_McsReconnectAction_None: + case GtalkClientEvent_McsReconnectAction_NotConnected: + case GtalkClientEvent_McsReconnectAction_TooSoon: + return YES; + default: + return NO; + } +} + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.h new file mode 100644 index 0000000..f461884 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.h @@ -0,0 +1,617 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: buzz/mobile/proto/gtalk_extensions.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +@class GtalkOtrItem; +@class GtalkPhoto; +@class GtalkRosterItem; +@class GtalkSharedStatus_StatusList; + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Enum GtalkRosterItem_SubscriptionType + +typedef GPB_ENUM(GtalkRosterItem_SubscriptionType) { + GtalkRosterItem_SubscriptionType_None = 0, + GtalkRosterItem_SubscriptionType_To = 1, + GtalkRosterItem_SubscriptionType_From = 2, + GtalkRosterItem_SubscriptionType_Both = 3, + GtalkRosterItem_SubscriptionType_Remove = 4, +}; + +GPBEnumDescriptor *GtalkRosterItem_SubscriptionType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkRosterItem_SubscriptionType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkRosterItem_AskType + +typedef GPB_ENUM(GtalkRosterItem_AskType) { + GtalkRosterItem_AskType_Subscribe = 0, +}; + +GPBEnumDescriptor *GtalkRosterItem_AskType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkRosterItem_AskType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkRosterItem_DisplayType + +typedef GPB_ENUM(GtalkRosterItem_DisplayType) { + GtalkRosterItem_DisplayType_Blocked = 0, + GtalkRosterItem_DisplayType_Hidden = 1, + GtalkRosterItem_DisplayType_Pinned = 2, +}; + +GPBEnumDescriptor *GtalkRosterItem_DisplayType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkRosterItem_DisplayType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkSharedStatus_ShowType + +typedef GPB_ENUM(GtalkSharedStatus_ShowType) { + GtalkSharedStatus_ShowType_Default = 0, + GtalkSharedStatus_ShowType_Dnd = 1, +}; + +GPBEnumDescriptor *GtalkSharedStatus_ShowType_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkSharedStatus_ShowType_IsValidValue(int32_t value); + +#pragma mark - Enum GtalkPostAuthBatchQuery_CapabilitiesExtFlags + +typedef GPB_ENUM(GtalkPostAuthBatchQuery_CapabilitiesExtFlags) { + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVoiceV1 = 1, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVideoV1 = 2, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasCameraV1 = 4, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasPmucV1 = 8, +}; + +GPBEnumDescriptor *GtalkPostAuthBatchQuery_CapabilitiesExtFlags_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GtalkPostAuthBatchQuery_CapabilitiesExtFlags_IsValidValue(int32_t value); + +#pragma mark - GtalkGtalkExtensionsRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GtalkGtalkExtensionsRoot : GPBRootObject +@end + +#pragma mark - GtalkRosterQuery + +typedef GPB_ENUM(GtalkRosterQuery_FieldNumber) { + GtalkRosterQuery_FieldNumber_Etag = 1, + GtalkRosterQuery_FieldNumber_NotModified = 2, + GtalkRosterQuery_FieldNumber_ItemArray = 3, + GtalkRosterQuery_FieldNumber_AvatarWidth = 4, + GtalkRosterQuery_FieldNumber_AvatarHeight = 5, +}; + +@interface GtalkRosterQuery : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *etag; +/** Test to see if @c etag has been set. */ +@property(nonatomic, readwrite) BOOL hasEtag; + + +@property(nonatomic, readwrite) BOOL notModified; + +@property(nonatomic, readwrite) BOOL hasNotModified; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *itemArray; +/** The number of items in @c itemArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger itemArray_Count; + + +@property(nonatomic, readwrite) int32_t avatarWidth; + +@property(nonatomic, readwrite) BOOL hasAvatarWidth; + +@property(nonatomic, readwrite) int32_t avatarHeight; + +@property(nonatomic, readwrite) BOOL hasAvatarHeight; +@end + +#pragma mark - GtalkRosterItem + +typedef GPB_ENUM(GtalkRosterItem_FieldNumber) { + GtalkRosterItem_FieldNumber_Jid = 1, + GtalkRosterItem_FieldNumber_Name = 2, + GtalkRosterItem_FieldNumber_Subscription = 3, + GtalkRosterItem_FieldNumber_Ask = 4, + GtalkRosterItem_FieldNumber_GroupArray = 5, + GtalkRosterItem_FieldNumber_QuickContact = 6, + GtalkRosterItem_FieldNumber_Display = 7, + GtalkRosterItem_FieldNumber_Rejected = 8, +}; + +@interface GtalkRosterItem : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *jid; +/** Test to see if @c jid has been set. */ +@property(nonatomic, readwrite) BOOL hasJid; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; +/** Test to see if @c name has been set. */ +@property(nonatomic, readwrite) BOOL hasName; + + +@property(nonatomic, readwrite) GtalkRosterItem_SubscriptionType subscription; + +@property(nonatomic, readwrite) BOOL hasSubscription; + +@property(nonatomic, readwrite) GtalkRosterItem_AskType ask; + +@property(nonatomic, readwrite) BOOL hasAsk; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *groupArray; +/** The number of items in @c groupArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger groupArray_Count; + + +@property(nonatomic, readwrite) BOOL quickContact; + +@property(nonatomic, readwrite) BOOL hasQuickContact; + +@property(nonatomic, readwrite) GtalkRosterItem_DisplayType display; + +@property(nonatomic, readwrite) BOOL hasDisplay; + +@property(nonatomic, readwrite) BOOL rejected; + +@property(nonatomic, readwrite) BOOL hasRejected; +@end + +#pragma mark - GtalkRmqLastId + +typedef GPB_ENUM(GtalkRmqLastId_FieldNumber) { + GtalkRmqLastId_FieldNumber_Id_p = 1, +}; + +@interface GtalkRmqLastId : GPBMessage + + +@property(nonatomic, readwrite) int64_t id_p; + +@property(nonatomic, readwrite) BOOL hasId_p; +@end + +#pragma mark - GtalkRmqAck + +typedef GPB_ENUM(GtalkRmqAck_FieldNumber) { + GtalkRmqAck_FieldNumber_Id_p = 1, +}; + +@interface GtalkRmqAck : GPBMessage + + +@property(nonatomic, readwrite) int64_t id_p; + +@property(nonatomic, readwrite) BOOL hasId_p; +@end + +#pragma mark - GtalkVCard + +typedef GPB_ENUM(GtalkVCard_FieldNumber) { + GtalkVCard_FieldNumber_Version = 1, + GtalkVCard_FieldNumber_FullName = 2, + GtalkVCard_FieldNumber_Photo = 3, + GtalkVCard_FieldNumber_AvatarHash = 4, + GtalkVCard_FieldNumber_Modified = 5, +}; + +@interface GtalkVCard : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *version; +/** Test to see if @c version has been set. */ +@property(nonatomic, readwrite) BOOL hasVersion; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *fullName; +/** Test to see if @c fullName has been set. */ +@property(nonatomic, readwrite) BOOL hasFullName; + + +@property(nonatomic, readwrite, strong, null_resettable) GtalkPhoto *photo; +/** Test to see if @c photo has been set. */ +@property(nonatomic, readwrite) BOOL hasPhoto; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *avatarHash; +/** Test to see if @c avatarHash has been set. */ +@property(nonatomic, readwrite) BOOL hasAvatarHash; + + +@property(nonatomic, readwrite) BOOL modified; + +@property(nonatomic, readwrite) BOOL hasModified; +@end + +#pragma mark - GtalkPhoto + +typedef GPB_ENUM(GtalkPhoto_FieldNumber) { + GtalkPhoto_FieldNumber_Type = 1, + GtalkPhoto_FieldNumber_Data_p = 2, +}; + +@interface GtalkPhoto : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *type; +/** Test to see if @c type has been set. */ +@property(nonatomic, readwrite) BOOL hasType; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *data_p; +/** Test to see if @c data_p has been set. */ +@property(nonatomic, readwrite) BOOL hasData_p; + +@end + +#pragma mark - GtalkChatRead + +typedef GPB_ENUM(GtalkChatRead_FieldNumber) { + GtalkChatRead_FieldNumber_User = 1, +}; + +@interface GtalkChatRead : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *user; +/** Test to see if @c user has been set. */ +@property(nonatomic, readwrite) BOOL hasUser; + +@end + +#pragma mark - GtalkChatClosed + +typedef GPB_ENUM(GtalkChatClosed_FieldNumber) { + GtalkChatClosed_FieldNumber_User = 1, +}; + +@interface GtalkChatClosed : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *user; +/** Test to see if @c user has been set. */ +@property(nonatomic, readwrite) BOOL hasUser; + +@end + +#pragma mark - GtalkCapabilities + +typedef GPB_ENUM(GtalkCapabilities_FieldNumber) { + GtalkCapabilities_FieldNumber_Node = 1, + GtalkCapabilities_FieldNumber_Ver = 2, + GtalkCapabilities_FieldNumber_Ext = 3, + GtalkCapabilities_FieldNumber_Hash_p = 4, +}; + +@interface GtalkCapabilities : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *node; +/** Test to see if @c node has been set. */ +@property(nonatomic, readwrite) BOOL hasNode; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *ver; +/** Test to see if @c ver has been set. */ +@property(nonatomic, readwrite) BOOL hasVer; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *ext; +/** Test to see if @c ext has been set. */ +@property(nonatomic, readwrite) BOOL hasExt; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *hash_p; +/** Test to see if @c hash_p has been set. */ +@property(nonatomic, readwrite) BOOL hasHash_p; + +@end + +#pragma mark - GtalkSharedStatus + +typedef GPB_ENUM(GtalkSharedStatus_FieldNumber) { + GtalkSharedStatus_FieldNumber_StatusMax = 1, + GtalkSharedStatus_FieldNumber_StatusListMax = 2, + GtalkSharedStatus_FieldNumber_StatusListContentsMax = 3, + GtalkSharedStatus_FieldNumber_Status = 4, + GtalkSharedStatus_FieldNumber_Show = 5, + GtalkSharedStatus_FieldNumber_StatusListArray = 6, + GtalkSharedStatus_FieldNumber_Invisible = 9, + GtalkSharedStatus_FieldNumber_StatusMinVersion = 10, +}; + +@interface GtalkSharedStatus : GPBMessage + + +@property(nonatomic, readwrite) int32_t statusMax; + +@property(nonatomic, readwrite) BOOL hasStatusMax; + +@property(nonatomic, readwrite) int32_t statusListMax; + +@property(nonatomic, readwrite) BOOL hasStatusListMax; + +@property(nonatomic, readwrite) int32_t statusListContentsMax; + +@property(nonatomic, readwrite) BOOL hasStatusListContentsMax; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *status; +/** Test to see if @c status has been set. */ +@property(nonatomic, readwrite) BOOL hasStatus; + + +@property(nonatomic, readwrite) GtalkSharedStatus_ShowType show; + +@property(nonatomic, readwrite) BOOL hasShow; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *statusListArray; +/** The number of items in @c statusListArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger statusListArray_Count; + + +@property(nonatomic, readwrite) BOOL invisible; + +@property(nonatomic, readwrite) BOOL hasInvisible; + +@property(nonatomic, readwrite) int32_t statusMinVersion; + +@property(nonatomic, readwrite) BOOL hasStatusMinVersion; +@end + +#pragma mark - GtalkSharedStatus_StatusList + +typedef GPB_ENUM(GtalkSharedStatus_StatusList_FieldNumber) { + GtalkSharedStatus_StatusList_FieldNumber_Show = 7, + GtalkSharedStatus_StatusList_FieldNumber_StatusArray = 8, +}; + +@interface GtalkSharedStatus_StatusList : GPBMessage + + +@property(nonatomic, readwrite) GtalkSharedStatus_ShowType show; + +@property(nonatomic, readwrite) BOOL hasShow; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *statusArray; +/** The number of items in @c statusArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger statusArray_Count; + +@end + +#pragma mark - GtalkOtrQuery + +typedef GPB_ENUM(GtalkOtrQuery_FieldNumber) { + GtalkOtrQuery_FieldNumber_NosaveDefault = 1, + GtalkOtrQuery_FieldNumber_ItemArray = 2, + GtalkOtrQuery_FieldNumber_Etag = 3, + GtalkOtrQuery_FieldNumber_NotModified = 4, +}; + +@interface GtalkOtrQuery : GPBMessage + + +@property(nonatomic, readwrite) BOOL nosaveDefault; + +@property(nonatomic, readwrite) BOOL hasNosaveDefault; + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *itemArray; +/** The number of items in @c itemArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger itemArray_Count; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *etag; +/** Test to see if @c etag has been set. */ +@property(nonatomic, readwrite) BOOL hasEtag; + + +@property(nonatomic, readwrite) BOOL notModified; + +@property(nonatomic, readwrite) BOOL hasNotModified; +@end + +#pragma mark - GtalkOtrItem + +typedef GPB_ENUM(GtalkOtrItem_FieldNumber) { + GtalkOtrItem_FieldNumber_Jid = 1, + GtalkOtrItem_FieldNumber_Nosave = 2, + GtalkOtrItem_FieldNumber_ChangedByBuddy = 3, +}; + +@interface GtalkOtrItem : GPBMessage + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *jid; +/** Test to see if @c jid has been set. */ +@property(nonatomic, readwrite) BOOL hasJid; + + +@property(nonatomic, readwrite) BOOL nosave; + +@property(nonatomic, readwrite) BOOL hasNosave; + +@property(nonatomic, readwrite) BOOL changedByBuddy; + +@property(nonatomic, readwrite) BOOL hasChangedByBuddy; +@end + +#pragma mark - GtalkIdle + +typedef GPB_ENUM(GtalkIdle_FieldNumber) { + GtalkIdle_FieldNumber_Idle = 1, + GtalkIdle_FieldNumber_Away = 2, +}; + +@interface GtalkIdle : GPBMessage + + +@property(nonatomic, readwrite) BOOL idle; + +@property(nonatomic, readwrite) BOOL hasIdle; + +@property(nonatomic, readwrite) BOOL away; + +@property(nonatomic, readwrite) BOOL hasAway; +@end + +#pragma mark - GtalkPostAuthBatchQuery + +typedef GPB_ENUM(GtalkPostAuthBatchQuery_FieldNumber) { + GtalkPostAuthBatchQuery_FieldNumber_Available = 1, + GtalkPostAuthBatchQuery_FieldNumber_DeviceIdle = 2, + GtalkPostAuthBatchQuery_FieldNumber_MobileIndicator = 3, + GtalkPostAuthBatchQuery_FieldNumber_SharedStatusVersion = 4, + GtalkPostAuthBatchQuery_FieldNumber_RosterEtag = 5, + GtalkPostAuthBatchQuery_FieldNumber_OtrEtag = 6, + GtalkPostAuthBatchQuery_FieldNumber_AvatarHash = 7, + GtalkPostAuthBatchQuery_FieldNumber_VcardQueryStanzaId = 8, + GtalkPostAuthBatchQuery_FieldNumber_CapabilitiesExtFlags = 9, +}; + +@interface GtalkPostAuthBatchQuery : GPBMessage + + +@property(nonatomic, readwrite) BOOL available; + +@property(nonatomic, readwrite) BOOL hasAvailable; + +@property(nonatomic, readwrite) BOOL deviceIdle; + +@property(nonatomic, readwrite) BOOL hasDeviceIdle; + +@property(nonatomic, readwrite) BOOL mobileIndicator; + +@property(nonatomic, readwrite) BOOL hasMobileIndicator; + +@property(nonatomic, readwrite) int32_t sharedStatusVersion; + +@property(nonatomic, readwrite) BOOL hasSharedStatusVersion; + +@property(nonatomic, readwrite, copy, null_resettable) NSString *rosterEtag; +/** Test to see if @c rosterEtag has been set. */ +@property(nonatomic, readwrite) BOOL hasRosterEtag; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *otrEtag; +/** Test to see if @c otrEtag has been set. */ +@property(nonatomic, readwrite) BOOL hasOtrEtag; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *avatarHash; +/** Test to see if @c avatarHash has been set. */ +@property(nonatomic, readwrite) BOOL hasAvatarHash; + + +@property(nonatomic, readwrite, copy, null_resettable) NSString *vcardQueryStanzaId; +/** Test to see if @c vcardQueryStanzaId has been set. */ +@property(nonatomic, readwrite) BOOL hasVcardQueryStanzaId; + + +@property(nonatomic, readwrite) int32_t capabilitiesExtFlags; + +@property(nonatomic, readwrite) BOOL hasCapabilitiesExtFlags; +@end + +#pragma mark - GtalkStreamAck + +@interface GtalkStreamAck : GPBMessage + +@end + +#pragma mark - GtalkSelectiveAck + +typedef GPB_ENUM(GtalkSelectiveAck_FieldNumber) { + GtalkSelectiveAck_FieldNumber_IdArray = 1, +}; + +@interface GtalkSelectiveAck : GPBMessage + + +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *idArray; +/** The number of items in @c idArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger idArray_Count; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.m b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.m new file mode 100644 index 0000000..e41d416 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Protos/GtalkExtensions.pbobjc.m @@ -0,0 +1,1407 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: buzz/mobile/proto/gtalk_extensions.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + + #import "GtalkExtensions.pbobjc.h" +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GtalkGtalkExtensionsRoot + +@implementation GtalkGtalkExtensionsRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GtalkGtalkExtensionsRoot_FileDescriptor + +static GPBFileDescriptor *GtalkGtalkExtensionsRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"mobilegtalk" + objcPrefix:@"Gtalk" + syntax:GPBFileSyntaxProto2]; + } + return descriptor; +} + +#pragma mark - GtalkRosterQuery + +@implementation GtalkRosterQuery + +@dynamic hasEtag, etag; +@dynamic hasNotModified, notModified; +@dynamic itemArray, itemArray_Count; +@dynamic hasAvatarWidth, avatarWidth; +@dynamic hasAvatarHeight, avatarHeight; + +typedef struct GtalkRosterQuery__storage_ { + uint32_t _has_storage_[1]; + int32_t avatarWidth; + int32_t avatarHeight; + NSString *etag; + NSMutableArray *itemArray; +} GtalkRosterQuery__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "etag", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterQuery_FieldNumber_Etag, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkRosterQuery__storage_, etag), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "notModified", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterQuery_FieldNumber_NotModified, + .hasIndex = 1, + .offset = 2, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "itemArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkRosterItem), + .number = GtalkRosterQuery_FieldNumber_ItemArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkRosterQuery__storage_, itemArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "avatarWidth", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterQuery_FieldNumber_AvatarWidth, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkRosterQuery__storage_, avatarWidth), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeInt32, + }, + { + .name = "avatarHeight", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterQuery_FieldNumber_AvatarHeight, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkRosterQuery__storage_, avatarHeight), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkRosterQuery class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkRosterQuery__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\002\004\013\000\005\014\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkRosterItem + +@implementation GtalkRosterItem + +@dynamic hasJid, jid; +@dynamic hasName, name; +@dynamic hasSubscription, subscription; +@dynamic hasAsk, ask; +@dynamic groupArray, groupArray_Count; +@dynamic hasQuickContact, quickContact; +@dynamic hasDisplay, display; +@dynamic hasRejected, rejected; + +typedef struct GtalkRosterItem__storage_ { + uint32_t _has_storage_[1]; + GtalkRosterItem_SubscriptionType subscription; + GtalkRosterItem_AskType ask; + GtalkRosterItem_DisplayType display; + NSString *jid; + NSString *name; + NSMutableArray *groupArray; +} GtalkRosterItem__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "jid", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterItem_FieldNumber_Jid, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, jid), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterItem_FieldNumber_Name, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "subscription", + .dataTypeSpecific.enumDescFunc = GtalkRosterItem_SubscriptionType_EnumDescriptor, + .number = GtalkRosterItem_FieldNumber_Subscription, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, subscription), + .flags = (GPBFieldFlags)(GPBFieldRequired | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "ask", + .dataTypeSpecific.enumDescFunc = GtalkRosterItem_AskType_EnumDescriptor, + .number = GtalkRosterItem_FieldNumber_Ask, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, ask), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "groupArray", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterItem_FieldNumber_GroupArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, groupArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + { + .name = "quickContact", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterItem_FieldNumber_QuickContact, + .hasIndex = 4, + .offset = 5, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "display", + .dataTypeSpecific.enumDescFunc = GtalkRosterItem_DisplayType_EnumDescriptor, + .number = GtalkRosterItem_FieldNumber_Display, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkRosterItem__storage_, display), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "rejected", + .dataTypeSpecific.className = NULL, + .number = GtalkRosterItem_FieldNumber_Rejected, + .hasIndex = 7, + .offset = 8, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkRosterItem class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkRosterItem__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkRosterItem_SubscriptionType + +GPBEnumDescriptor *GtalkRosterItem_SubscriptionType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "None\000To\000From\000Both\000Remove\000"; + static const int32_t values[] = { + GtalkRosterItem_SubscriptionType_None, + GtalkRosterItem_SubscriptionType_To, + GtalkRosterItem_SubscriptionType_From, + GtalkRosterItem_SubscriptionType_Both, + GtalkRosterItem_SubscriptionType_Remove, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkRosterItem_SubscriptionType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkRosterItem_SubscriptionType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkRosterItem_SubscriptionType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkRosterItem_SubscriptionType_None: + case GtalkRosterItem_SubscriptionType_To: + case GtalkRosterItem_SubscriptionType_From: + case GtalkRosterItem_SubscriptionType_Both: + case GtalkRosterItem_SubscriptionType_Remove: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkRosterItem_AskType + +GPBEnumDescriptor *GtalkRosterItem_AskType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Subscribe\000"; + static const int32_t values[] = { + GtalkRosterItem_AskType_Subscribe, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkRosterItem_AskType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkRosterItem_AskType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkRosterItem_AskType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkRosterItem_AskType_Subscribe: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GtalkRosterItem_DisplayType + +GPBEnumDescriptor *GtalkRosterItem_DisplayType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Blocked\000Hidden\000Pinned\000"; + static const int32_t values[] = { + GtalkRosterItem_DisplayType_Blocked, + GtalkRosterItem_DisplayType_Hidden, + GtalkRosterItem_DisplayType_Pinned, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkRosterItem_DisplayType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkRosterItem_DisplayType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkRosterItem_DisplayType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkRosterItem_DisplayType_Blocked: + case GtalkRosterItem_DisplayType_Hidden: + case GtalkRosterItem_DisplayType_Pinned: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkRmqLastId + +@implementation GtalkRmqLastId + +@dynamic hasId_p, id_p; + +typedef struct GtalkRmqLastId__storage_ { + uint32_t _has_storage_[1]; + int64_t id_p; +} GtalkRmqLastId__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkRmqLastId_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkRmqLastId__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkRmqLastId class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkRmqLastId__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkRmqAck + +@implementation GtalkRmqAck + +@dynamic hasId_p, id_p; + +typedef struct GtalkRmqAck__storage_ { + uint32_t _has_storage_[1]; + int64_t id_p; +} GtalkRmqAck__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "id_p", + .dataTypeSpecific.className = NULL, + .number = GtalkRmqAck_FieldNumber_Id_p, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkRmqAck__storage_, id_p), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkRmqAck class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkRmqAck__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkVCard + +@implementation GtalkVCard + +@dynamic hasVersion, version; +@dynamic hasFullName, fullName; +@dynamic hasPhoto, photo; +@dynamic hasAvatarHash, avatarHash; +@dynamic hasModified, modified; + +typedef struct GtalkVCard__storage_ { + uint32_t _has_storage_[1]; + NSString *version; + NSString *fullName; + GtalkPhoto *photo; + NSString *avatarHash; +} GtalkVCard__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "version", + .dataTypeSpecific.className = NULL, + .number = GtalkVCard_FieldNumber_Version, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkVCard__storage_, version), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "fullName", + .dataTypeSpecific.className = NULL, + .number = GtalkVCard_FieldNumber_FullName, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkVCard__storage_, fullName), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "photo", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkPhoto), + .number = GtalkVCard_FieldNumber_Photo, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkVCard__storage_, photo), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "avatarHash", + .dataTypeSpecific.className = NULL, + .number = GtalkVCard_FieldNumber_AvatarHash, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkVCard__storage_, avatarHash), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "modified", + .dataTypeSpecific.className = NULL, + .number = GtalkVCard_FieldNumber_Modified, + .hasIndex = 4, + .offset = 5, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkVCard class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkVCard__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkPhoto + +@implementation GtalkPhoto + +@dynamic hasType, type; +@dynamic hasData_p, data_p; + +typedef struct GtalkPhoto__storage_ { + uint32_t _has_storage_[1]; + NSString *type; + NSString *data_p; +} GtalkPhoto__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "type", + .dataTypeSpecific.className = NULL, + .number = GtalkPhoto_FieldNumber_Type, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkPhoto__storage_, type), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "data_p", + .dataTypeSpecific.className = NULL, + .number = GtalkPhoto_FieldNumber_Data_p, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkPhoto__storage_, data_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkPhoto class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkPhoto__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkChatRead + +@implementation GtalkChatRead + +@dynamic hasUser, user; + +typedef struct GtalkChatRead__storage_ { + uint32_t _has_storage_[1]; + NSString *user; +} GtalkChatRead__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "user", + .dataTypeSpecific.className = NULL, + .number = GtalkChatRead_FieldNumber_User, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkChatRead__storage_, user), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkChatRead class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkChatRead__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkChatClosed + +@implementation GtalkChatClosed + +@dynamic hasUser, user; + +typedef struct GtalkChatClosed__storage_ { + uint32_t _has_storage_[1]; + NSString *user; +} GtalkChatClosed__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "user", + .dataTypeSpecific.className = NULL, + .number = GtalkChatClosed_FieldNumber_User, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkChatClosed__storage_, user), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkChatClosed class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkChatClosed__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkCapabilities + +@implementation GtalkCapabilities + +@dynamic hasNode, node; +@dynamic hasVer, ver; +@dynamic hasExt, ext; +@dynamic hasHash_p, hash_p; + +typedef struct GtalkCapabilities__storage_ { + uint32_t _has_storage_[1]; + NSString *node; + NSString *ver; + NSString *ext; + NSString *hash_p; +} GtalkCapabilities__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "node", + .dataTypeSpecific.className = NULL, + .number = GtalkCapabilities_FieldNumber_Node, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkCapabilities__storage_, node), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "ver", + .dataTypeSpecific.className = NULL, + .number = GtalkCapabilities_FieldNumber_Ver, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkCapabilities__storage_, ver), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "ext", + .dataTypeSpecific.className = NULL, + .number = GtalkCapabilities_FieldNumber_Ext, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkCapabilities__storage_, ext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "hash_p", + .dataTypeSpecific.className = NULL, + .number = GtalkCapabilities_FieldNumber_Hash_p, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkCapabilities__storage_, hash_p), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkCapabilities class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkCapabilities__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkSharedStatus + +@implementation GtalkSharedStatus + +@dynamic hasStatusMax, statusMax; +@dynamic hasStatusListMax, statusListMax; +@dynamic hasStatusListContentsMax, statusListContentsMax; +@dynamic hasStatus, status; +@dynamic hasShow, show; +@dynamic statusListArray, statusListArray_Count; +@dynamic hasInvisible, invisible; +@dynamic hasStatusMinVersion, statusMinVersion; + +typedef struct GtalkSharedStatus__storage_ { + uint32_t _has_storage_[1]; + int32_t statusMax; + int32_t statusListMax; + int32_t statusListContentsMax; + GtalkSharedStatus_ShowType show; + int32_t statusMinVersion; + NSString *status; + NSMutableArray *statusListArray; +} GtalkSharedStatus__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "statusMax", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_StatusMax, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, statusMax), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "statusListMax", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_StatusListMax, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, statusListMax), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "statusListContentsMax", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_StatusListContentsMax, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, statusListContentsMax), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "status", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_Status, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, status), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "show", + .dataTypeSpecific.enumDescFunc = GtalkSharedStatus_ShowType_EnumDescriptor, + .number = GtalkSharedStatus_FieldNumber_Show, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, show), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "statusListArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkSharedStatus_StatusList), + .number = GtalkSharedStatus_FieldNumber_StatusListArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, statusListArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeGroup, + }, + { + .name = "invisible", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_Invisible, + .hasIndex = 5, + .offset = 6, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "statusMinVersion", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_FieldNumber_StatusMinVersion, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkSharedStatus__storage_, statusMinVersion), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkSharedStatus class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkSharedStatus__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkSharedStatus_ShowType + +GPBEnumDescriptor *GtalkSharedStatus_ShowType_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "Default\000Dnd\000"; + static const int32_t values[] = { + GtalkSharedStatus_ShowType_Default, + GtalkSharedStatus_ShowType_Dnd, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkSharedStatus_ShowType) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkSharedStatus_ShowType_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkSharedStatus_ShowType_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkSharedStatus_ShowType_Default: + case GtalkSharedStatus_ShowType_Dnd: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkSharedStatus_StatusList + +@implementation GtalkSharedStatus_StatusList + +@dynamic hasShow, show; +@dynamic statusArray, statusArray_Count; + +typedef struct GtalkSharedStatus_StatusList__storage_ { + uint32_t _has_storage_[1]; + GtalkSharedStatus_ShowType show; + NSMutableArray *statusArray; +} GtalkSharedStatus_StatusList__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "show", + .dataTypeSpecific.enumDescFunc = GtalkSharedStatus_ShowType_EnumDescriptor, + .number = GtalkSharedStatus_StatusList_FieldNumber_Show, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkSharedStatus_StatusList__storage_, show), + .flags = (GPBFieldFlags)(GPBFieldRequired | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "statusArray", + .dataTypeSpecific.className = NULL, + .number = GtalkSharedStatus_StatusList_FieldNumber_StatusArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkSharedStatus_StatusList__storage_, statusArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkSharedStatus_StatusList class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkSharedStatus_StatusList__storage_) + flags:GPBDescriptorInitializationFlag_None]; + [localDescriptor setupContainingMessageClassName:GPBStringifySymbol(GtalkSharedStatus)]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkOtrQuery + +@implementation GtalkOtrQuery + +@dynamic hasNosaveDefault, nosaveDefault; +@dynamic itemArray, itemArray_Count; +@dynamic hasEtag, etag; +@dynamic hasNotModified, notModified; + +typedef struct GtalkOtrQuery__storage_ { + uint32_t _has_storage_[1]; + NSMutableArray *itemArray; + NSString *etag; +} GtalkOtrQuery__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "nosaveDefault", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrQuery_FieldNumber_NosaveDefault, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "itemArray", + .dataTypeSpecific.className = GPBStringifySymbol(GtalkOtrItem), + .number = GtalkOtrQuery_FieldNumber_ItemArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkOtrQuery__storage_, itemArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "etag", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrQuery_FieldNumber_Etag, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GtalkOtrQuery__storage_, etag), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "notModified", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrQuery_FieldNumber_NotModified, + .hasIndex = 3, + .offset = 4, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkOtrQuery class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkOtrQuery__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkOtrItem + +@implementation GtalkOtrItem + +@dynamic hasJid, jid; +@dynamic hasNosave, nosave; +@dynamic hasChangedByBuddy, changedByBuddy; + +typedef struct GtalkOtrItem__storage_ { + uint32_t _has_storage_[1]; + NSString *jid; +} GtalkOtrItem__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "jid", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrItem_FieldNumber_Jid, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GtalkOtrItem__storage_, jid), + .flags = GPBFieldRequired, + .dataType = GPBDataTypeString, + }, + { + .name = "nosave", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrItem_FieldNumber_Nosave, + .hasIndex = 1, + .offset = 2, // Stored in _has_storage_ to save space. + .flags = GPBFieldRequired, + .dataType = GPBDataTypeBool, + }, + { + .name = "changedByBuddy", + .dataTypeSpecific.className = NULL, + .number = GtalkOtrItem_FieldNumber_ChangedByBuddy, + .hasIndex = 3, + .offset = 4, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkOtrItem class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkOtrItem__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkIdle + +@implementation GtalkIdle + +@dynamic hasIdle, idle; +@dynamic hasAway, away; + +typedef struct GtalkIdle__storage_ { + uint32_t _has_storage_[1]; +} GtalkIdle__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "idle", + .dataTypeSpecific.className = NULL, + .number = GtalkIdle_FieldNumber_Idle, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldRequired, + .dataType = GPBDataTypeBool, + }, + { + .name = "away", + .dataTypeSpecific.className = NULL, + .number = GtalkIdle_FieldNumber_Away, + .hasIndex = 2, + .offset = 3, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkIdle class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkIdle__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkPostAuthBatchQuery + +@implementation GtalkPostAuthBatchQuery + +@dynamic hasAvailable, available; +@dynamic hasDeviceIdle, deviceIdle; +@dynamic hasMobileIndicator, mobileIndicator; +@dynamic hasSharedStatusVersion, sharedStatusVersion; +@dynamic hasRosterEtag, rosterEtag; +@dynamic hasOtrEtag, otrEtag; +@dynamic hasAvatarHash, avatarHash; +@dynamic hasVcardQueryStanzaId, vcardQueryStanzaId; +@dynamic hasCapabilitiesExtFlags, capabilitiesExtFlags; + +typedef struct GtalkPostAuthBatchQuery__storage_ { + uint32_t _has_storage_[1]; + int32_t sharedStatusVersion; + int32_t capabilitiesExtFlags; + NSString *rosterEtag; + NSString *otrEtag; + NSString *avatarHash; + NSString *vcardQueryStanzaId; +} GtalkPostAuthBatchQuery__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "available", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_Available, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldRequired, + .dataType = GPBDataTypeBool, + }, + { + .name = "deviceIdle", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_DeviceIdle, + .hasIndex = 2, + .offset = 3, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "mobileIndicator", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_MobileIndicator, + .hasIndex = 4, + .offset = 5, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "sharedStatusVersion", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_SharedStatusVersion, + .hasIndex = 6, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, sharedStatusVersion), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "rosterEtag", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_RosterEtag, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, rosterEtag), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "otrEtag", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_OtrEtag, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, otrEtag), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "avatarHash", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_AvatarHash, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, avatarHash), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "vcardQueryStanzaId", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_VcardQueryStanzaId, + .hasIndex = 10, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, vcardQueryStanzaId), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "capabilitiesExtFlags", + .dataTypeSpecific.className = NULL, + .number = GtalkPostAuthBatchQuery_FieldNumber_CapabilitiesExtFlags, + .hasIndex = 11, + .offset = (uint32_t)offsetof(GtalkPostAuthBatchQuery__storage_, capabilitiesExtFlags), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkPostAuthBatchQuery class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkPostAuthBatchQuery__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - Enum GtalkPostAuthBatchQuery_CapabilitiesExtFlags + +GPBEnumDescriptor *GtalkPostAuthBatchQuery_CapabilitiesExtFlags_EnumDescriptor(void) { + static GPBEnumDescriptor *descriptor = NULL; + if (!descriptor) { + static const char *valueNames = + "HasVoiceV1\000HasVideoV1\000HasCameraV1\000HasPmu" + "cV1\000"; + static const int32_t values[] = { + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVoiceV1, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVideoV1, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasCameraV1, + GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasPmucV1, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GtalkPostAuthBatchQuery_CapabilitiesExtFlags) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GtalkPostAuthBatchQuery_CapabilitiesExtFlags_IsValidValue]; + if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GtalkPostAuthBatchQuery_CapabilitiesExtFlags_IsValidValue(int32_t value__) { + switch (value__) { + case GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVoiceV1: + case GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasVideoV1: + case GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasCameraV1: + case GtalkPostAuthBatchQuery_CapabilitiesExtFlags_HasPmucV1: + return YES; + default: + return NO; + } +} + +#pragma mark - GtalkStreamAck + +@implementation GtalkStreamAck + + +typedef struct GtalkStreamAck__storage_ { + uint32_t _has_storage_[1]; +} GtalkStreamAck__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkStreamAck class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:NULL + fieldCount:0 + storageSize:sizeof(GtalkStreamAck__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GtalkSelectiveAck + +@implementation GtalkSelectiveAck + +@dynamic idArray, idArray_Count; + +typedef struct GtalkSelectiveAck__storage_ { + uint32_t _has_storage_[1]; + NSMutableArray *idArray; +} GtalkSelectiveAck__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "idArray", + .dataTypeSpecific.className = NULL, + .number = GtalkSelectiveAck_FieldNumber_IdArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GtalkSelectiveAck__storage_, idArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GtalkSelectiveAck class] + rootClass:[GtalkGtalkExtensionsRoot class] + file:GtalkGtalkExtensionsRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GtalkSelectiveAck__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FIRMessaging.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FIRMessaging.h new file mode 100644 index 0000000..d0ccfac --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FIRMessaging.h @@ -0,0 +1,552 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * @related FIRMessaging + * + * The completion handler invoked when the registration token returns. + * If the call fails we return the appropriate `error code`, described by + * `FIRMessagingError`. + * + * @param FCMToken The valid registration token returned by FCM. + * @param error The error describing why a token request failed. The error code + * will match a value from the FIRMessagingError enumeration. + */ +typedef void(^FIRMessagingFCMTokenFetchCompletion)(NSString * _Nullable FCMToken, + NSError * _Nullable error) + NS_SWIFT_NAME(MessagingFCMTokenFetchCompletion); + + +/** + * @related FIRMessaging + * + * The completion handler invoked when the registration token deletion request is + * completed. If the call fails we return the appropriate `error code`, described + * by `FIRMessagingError`. + * + * @param error The error describing why a token deletion failed. The error code + * will match a value from the FIRMessagingError enumeration. + */ +typedef void(^FIRMessagingDeleteFCMTokenCompletion)(NSError * _Nullable error) + NS_SWIFT_NAME(MessagingDeleteFCMTokenCompletion); + +/** + * Callback to invoke once the HTTP call to FIRMessaging backend for updating + * subscription finishes. + * + * @param error The error which occurred while updating the subscription topic + * on the FIRMessaging server. This will be nil in case the operation + * was successful, or if the operation was cancelled. + */ +typedef void (^FIRMessagingTopicOperationCompletion)(NSError *_Nullable error); + +/** + * The completion handler invoked once the data connection with FIRMessaging is + * established. The data connection is used to send a continuous stream of + * data and all the FIRMessaging data notifications arrive through this connection. + * Once the connection is established we invoke the callback with `nil` error. + * Correspondingly if we get an error while trying to establish a connection + * we invoke the handler with an appropriate error object and do an + * exponential backoff to try and connect again unless successful. + * + * @param error The error object if any describing why the data connection + * to FIRMessaging failed. + */ +typedef void(^FIRMessagingConnectCompletion)(NSError * __nullable error) + NS_SWIFT_NAME(MessagingConnectCompletion) + __deprecated_msg("Please listen for the FIRMessagingConnectionStateChangedNotification " + "NSNotification instead."); + +#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 +/** + * Notification sent when the upstream message has been delivered + * successfully to the server. The notification object will be the messageID + * of the successfully delivered message. + */ +FOUNDATION_EXPORT const NSNotificationName FIRMessagingSendSuccessNotification + NS_SWIFT_NAME(MessagingSendSuccess); + +/** + * Notification sent when the upstream message was failed to be sent to the + * server. The notification object will be the messageID of the failed + * message. The userInfo dictionary will contain the relevant error + * information for the failure. + */ +FOUNDATION_EXPORT const NSNotificationName FIRMessagingSendErrorNotification + NS_SWIFT_NAME(MessagingSendError); + +/** + * Notification sent when the Firebase messaging server deletes pending + * messages due to exceeded storage limits. This may occur, for example, when + * the device cannot be reached for an extended period of time. + * + * It is recommended to retrieve any missing messages directly from the + * server. + */ +FOUNDATION_EXPORT const NSNotificationName FIRMessagingMessagesDeletedNotification + NS_SWIFT_NAME(MessagingMessagesDeleted); + +/** + * Notification sent when Firebase Messaging establishes or disconnects from + * an FCM socket connection. You can query the connection state in this + * notification by checking the `isDirectChannelEstablished` property of FIRMessaging. + */ +FOUNDATION_EXPORT const NSNotificationName FIRMessagingConnectionStateChangedNotification + NS_SWIFT_NAME(MessagingConnectionStateChanged); + +/** + * Notification sent when the FCM registration token has been refreshed. Please use the + * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and + * updated tokens. + */ +FOUNDATION_EXPORT const NSNotificationName + FIRMessagingRegistrationTokenRefreshedNotification + NS_SWIFT_NAME(MessagingRegistrationTokenRefreshed); +#else +/** + * Notification sent when the upstream message has been delivered + * successfully to the server. The notification object will be the messageID + * of the successfully delivered message. + */ +FOUNDATION_EXPORT NSString *const FIRMessagingSendSuccessNotification + NS_SWIFT_NAME(MessagingSendSuccessNotification); + +/** + * Notification sent when the upstream message was failed to be sent to the + * server. The notification object will be the messageID of the failed + * message. The userInfo dictionary will contain the relevant error + * information for the failure. + */ +FOUNDATION_EXPORT NSString *const FIRMessagingSendErrorNotification + NS_SWIFT_NAME(MessagingSendErrorNotification); + +/** + * Notification sent when the Firebase messaging server deletes pending + * messages due to exceeded storage limits. This may occur, for example, when + * the device cannot be reached for an extended period of time. + * + * It is recommended to retrieve any missing messages directly from the + * server. + */ +FOUNDATION_EXPORT NSString *const FIRMessagingMessagesDeletedNotification + NS_SWIFT_NAME(MessagingMessagesDeletedNotification); + +/** + * Notification sent when Firebase Messaging establishes or disconnects from + * an FCM socket connection. You can query the connection state in this + * notification by checking the `isDirectChannelEstablished` property of FIRMessaging. + */ +FOUNDATION_EXPORT NSString *const FIRMessagingConnectionStateChangedNotification + NS_SWIFT_NAME(MessagingConnectionStateChangedNotification); + +/** + * Notification sent when the FCM registration token has been refreshed. Please use the + * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and + * updated tokens. + */ +FOUNDATION_EXPORT NSString *const FIRMessagingRegistrationTokenRefreshedNotification + NS_SWIFT_NAME(MessagingRegistrationTokenRefreshedNotification); +#endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 + +/** + * @enum FIRMessagingError + */ +typedef NS_ENUM(NSUInteger, FIRMessagingError) { + /// Unknown error. + FIRMessagingErrorUnknown = 0, + + /// FIRMessaging couldn't validate request from this client. + FIRMessagingErrorAuthentication = 1, + + /// InstanceID service cannot be accessed. + FIRMessagingErrorNoAccess = 2, + + /// Request to InstanceID backend timed out. + FIRMessagingErrorTimeout = 3, + + /// No network available to reach the servers. + FIRMessagingErrorNetwork = 4, + + /// Another similar operation in progress, bailing this one. + FIRMessagingErrorOperationInProgress = 5, + + /// Some parameters of the request were invalid. + FIRMessagingErrorInvalidRequest = 7, + + /// Topic name is invalid for subscription/unsubscription. + FIRMessagingErrorInvalidTopicName = 8, + +} NS_SWIFT_NAME(MessagingError); + +/// Status for the downstream message received by the app. +typedef NS_ENUM(NSInteger, FIRMessagingMessageStatus) { + /// Unknown status. + FIRMessagingMessageStatusUnknown, + /// New downstream message received by the app. + FIRMessagingMessageStatusNew, +} NS_SWIFT_NAME(MessagingMessageStatus); + +/** + * The APNS token type for the app. If the token type is set to `UNKNOWN` + * Firebase Messaging will implicitly try to figure out what the actual token type + * is from the provisioning profile. + * Unless you really need to specify the type, you should use the `APNSToken` + * property instead. + */ +typedef NS_ENUM(NSInteger, FIRMessagingAPNSTokenType) { + /// Unknown token type. + FIRMessagingAPNSTokenTypeUnknown, + /// Sandbox token type. + FIRMessagingAPNSTokenTypeSandbox, + /// Production token type. + FIRMessagingAPNSTokenTypeProd, +} NS_SWIFT_NAME(MessagingAPNSTokenType); + +/// Information about a downstream message received by the app. +NS_SWIFT_NAME(MessagingMessageInfo) +@interface FIRMessagingMessageInfo : NSObject + +/// The status of the downstream message +@property(nonatomic, readonly, assign) FIRMessagingMessageStatus status; + +@end + +/** + * A remote data message received by the app via FCM (not just the APNs interface). + * + * This is only for devices running iOS 10 or above. To support devices running iOS 9 or below, use + * the local and remote notifications handlers defined in UIApplicationDelegate protocol. + */ +NS_SWIFT_NAME(MessagingRemoteMessage) +@interface FIRMessagingRemoteMessage : NSObject + +/// The message ID of downstream message. +@property(nonatomic, readonly, copy) NSString *messageID; +/// The downstream message received by the application. +@property(nonatomic, readonly, strong) NSDictionary *appData; + +@end + +@class FIRMessaging; +/** + * A protocol to handle token update or data message delivery from FCM. + * + */ +NS_SWIFT_NAME(MessagingDelegate) +@protocol FIRMessagingDelegate + +@optional +/// This method will be called once a token is available, or has been refreshed. Typically it +/// will be called once per app start, but may be called more often, if token is invalidated or +/// updated. In this method, you should perform operations such as: +/// +/// * Uploading the FCM token to your application server, so targeted notifications can be sent. +/// +/// * Subscribing to any topics. +- (void)messaging:(FIRMessaging *)messaging + didReceiveRegistrationToken:(NSString *)fcmToken + NS_SWIFT_NAME(messaging(_:didReceiveRegistrationToken:)); + +/// This method is called on iOS 10+ devices to handle data messages received via FCM +/// direct channel (not via APNS). For iOS 9 and below, the direct channel data message +/// is handled by the UIApplicationDelegate's -application:didReceiveRemoteNotification: method. +/// You can enable all direct channel data messages to be delivered in FIRMessagingDelegate +/// by setting the flag `useMessagingDelegateForDirectMessages` to true. +- (void)messaging:(FIRMessaging *)messaging + didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage + NS_SWIFT_NAME(messaging(_:didReceive:)) + __IOS_AVAILABLE(10.0); + +@end + +/** + * Firebase Messaging lets you reliably deliver messages at no cost. + * + * To send or receive messages, the app must get a + * registration token from FIRInstanceID. This token authorizes an + * app server to send messages to an app instance. + * + * In order to receive FIRMessaging messages, declare + * `application:didReceiveRemoteNotification::fetchCompletionHandler:`. + */ +NS_SWIFT_NAME(Messaging) +@interface FIRMessaging : NSObject + +/** + * Delegate to handle FCM token refreshes, and remote data messages received via FCM direct channel. + */ +@property(nonatomic, weak, nullable) id delegate; + +/** + * When set to `YES`, Firebase Messaging will automatically establish a socket-based, direct + * channel to the FCM server. Enable this only if you are sending upstream messages or + * receiving non-APNS, data-only messages in foregrounded apps. + * Default is `NO`. + */ +@property(nonatomic) BOOL shouldEstablishDirectChannel; + +/** + * Returns `YES` if the direct channel to the FCM server is active, and `NO` otherwise. + */ +@property(nonatomic, readonly) BOOL isDirectChannelEstablished; + +/* + * Whether direct channel message should only use FIRMessagingDelegate messaging(_:didReceive:) + * for message delivery callback. The default value is false. If you need to change + * the default, set FirebaseMessagingUseMessagingDelegateForDirectChannel to true in + * your application’s Info.plist. + * + * If false, the message via direct channel for iOS 9 and below is still delivered in + * `-UIApplicationDelegate application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`, + * and the FIRMessagingRemoteMessage object and its associated data will be unavailable. + * For iOS 10 and above, it is still delivered in `FIRMessagingDelegate messaging(_:didReceive:)`. + * + * If true, the data message sent by direct channel will be delivered via + * `FIRMessagingDelegate messaging(_:didReceive:)` and across all iOS versions. + */ +@property(nonatomic, assign) BOOL useMessagingDelegateForDirectChannel; + +/** + * FIRMessaging + * + * @return An instance of FIRMessaging. + */ ++ (instancetype)messaging NS_SWIFT_NAME(messaging()); + +/** + * Unavailable. Use +messaging instead. + */ +- (instancetype)init __attribute__((unavailable("Use +messaging instead."))); + +#pragma mark - APNS + +/** + * This property is used to set the APNS Token received by the application delegate. + * + * FIRMessaging uses method swizzling to ensure that the APNS token is set + * automatically. However, if you have disabled swizzling by setting + * `FirebaseAppDelegateProxyEnabled` to `NO` in your app's + * Info.plist, you should manually set the APNS token in your application + * delegate's `-application:didRegisterForRemoteNotificationsWithDeviceToken:` + * method. + * + * If you would like to set the type of the APNS token, rather than relying on + * automatic detection, see: `-setAPNSToken:type:`. + */ +@property(nonatomic, copy, nullable) NSData *APNSToken NS_SWIFT_NAME(apnsToken); + +/** + * Set APNS token for the application. This APNS token will be used to register + * with Firebase Messaging using `FCMToken` or + * `tokenWithAuthorizedEntity:scope:options:handler`. + * + * @param apnsToken The APNS token for the application. + * @param type The type of APNS token. Debug builds should use + * FIRMessagingAPNSTokenTypeSandbox. Alternatively, you can supply + * FIRMessagingAPNSTokenTypeUnknown to have the type automatically + * detected based on your provisioning profile. + */ +- (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type; + +#pragma mark - FCM Tokens + +/** + * Is Firebase Messaging token auto generation enabled? If this flag is disabled, + * Firebase Messaging will not generate token automatically for message delivery. + * + * If this flag is disabled, Firebase Messaging does not generate new tokens automatically for + * message delivery. If this flag is enabled, FCM generates a registration token on application + * start when there is no existing valid token. FCM also generates a new token when an existing + * token is deleted. + * + * This setting is persisted, and is applied on future + * invocations of your application. Once explicitly set, it overrides any + * settings in your Info.plist. + * + * By default, FCM automatic initialization is enabled. If you need to change the + * default (for example, because you want to prompt the user before getting token) + * set FirebaseMessagingAutoInitEnabled to false in your application's Info.plist. + */ +@property(nonatomic, assign, getter=isAutoInitEnabled) BOOL autoInitEnabled; + +/** + * The FCM token is used to identify this device so that FCM can send notifications to it. + * It is associated with your APNS token when the APNS token is supplied, so that sending + * messages to the FCM token will be delivered over APNS. + * + * The FCM token is sometimes refreshed automatically. In your FIRMessaging delegate, the + * delegate method `messaging:didReceiveRegistrationToken:` will be called once a token is + * available, or has been refreshed. Typically it should be called once per app start, but + * may be called more often, if token is invalidated or updated. + * + * Once you have an FCM token, you should send it to your application server, so it can use + * the FCM token to send notifications to your device. + */ +@property(nonatomic, readonly, nullable) NSString *FCMToken NS_SWIFT_NAME(fcmToken); + + +/** + * Retrieves an FCM registration token for a particular Sender ID. This can be used to allow + * multiple senders to send notifications to the same device. By providing a different Sender + * ID than your default when fetching a token, you can create a new FCM token which you can + * give to a different sender. Both tokens will deliver notifications to your device, and you + * can revoke a token when you need to. + * + * This registration token is not cached by FIRMessaging. FIRMessaging should have an APNS + * token set before calling this to ensure that notifications can be delivered via APNS using + * this FCM token. You may re-retrieve the FCM token once you have the APNS token set, to + * associate it with the FCM token. The default FCM token is automatically associated with + * the APNS token, if the APNS token data is available. + * + * @param senderID The Sender ID for a particular Firebase project. + * @param completion The completion handler to handle the token request. + */ +- (void)retrieveFCMTokenForSenderID:(NSString *)senderID + completion:(FIRMessagingFCMTokenFetchCompletion)completion + NS_SWIFT_NAME(retrieveFCMToken(forSenderID:completion:)); + + +/** + * Invalidates an FCM token for a particular Sender ID. That Sender ID cannot no longer send + * notifications to that FCM token. + * + * @param senderID The senderID for a particular Firebase project. + * @param completion The completion handler to handle the token deletion. + */ +- (void)deleteFCMTokenForSenderID:(NSString *)senderID + completion:(FIRMessagingDeleteFCMTokenCompletion)completion + NS_SWIFT_NAME(deleteFCMToken(forSenderID:completion:)); + + +#pragma mark - FCM Direct Channel + +/** + * Create a FIRMessaging data connection which will be used to send the data notifications + * sent by your server. It will also be used to send ACKS and other messages based + * on the FIRMessaging ACKS and other messages based on the FIRMessaging protocol. + * + * + * @param handler The handler to be invoked once the connection is established. + * If the connection fails we invoke the handler with an + * appropriate error code letting you know why it failed. At + * the same time, FIRMessaging performs exponential backoff to retry + * establishing a connection and invoke the handler when successful. + */ +- (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler + NS_SWIFT_NAME(connect(handler:)) + __deprecated_msg("Please use the shouldEstablishDirectChannel property instead."); + +/** + * Disconnect the current FIRMessaging data connection. This stops any attempts to + * connect to FIRMessaging. Calling this on an already disconnected client is a no-op. + * + * Call this before `teardown` when your app is going to the background. + * Since the FIRMessaging connection won't be allowed to live when in the background, it is + * prudent to close the connection. + */ +- (void)disconnect + __deprecated_msg("Please use the shouldEstablishDirectChannel property instead."); + +#pragma mark - Topics + +/** + * Asynchronously subscribes to a topic. + * + * @param topic The name of the topic, for example, @"sports". + */ +- (void)subscribeToTopic:(NSString *)topic NS_SWIFT_NAME(subscribe(toTopic:)); + +/** + * Asynchronously subscribe to the provided topic, retrying on failure. + * + * @param topic The topic name to subscribe to, for example, @"sports". + * @param completion The completion that is invoked once the subscribe call ends. + * In case of success, nil error is returned. Otherwise, an + * appropriate error object is returned. + */ +- (void)subscribeToTopic:(nonnull NSString *)topic + completion:(nullable FIRMessagingTopicOperationCompletion)completion; + +/** + * Asynchronously unsubscribe from a topic. + * + * @param topic The name of the topic, for example @"sports". + */ +- (void)unsubscribeFromTopic:(NSString *)topic NS_SWIFT_NAME(unsubscribe(fromTopic:)); + +/** + * Asynchronously unsubscribe from the provided topic, retrying on failure. + * + * @param topic The topic name to unsubscribe from, for example @"sports". + * @param completion The completion that is invoked once the unsubscribe call ends. + * In case of success, nil error is returned. Otherwise, an + * appropriate error object is returned. + */ +- (void)unsubscribeFromTopic:(nonnull NSString *)topic + completion:(nullable FIRMessagingTopicOperationCompletion)completion; + +#pragma mark - Upstream + +/** + * Sends an upstream ("device to cloud") message. + * + * The message is queued if we don't have an active connection. + * You can only use the upstream feature if your FCM implementation + * uses the XMPP server protocol. + * + * @param message Key/Value pairs to be sent. Values must be String, any + * other type will be ignored. + * @param receiver A string identifying the receiver of the message. For FCM + * project IDs the value is `SENDER_ID@gcm.googleapis.com`. + * @param messageID The ID of the message. This is generated by the application. It + * must be unique for each message generated by this application. + * It allows error callbacks and debugging, to uniquely identify + * each message. + * @param ttl The time to live for the message. In case we aren't able to + * send the message before the TTL expires we will send you a + * callback. If 0, we'll attempt to send immediately and return + * an error if we're not connected. Otherwise, the message will + * be queued. As for server-side messages, we don't return an error + * if the message has been dropped because of TTL; this can happen + * on the server side, and it would require extra communication. + */ +- (void)sendMessage:(NSDictionary *)message + to:(NSString *)receiver + withMessageID:(NSString *)messageID + timeToLive:(int64_t)ttl; + +#pragma mark - Analytics + +/** + * Use this to track message delivery and analytics for messages, typically + * when you receive a notification in `application:didReceiveRemoteNotification:`. + * However, you only need to call this if you set the `FirebaseAppDelegateProxyEnabled` + * flag to `NO` in your Info.plist. If `FirebaseAppDelegateProxyEnabled` is either missing + * or set to `YES` in your Info.plist, the library will call this automatically. + * + * @param message The downstream message received by the application. + * + * @return Information about the downstream message. + */ +- (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FirebaseMessaging.h b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FirebaseMessaging.h new file mode 100755 index 0000000..ef081c9 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/Firebase/Messaging/Public/FirebaseMessaging.h @@ -0,0 +1,17 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRMessaging.h" diff --git a/My Mind/Pods/FirebaseMessaging/LICENSE b/My Mind/Pods/FirebaseMessaging/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseMessaging/README.md b/My Mind/Pods/FirebaseMessaging/README.md new file mode 100644 index 0000000..d414a4c --- /dev/null +++ b/My Mind/Pods/FirebaseMessaging/README.md @@ -0,0 +1,193 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Code Formatting + +Travis will verify that any code changes are done in a style compliant way. Install +`clang-format` and `swiftformat`. +This command will get the right `clang-format` version: + +`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/0743d748ba8b41eec074a0a787dc80219142c525/Formula/clang-format.rb` + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorage.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorage.m new file mode 100644 index 0000000..82dcbfa --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorage.m @@ -0,0 +1,251 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Public/FIRStorage.h" + +#import "FIRStorageComponent.h" +#import "FIRStorageConstants_Private.h" +#import "FIRStoragePath.h" +#import "FIRStorageReference_Private.h" +#import "FIRStorageTokenAuthorizer.h" +#import "FIRStorageUtils.h" +#import "FIRStorage_Private.h" +#import "Public/FIRStorageReference.h" + +#import +#import +#import +#import + +#import +#import + +static NSMutableDictionary< + NSString * /* app name */, + NSMutableDictionary *> *_fetcherServiceMap; +static GTMSessionFetcherRetryBlock _retryWhenOffline; + +@interface FIRStorage () { + /// Stored Auth reference, if it exists. This needs to be stored for `copyWithZone:`. + id _Nullable _auth; +} +@end + +@implementation FIRStorage + ++ (void)initialize { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _retryWhenOffline = ^(BOOL suggestedWillRetry, NSError *GTM_NULLABLE_TYPE error, + GTMSessionFetcherRetryResponse response) { + bool shouldRetry = suggestedWillRetry; + // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we + // special-case it here. + if (!shouldRetry && error) { + shouldRetry = error.code == NSURLErrorNotConnectedToInternet; + } + response(shouldRetry); + }; + _fetcherServiceMap = [[NSMutableDictionary alloc] init]; + }); +} + ++ (GTMSessionFetcherService *)fetcherServiceForApp:(FIRApp *)app + bucket:(NSString *)bucket + auth:(nullable id)auth { + @synchronized(_fetcherServiceMap) { + NSMutableDictionary *bucketMap = _fetcherServiceMap[app.name]; + if (!bucketMap) { + bucketMap = [[NSMutableDictionary alloc] init]; + _fetcherServiceMap[app.name] = bucketMap; + } + + GTMSessionFetcherService *fetcherService = bucketMap[bucket]; + if (!fetcherService) { + fetcherService = [[GTMSessionFetcherService alloc] init]; + [fetcherService setRetryEnabled:YES]; + [fetcherService setRetryBlock:_retryWhenOffline]; + FIRStorageTokenAuthorizer *authorizer = + [[FIRStorageTokenAuthorizer alloc] initWithGoogleAppID:app.options.googleAppID + fetcherService:fetcherService + authProvider:auth]; + [fetcherService setAuthorizer:authorizer]; + bucketMap[bucket] = fetcherService; + } + return fetcherService; + } +} + ++ (void)setGTMSessionFetcherLoggingEnabled:(BOOL)isLoggingEnabled { + [GTMSessionFetcher setLoggingEnabled:isLoggingEnabled]; +} + ++ (instancetype)storage { + return [self storageForApp:[FIRApp defaultApp]]; +} + ++ (instancetype)storageForApp:(FIRApp *)app { + if (app.options.storageBucket) { + NSString *url = [app.options.storageBucket isEqualToString:@""] + ? @"" + : [@"gs://" stringByAppendingString:app.options.storageBucket]; + return [self storageForApp:app URL:url]; + } else { + NSString *const kAppNotConfiguredMessage = + @"No default Storage bucket found. Did you configure Firebase Storage properly?"; + [NSException raise:NSInvalidArgumentException format:kAppNotConfiguredMessage]; + return nil; + } +} + ++ (instancetype)storageWithURL:(NSString *)url { + return [self storageForApp:[FIRApp defaultApp] URL:url]; +} + ++ (instancetype)storageForApp:(FIRApp *)app URL:(NSString *)url { + NSString *bucket; + if ([url isEqualToString:@""]) { + bucket = @""; + } else { + FIRStoragePath *path; + + @try { + path = [FIRStoragePath pathFromGSURI:url]; + } @catch (NSException *e) { + [NSException raise:NSInternalInconsistencyException + format:@"URI must be in the form of gs:///"]; + } + + if (path.object != nil && ![path.object isEqualToString:@""]) { + [NSException raise:NSInternalInconsistencyException + format:@"Storage bucket cannot be initialized with a path"]; + } + + bucket = path.bucket; + } + + // Retrieve the instance provider from the app's container to inject dependencies as needed. + id provider = + FIR_COMPONENT(FIRStorageMultiBucketProvider, app.container); + return [provider storageForBucket:bucket]; +} + +- (instancetype)initWithApp:(FIRApp *)app + bucket:(NSString *)bucket + auth:(nullable id)auth { + self = [super init]; + if (self) { + _app = app; + _auth = auth; + _storageBucket = bucket; + _dispatchQueue = dispatch_queue_create("com.google.firebase.storage", DISPATCH_QUEUE_SERIAL); + _fetcherServiceForApp = [FIRStorage fetcherServiceForApp:_app bucket:bucket auth:auth]; + _maxDownloadRetryTime = 600.0; + _maxOperationRetryTime = 120.0; + _maxUploadRetryTime = 600.0; + } + return self; +} + +#pragma mark - NSObject overrides + +- (instancetype)copyWithZone:(NSZone *)zone { + FIRStorage *storage = + [[[self class] allocWithZone:zone] initWithApp:_app bucket:_storageBucket auth:_auth]; + storage.callbackQueue = _callbackQueue; + return storage; +} + +// Two FIRStorage objects are equal if they use the same app +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[FIRStorage class]]) { + return NO; + } + + BOOL isEqualObject = [self isEqualToFIRStorage:(FIRStorage *)object]; + return isEqualObject; +} + +- (BOOL)isEqualToFIRStorage:(FIRStorage *)storage { + BOOL isEqual = + [_app isEqual:storage.app] && [_storageBucket isEqualToString:storage.storageBucket]; + return isEqual; +} + +- (NSUInteger)hash { + NSUInteger hash = [_app hash] ^ [_callbackQueue hash]; + return hash; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p: %@", [self class], self, _app]; +} + +#pragma mark - Public methods + +- (FIRStorageReference *)reference { + FIRStoragePath *path = [[FIRStoragePath alloc] initWithBucket:_storageBucket object:nil]; + return [[FIRStorageReference alloc] initWithStorage:self path:path]; +} + +- (FIRStorageReference *)referenceForURL:(NSString *)string { + FIRStoragePath *path = [FIRStoragePath pathFromString:string]; + + // If no default bucket exists (empty string), accept anything. + if ([_storageBucket isEqual:@""]) { + FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path]; + return reference; + } + + // If there exists a default bucket, throw if provided a different bucket. + if (![path.bucket isEqual:_storageBucket]) { + NSString *const kInvalidBucketFormat = + @"Provided bucket: %@ does not match the Storage bucket of the current instance: %@"; + [NSException raise:NSInvalidArgumentException + format:kInvalidBucketFormat, path.bucket, _storageBucket]; + } + + FIRStorageReference *reference = [[FIRStorageReference alloc] initWithStorage:self path:path]; + return reference; +} + +- (FIRStorageReference *)referenceWithPath:(NSString *)string { + FIRStorageReference *reference = [[self reference] child:string]; + return reference; +} + +- (void)setCallbackQueue:(dispatch_queue_t)callbackQueue { + _fetcherServiceForApp.callbackQueue = callbackQueue; +} + +#pragma mark - Background tasks + ++ (void)enableBackgroundTasks:(BOOL)isEnabled { + [NSException raise:NSGenericException format:@"enableBackgroundTasks not implemented"]; +} + +- (NSArray *)uploadTasks { + [NSException raise:NSGenericException format:@"getUploadTasks not implemented"]; + return nil; +} + +- (NSArray *)downloadTasks { + [NSException raise:NSGenericException format:@"getDownloadTasks not implemented"]; + return nil; +} +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageComponent.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageComponent.m new file mode 100644 index 0000000..01d7cc2 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageComponent.m @@ -0,0 +1,86 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageComponent.h" + +#import "Public/FIRStorage.h" + +#import +#import +#import +#import +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorage () +// Surface the internal initializer to create instances of FIRStorage. +- (instancetype)initWithApp:(FIRApp *)app + bucket:(NSString *)bucket + auth:(nullable id)auth; +@end + +@interface FIRStorageComponent () +/// Internal intializer. +- (instancetype)initWithApp:(FIRApp *)app; +@end + +@implementation FIRStorageComponent + +#pragma mark - Initialization + +- (instancetype)initWithApp:(FIRApp *)app { + self = [super init]; + if (self) { + _app = app; + } + return self; +} + +#pragma mark - Lifecycle + ++ (void)load { + [FIRComponentContainer registerAsComponentRegistrant:self]; +} + +#pragma mark - FIRComponentRegistrant + ++ (nonnull NSArray *)componentsToRegister { + FIRDependency *authDep = + [FIRDependency dependencyWithProtocol:@protocol(FIRAuthInterop) isRequired:NO]; + FIRComponentCreationBlock creationBlock = + ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) { + return [[FIRStorageComponent alloc] initWithApp:container.app]; + }; + FIRComponent *storageProvider = + [FIRComponent componentWithProtocol:@protocol(FIRStorageMultiBucketProvider) + instantiationTiming:FIRInstantiationTimingLazy + dependencies:@[ authDep ] + creationBlock:creationBlock]; + + return @[ storageProvider ]; +} + +#pragma mark - FIRStorageInstanceProvider Conformance + +- (FIRStorage *)storageForBucket:(NSString *)bucket { + // Create an instance of FIRStorage and return it. + id auth = FIR_COMPONENT(FIRAuthInterop, self.app.container); + return [[FIRStorage alloc] initWithApp:self.app bucket:bucket auth:auth]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageConstants.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageConstants.m new file mode 100644 index 0000000..3136807 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageConstants.m @@ -0,0 +1,86 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageConstants.h" + +#import "FIRStorageConstants_Private.h" + +NSString *const kGCSScheme = @"https"; +NSString *const kGCSHost = @"www.googleapis.com"; +NSString *const kGCSUploadPath = @"upload"; +NSString *const kGCSStorageVersionPath = @"storage/v1"; +NSString *const kGCSBucketPathFormat = @"b/%@"; +NSString *const kGCSObjectPathFormat = @"o/%@"; + +NSString *const kFIRStorageScheme = @"https"; +NSString *const kFIRStorageHost = @"firebasestorage.googleapis.com"; +NSString *const kFIRStorageVersionPath = @"v0"; +NSString *const kFIRStorageBucketPathFormat = @"b/%@"; +NSString *const kFIRStorageObjectPathFormat = @"o/%@"; +NSString *const kFIRStorageFullPathFormat = @"/v0/b/%@/o/%@"; + +NSString *const kFIRStorageAuthTokenFormat = @"Firebase %@"; +NSString *const kFIRStorageDefaultBucketFormat = @"gs://%@"; + +NSString *const kFIRStorageResponseErrorDomain = @"ResponseErrorDomain"; +NSString *const kFIRStorageResponseErrorCode = @"ResponseErrorCode"; +NSString *const kFIRStorageResponseBody = @"ResponseBody"; + +NSString *const FIRStorageErrorDomain = @"FIRStorageErrorDomain"; + +NSString *const kFIRStorageInvalidDataFormat = @"Invalid data returned from the server: %@"; +NSString *const kFIRStorageInvalidObserverStatus = + @"Invalid observer status requested, use one " + @"of: FIRStorageTaskStatusPause, Resume, Progress, " + @"Complete, or Failure"; + +/** + * String constants mapping GCS Object#resource mappings to metadata fields. + */ +NSString *const kFIRStorageMetadataBucket = @"bucket"; +NSString *const kFIRStorageMetadataCacheControl = @"cacheControl"; +NSString *const kFIRStorageMetadataContentDisposition = @"contentDisposition"; +NSString *const kFIRStorageMetadataContentEncoding = @"contentEncoding"; +NSString *const kFIRStorageMetadataContentLanguage = @"contentLanguage"; +NSString *const kFIRStorageMetadataContentType = @"contentType"; +NSString *const kFIRStorageMetadataCustomMetadata = @"metadata"; +NSString *const kFIRStorageMetadataSize = @"size"; +NSString *const kFIRStorageMetadataDownloadURLs = @"downloadURLs"; +NSString *const kFIRStorageMetadataGeneration = @"generation"; +NSString *const kFIRStorageMetadataMetageneration = @"metageneration"; +NSString *const kFIRStorageMetadataTimeCreated = @"timeCreated"; +NSString *const kFIRStorageMetadataUpdated = @"updated"; +NSString *const kFIRStorageMetadataName = @"name"; +NSString *const kFIRStorageMetadataDownloadTokens = @"downloadTokens"; +NSString *const kFIRStorageMetadataMd5Hash = @"md5Hash"; + +// TODO: add notification support +NSString *const kFIRStorageTaskStatusResumeNotification = + @"kFIRStorageTaskStatusResumeNotification"; +NSString *const kFIRStorageTaskStatusPauseNotification = @"kFIRStorageTaskStatusResumeNotification"; +NSString *const kFIRStorageTaskStatusProgressNotification = + @"kFIRStorageTaskStatusResumeNotification"; +NSString *const kFIRStorageTaskStatusCompleteNotification = + @"kFIRStorageTaskStatusResumeNotification"; +NSString *const kFIRStorageTaskStatusFailureNotification = + @"kFIRStorageTaskStatusResumeNotification"; + +NSString *const kFIRStorageBundleIdentifier = @"com.google.firebase.storage"; + +// The STR and STR_EXPAND macro allow a numeric version passed to he compiler driver +// with a -D to be treated as a string instead of an invalid floating point value. +#define STR(x) STR_EXPAND(x) +#define STR_EXPAND(x) #x +const unsigned char *const FIRStorageVersionString = + (const unsigned char *const)STR(FIRStorage_VERSION); diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDeleteTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDeleteTask.m new file mode 100644 index 0000000..5617e48 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDeleteTask.m @@ -0,0 +1,83 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageDeleteTask.h" + +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageDeleteTask { + @private + FIRStorageVoidError _completion; +} + +@synthesize fetcher = _fetcher; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (void)dealloc { + [_fetcher stopFetching]; +} + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidError)completion { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _completion = [completion copy]; + } + return self; +} + +- (void)enqueue { + __weak FIRStorageDeleteTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageDeleteTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + request.HTTPMethod = @"DELETE"; + request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime; + + FIRStorageVoidError callback = strongSelf->_completion; + strongSelf->_completion = nil; + + GTMSessionFetcher *fetcher = [strongSelf.fetcherService fetcherWithRequest:request]; + strongSelf->_fetcher = fetcher; + + fetcher.comment = @"DeleteTask"; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *_Nullable data, NSError *_Nullable error) { + if (!self.error) { + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + } + if (callback) { + callback(self.error); + } + self->_fetcherCompletion = nil; + }; +#pragma clang diangostic pop + + [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDownloadTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDownloadTask.m new file mode 100644 index 0000000..0752df7 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageDownloadTask.m @@ -0,0 +1,189 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageDownloadTask.h" + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageDownloadTask_Private.h" +#import "FIRStorageObservableTask_Private.h" +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageDownloadTask + +@synthesize progress = _progress; +@synthesize fetcher = _fetcher; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + file:(nullable NSURL *)fileURL { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _fileURL = [fileURL copy]; + _progress = [NSProgress progressWithTotalUnitCount:0]; + } + return self; +} + +- (void)dealloc { + [_fetcher stopFetching]; +} + +- (void)enqueue { + [self enqueueWithData:nil]; +} + +- (void)enqueueWithData:(nullable NSData *)resumeData { + __weak FIRStorageDownloadTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageDownloadTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + strongSelf.state = FIRStorageTaskStateQueueing; + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + request.HTTPMethod = @"GET"; + request.timeoutInterval = strongSelf.reference.storage.maxDownloadRetryTime; + NSURLComponents *components = + [NSURLComponents componentsWithURL:request.URL resolvingAgainstBaseURL:NO]; + [components setQuery:@"alt=media"]; + request.URL = components.URL; + + GTMSessionFetcher *fetcher; + if (resumeData) { + fetcher = [GTMSessionFetcher fetcherWithDownloadResumeData:resumeData]; + fetcher.comment = @"Resuming DownloadTask"; + } else { + fetcher = [strongSelf.fetcherService fetcherWithRequest:request]; + fetcher.comment = @"Starting DownloadTask"; + } + + [fetcher setResumeDataBlock:^(NSData *data) { + FIRStorageDownloadTask *strong = weakSelf; + if (strong && data) { + strong->_downloadData = data; + } + }]; + + fetcher.maxRetryInterval = strongSelf.reference.storage.maxDownloadRetryTime; + + if (strongSelf->_fileURL) { + // Handle file downloads + [fetcher setDestinationFileURL:strongSelf->_fileURL]; + [fetcher setDownloadProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten, + int64_t totalBytesExpectedToWrite) { + weakSelf.state = FIRStorageTaskStateProgress; + weakSelf.progress.completedUnitCount = totalBytesWritten; + weakSelf.progress.totalUnitCount = totalBytesExpectedToWrite; + FIRStorageTaskSnapshot *snapshot = weakSelf.snapshot; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:snapshot]; + weakSelf.state = FIRStorageTaskStateRunning; + }]; + } else { + // Handle data downloads + [fetcher setReceivedProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten) { + weakSelf.state = FIRStorageTaskStateProgress; + weakSelf.progress.completedUnitCount = totalBytesWritten; + int64_t totalLength = [[weakSelf.fetcher response] expectedContentLength]; + weakSelf.progress.totalUnitCount = totalLength; + FIRStorageTaskSnapshot *snapshot = weakSelf.snapshot; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:snapshot]; + weakSelf.state = FIRStorageTaskStateRunning; + }]; + } + + strongSelf->_fetcher = fetcher; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *data, NSError *error) { + // Fire last progress updates + [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:self.snapshot]; + + // Handle potential issues with download + if (error) { + self.state = FIRStorageTaskStateFailed; + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot]; + [self removeAllObservers]; + self->_fetcherCompletion = nil; + return; + } + + // Download completed successfully, fire completion callbacks + self.state = FIRStorageTaskStateSuccess; + + if (data) { + self->_downloadData = data; + } + + [self fireHandlersForStatus:FIRStorageTaskStatusSuccess snapshot:self.snapshot]; + [self removeAllObservers]; + self->_fetcherCompletion = nil; + }; +#pragma clang diagnostic pop + + strongSelf.state = FIRStorageTaskStateRunning; + [strongSelf.fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +} + +#pragma mark - Download Management + +- (void)cancel { + NSError *error = [FIRStorageErrors errorWithCode:FIRStorageErrorCodeCancelled]; + [self cancelWithError:error]; +} + +- (void)cancelWithError:(NSError *)error { + __weak FIRStorageDownloadTask *weakSelf = self; + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStateCancelled; + [weakSelf.fetcher stopFetching]; + weakSelf.error = error; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:weakSelf.snapshot]; + }]; +} + +- (void)pause { + __weak FIRStorageDownloadTask *weakSelf = self; + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStatePausing; + [weakSelf.fetcher stopFetching]; + // Give the resume callback a chance to run (if scheduled) + [weakSelf.fetcher waitForCompletionWithTimeout:0.001]; + weakSelf.state = FIRStorageTaskStatePaused; + FIRStorageTaskSnapshot *snapshot = weakSelf.snapshot; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusPause snapshot:snapshot]; + }]; +} + +- (void)resume { + __weak FIRStorageDownloadTask *weakSelf = self; + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStateResuming; + FIRStorageTaskSnapshot *snapshot = weakSelf.snapshot; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusResume snapshot:snapshot]; + weakSelf.state = FIRStorageTaskStateRunning; + [weakSelf enqueueWithData:weakSelf.downloadData]; + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageErrors.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageErrors.m new file mode 100644 index 0000000..651bfd1 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageErrors.m @@ -0,0 +1,190 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageErrors.h" + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageReference.h" +#import "FIRStorageReference_Private.h" + +@implementation FIRStorageErrors + ++ (NSError *)errorWithCode:(FIRStorageErrorCode)code { + return [FIRStorageErrors errorWithCode:code infoDictionary:nil]; +} + ++ (NSError *)errorWithCode:(FIRStorageErrorCode)code + infoDictionary:(nullable NSDictionary *)dictionary { + NSMutableDictionary *errorDictionary; + if (dictionary) { + errorDictionary = [dictionary mutableCopy]; + } else { + errorDictionary = [[NSMutableDictionary alloc] init]; + } + + NSString *errorMessage; + switch (code) { + case FIRStorageErrorCodeObjectNotFound: + errorMessage = + [NSString stringWithFormat:@"Object %@ does not exist.", errorDictionary[@"object"]]; + break; + + case FIRStorageErrorCodeBucketNotFound: + errorMessage = + [NSString stringWithFormat:@"Bucket %@ does not exist.", errorDictionary[@"bucket"]]; + break; + + case FIRStorageErrorCodeProjectNotFound: + errorMessage = + [NSString stringWithFormat:@"Project %@ does not exist.", errorDictionary[@"project"]]; + break; + + case FIRStorageErrorCodeQuotaExceeded: { + NSString *const kQuotaExceededFormat = + @"Quota for bucket %@ exceeded, please view quota on firebase.google.com."; + errorMessage = [NSString stringWithFormat:kQuotaExceededFormat, errorDictionary[@"bucket"]]; + break; + } + + case FIRStorageErrorCodeDownloadSizeExceeded: { + int64_t total = [errorDictionary[@"totalSize"] longLongValue]; + int64_t size = [errorDictionary[@"maxAllowedSize"] longLongValue]; + NSString *totalString = total ? @(total).stringValue : @"unknown"; + NSString *sizeString = total ? @(size).stringValue : @"unknown"; + NSString *const kSizeExceededErrorFormat = + @"Attempted to download object with size of %@ bytes, " + @"which exceeds the maximum size of %@ bytes. " + @"Consider raising the maximum download size, or using " + @"[FIRStorageReference writeToFile:]"; + errorMessage = [NSString stringWithFormat:kSizeExceededErrorFormat, totalString, sizeString]; + break; + } + + case FIRStorageErrorCodeUnauthenticated: + errorMessage = + @"User is not authenticated, please authenticate using Firebase " + @"Authentication and try again."; + break; + + case FIRStorageErrorCodeUnauthorized: { + NSString *bucket = errorDictionary[@"bucket"]; + NSString *object = errorDictionary[@"object"]; + NSString *const kUnauthorizedFormat = @"User does not have permission to access gs://%@/%@."; + errorMessage = [NSString stringWithFormat:kUnauthorizedFormat, bucket, object]; + break; + } + + case FIRStorageErrorCodeRetryLimitExceeded: + errorMessage = @"Max retry time for operation exceeded, please try again."; + break; + + case FIRStorageErrorCodeNonMatchingChecksum: { + // TODO: replace with actual checksum strings when we choose to implement. + NSString *const kChecksumFailedErrorFormat = + @"Uploaded/downloaded object %@ has checksum: %@ " + @"which does not match server checksum: %@. Please retry the upload/download."; + errorMessage = [NSString stringWithFormat:kChecksumFailedErrorFormat, @"object", + @"client checksum", @"server checksum"]; + break; + } + + case FIRStorageErrorCodeCancelled: + errorMessage = @"User cancelled the upload/download."; + break; + + case FIRStorageErrorCodeUnknown: + /* Fall through to default case for unknown errors */ + + default: + errorMessage = @"An unknown error occurred, please check the server response."; + break; + } + + errorDictionary[NSLocalizedDescriptionKey] = errorMessage; + + NSError *err = [NSError errorWithDomain:FIRStorageErrorDomain code:code userInfo:errorDictionary]; + return err; +} + ++ (nullable NSError *)errorWithServerError:(nullable NSError *)error + reference:(nullable FIRStorageReference *)reference { + if (error == nil) { + return nil; + } + + FIRStorageErrorCode errorCode; + switch (error.code) { + case 400: + errorCode = FIRStorageErrorCodeUnknown; + break; + + case 401: + errorCode = FIRStorageErrorCodeUnauthenticated; + break; + + case 402: + errorCode = FIRStorageErrorCodeQuotaExceeded; + break; + + case 403: + errorCode = FIRStorageErrorCodeUnauthorized; + break; + + case 404: + errorCode = FIRStorageErrorCodeObjectNotFound; + break; + + default: + errorCode = FIRStorageErrorCodeUnknown; + break; + } + + NSMutableDictionary *errorDictionary = + [[[NSDictionary alloc] initWithDictionary:error.userInfo] mutableCopy]; + errorDictionary[kFIRStorageResponseErrorDomain] = error.domain; + errorDictionary[kFIRStorageResponseErrorCode] = @(error.code); + + // Turn raw response into a string + NSData *responseData = errorDictionary[@"data"]; + if (responseData) { + NSString *errorString = + [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; + errorDictionary[kFIRStorageResponseBody] = errorString ?: @"No Response from Server."; + } + + errorDictionary[@"bucket"] = reference.path.bucket; + errorDictionary[@"object"] = reference.path.object; + + NSError *clientError = [FIRStorageErrors errorWithCode:errorCode infoDictionary:errorDictionary]; + return clientError; +} + ++ (NSError *)errorWithInvalidRequest:(NSData *)request { + NSString *requestString = [[NSString alloc] initWithData:request encoding:NSUTF8StringEncoding]; + NSString *invalidDataString = + [NSString stringWithFormat:kFIRStorageInvalidDataFormat, requestString]; + NSDictionary *dict; + if (invalidDataString.length > 0) { + dict = @{NSLocalizedFailureReasonErrorKey : invalidDataString}; + } + return [FIRStorageErrors errorWithCode:FIRStorageErrorCodeUnknown infoDictionary:dict]; +} + ++ (NSError *)errorWithCustomMessage:(NSString *)errorMessage { + return [NSError errorWithDomain:FIRStorageErrorDomain + code:FIRStorageErrorCodeUnknown + userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetDownloadURLTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetDownloadURLTask.m new file mode 100644 index 0000000..f5f7a7a --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetDownloadURLTask.m @@ -0,0 +1,126 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageGetDownloadURLTask.h" + +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageGetDownloadURLTask { + @private + FIRStorageVoidURLError _completion; +} + +@synthesize fetcher = _fetcher; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidURLError)completion { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _completion = [completion copy]; + } + return self; +} + +- (void)dealloc { + [_fetcher stopFetching]; +} + ++ (NSURL *)downloadURLFromMetadataDictionary:(NSDictionary *)dictionary { + NSString *downloadTokens = dictionary[kFIRStorageMetadataDownloadTokens]; + + if (downloadTokens && downloadTokens.length > 0) { + NSArray *downloadTokenArray = [downloadTokens componentsSeparatedByString:@","]; + NSString *bucket = dictionary[kFIRStorageMetadataBucket]; + NSString *path = dictionary[kFIRStorageMetadataName]; + NSString *fullPath = [NSString stringWithFormat:kFIRStorageFullPathFormat, bucket, + [FIRStorageUtils GCSEscapedString:path]]; + + NSURLComponents *components = [[NSURLComponents alloc] init]; + components.scheme = kFIRStorageScheme; + components.host = kFIRStorageHost; + components.percentEncodedPath = fullPath; + + // The backend can return an arbitrary number of download tokens, but we only expose the first + // token via the download URL. + NSURLQueryItem *altItem = [[NSURLQueryItem alloc] initWithName:@"alt" value:@"media"]; + NSURLQueryItem *tokenItem = + [[NSURLQueryItem alloc] initWithName:@"token" value:downloadTokenArray[0]]; + components.queryItems = @[ altItem, tokenItem ]; + + return [components URL]; + } + + return nil; +} + +- (void)enqueue { + __weak FIRStorageGetDownloadURLTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageGetDownloadURLTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + request.HTTPMethod = @"GET"; + request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime; + + FIRStorageVoidURLError callback = strongSelf->_completion; + strongSelf->_completion = nil; + + GTMSessionFetcher *fetcher = [strongSelf.fetcherService fetcherWithRequest:request]; + strongSelf->_fetcher = fetcher; + fetcher.comment = @"GetDownloadURLTask"; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *data, NSError *error) { + NSURL *downloadURL; + if (error) { + if (!self.error) { + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + } + } else { + NSDictionary *responseDictionary = [NSDictionary frs_dictionaryFromJSONData:data]; + if (responseDictionary != nil) { + downloadURL = + [FIRStorageGetDownloadURLTask downloadURLFromMetadataDictionary:responseDictionary]; + if (!downloadURL) { + self.error = + [FIRStorageErrors errorWithCustomMessage:@"Failed to retrieve a download URL."]; + } + } else { + self.error = [FIRStorageErrors errorWithInvalidRequest:data]; + } + } + + if (callback) { + callback(downloadURL, self.error); + } + + self->_fetcherCompletion = nil; + }; +#pragma clang diagnostic pop + [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +}; + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetMetadataTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetMetadataTask.m new file mode 100644 index 0000000..efa637b --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageGetMetadataTask.m @@ -0,0 +1,99 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageGetMetadataTask.h" + +#import "FIRStorageConstants.h" +#import "FIRStorageMetadata_Private.h" +#import "FIRStorageTask_Private.h" +#import "FIRStorageUtils.h" + +#import "FirebaseStorage.h" + +@implementation FIRStorageGetMetadataTask { + @private + FIRStorageVoidMetadataError _completion; +} + +@synthesize fetcher = _fetcher; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidMetadataError)completion { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _completion = [completion copy]; + } + return self; +} + +- (void)dealloc { + [_fetcher stopFetching]; +} + +- (void)enqueue { + __weak FIRStorageGetMetadataTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageGetMetadataTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + request.HTTPMethod = @"GET"; + request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime; + + FIRStorageVoidMetadataError callback = strongSelf->_completion; + strongSelf->_completion = nil; + + GTMSessionFetcher *fetcher = [strongSelf.fetcherService fetcherWithRequest:request]; + strongSelf->_fetcher = fetcher; + fetcher.comment = @"GetMetadataTask"; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *data, NSError *error) { + FIRStorageMetadata *metadata; + if (error) { + if (!self.error) { + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + } + } else { + NSDictionary *responseDictionary = [NSDictionary frs_dictionaryFromJSONData:data]; + if (responseDictionary != nil) { + metadata = [[FIRStorageMetadata alloc] initWithDictionary:responseDictionary]; + [metadata setType:FIRStorageMetadataTypeFile]; + } else { + self.error = [FIRStorageErrors errorWithInvalidRequest:data]; + } + } + + if (callback) { + callback(metadata, self.error); + } + self->_fetcherCompletion = nil; + }; +#pragma clang diagnostic pop + + [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageMetadata.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageMetadata.m new file mode 100644 index 0000000..764907c --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageMetadata.m @@ -0,0 +1,224 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageMetadata.h" + +#import "FIRStorageConstants.h" +#import "FIRStorageConstants_Private.h" +#import "FIRStorageMetadata_Private.h" +#import "FIRStorageUtils.h" + +// TODO: consider rewriting this using GTLR (GTLRStorageObjects.h) +@implementation FIRStorageMetadata + +#pragma mark - Initializers + +- (instancetype)init { + return [self initWithDictionary:[NSDictionary dictionary]]; +} + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary { + self = [super init]; + if (self) { + _initialMetadata = [dictionary copy]; + + _bucket = dictionary[kFIRStorageMetadataBucket]; + _cacheControl = dictionary[kFIRStorageMetadataCacheControl]; + _contentDisposition = dictionary[kFIRStorageMetadataContentDisposition]; + _contentEncoding = dictionary[kFIRStorageMetadataContentEncoding]; + _contentLanguage = dictionary[kFIRStorageMetadataContentLanguage]; + _contentType = dictionary[kFIRStorageMetadataContentType]; + _customMetadata = dictionary[kFIRStorageMetadataCustomMetadata]; + _size = [dictionary[kFIRStorageMetadataSize] longLongValue]; + _generation = [dictionary[kFIRStorageMetadataGeneration] longLongValue]; + _metageneration = [dictionary[kFIRStorageMetadataMetageneration] longLongValue]; + _timeCreated = [self dateFromRFC3339String:dictionary[kFIRStorageMetadataTimeCreated]]; + _updated = [self dateFromRFC3339String:dictionary[kFIRStorageMetadataUpdated]]; + _md5Hash = dictionary[kFIRStorageMetadataMd5Hash]; + // GCS "name" is our path, our "name" is just the last path component of the path + _path = dictionary[kFIRStorageMetadataName]; + _name = [_path lastPathComponent]; + } + return self; +} + +#pragma mark - NSObject overrides + +- (instancetype)copyWithZone:(NSZone *)zone { + FIRStorageMetadata *clone = + [[[self class] allocWithZone:zone] initWithDictionary:[self dictionaryRepresentation]]; + clone.initialMetadata = [self.initialMetadata copy]; + return clone; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[FIRStorageMetadata class]]) { + return NO; + } + + BOOL isEqualObject = [self isEqualToFIRStorageMetadata:(FIRStorageMetadata *)object]; + return isEqualObject; +} + +- (BOOL)isEqualToFIRStorageMetadata:(FIRStorageMetadata *)metadata { + return [[self dictionaryRepresentation] isEqualToDictionary:[metadata dictionaryRepresentation]]; +} + +- (NSUInteger)hash { + NSUInteger hash = [[self dictionaryRepresentation] hash]; + return hash; +} + +- (NSString *)description { + NSDictionary *metadataDictionary = [self dictionaryRepresentation]; + return [NSString stringWithFormat:@"%@ %p: %@", [self class], self, metadataDictionary]; +} + +#pragma mark - Public methods + +- (NSDictionary *)dictionaryRepresentation { + NSMutableDictionary *metadataDictionary = [[NSMutableDictionary alloc] initWithCapacity:13]; + + if (_bucket) { + metadataDictionary[kFIRStorageMetadataBucket] = _bucket; + } + + if (_cacheControl) { + metadataDictionary[kFIRStorageMetadataCacheControl] = _cacheControl; + } + + if (_contentDisposition) { + metadataDictionary[kFIRStorageMetadataContentDisposition] = _contentDisposition; + } + + if (_contentEncoding) { + metadataDictionary[kFIRStorageMetadataContentEncoding] = _contentEncoding; + } + + if (_contentLanguage) { + metadataDictionary[kFIRStorageMetadataContentLanguage] = _contentLanguage; + } + + if (_contentType) { + metadataDictionary[kFIRStorageMetadataContentType] = _contentType; + } + + if (_md5Hash) { + metadataDictionary[kFIRStorageMetadataMd5Hash] = _md5Hash; + } + + if (_customMetadata) { + metadataDictionary[kFIRStorageMetadataCustomMetadata] = _customMetadata; + } + + if (_generation) { + NSString *generationString = [NSString stringWithFormat:@"%lld", _generation]; + metadataDictionary[kFIRStorageMetadataGeneration] = generationString; + } + + if (_metageneration) { + NSString *metagenerationString = [NSString stringWithFormat:@"%lld", _metageneration]; + metadataDictionary[kFIRStorageMetadataMetageneration] = metagenerationString; + } + + if (_timeCreated) { + metadataDictionary[kFIRStorageMetadataTimeCreated] = [self RFC3339StringFromDate:_timeCreated]; + } + + if (_updated) { + metadataDictionary[kFIRStorageMetadataUpdated] = [self RFC3339StringFromDate:_updated]; + } + + if (_path) { + metadataDictionary[kFIRStorageMetadataName] = _path; + } + + if (_size) { + metadataDictionary[kFIRStorageMetadataSize] = [NSNumber numberWithLongLong:_size]; + } + + return [metadataDictionary copy]; +} + +- (BOOL)isFile { + return _type == FIRStorageMetadataTypeFile; +} + +- (BOOL)isFolder { + return _type == FIRStorageMetadataTypeFolder; +} + +#pragma mark - Private methods + ++ (void)removeMatchingMetadata:(NSMutableDictionary *)metadata + oldMetadata:(NSDictionary *)oldMetadata { + for (NSString *metadataKey in [oldMetadata allKeys]) { + id oldValue = [oldMetadata objectForKey:metadataKey]; + id newValue = [metadata objectForKey:metadataKey]; + + if (oldValue && !newValue) { + [metadata setObject:[NSNull null] forKey:metadataKey]; + } else if ([oldValue isKindOfClass:[NSString class]] && + [newValue isKindOfClass:[NSString class]]) { + if ([oldValue isEqualToString:newValue]) { + [metadata removeObjectForKey:metadataKey]; + } + } else if ([oldValue isKindOfClass:[NSDictionary class]] && + [newValue isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *nestedMetadata = [newValue mutableCopy]; + [self removeMatchingMetadata:nestedMetadata oldMetadata:oldValue]; + [metadata setObject:[nestedMetadata copy] forKey:metadataKey]; + } + } +} + +- (NSDictionary *)updatedMetadata { + NSMutableDictionary *metadataUpdate = [[self dictionaryRepresentation] mutableCopy]; + [FIRStorageMetadata removeMatchingMetadata:metadataUpdate oldMetadata:_initialMetadata]; + return [metadataUpdate copy]; +} + +#pragma mark - RFC 3339 conversions + +static NSDateFormatter *sRFC3339DateFormatter; + +static void setupDateFormatterOnce(void) { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sRFC3339DateFormatter = [[NSDateFormatter alloc] init]; + NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; + + [sRFC3339DateFormatter setLocale:enUSPOSIXLocale]; + [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZZZ"]; + [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; + }); +} + +- (nullable NSDate *)dateFromRFC3339String:(NSString *)dateString { + setupDateFormatterOnce(); + NSDate *rfc3339Date = [sRFC3339DateFormatter dateFromString:dateString]; + return rfc3339Date; +} + +- (nullable NSString *)RFC3339StringFromDate:(NSDate *)date { + setupDateFormatterOnce(); + NSString *rfc3339String = [sRFC3339DateFormatter stringFromDate:date]; + return rfc3339String; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageObservableTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageObservableTask.m new file mode 100644 index 0000000..2f35e53 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageObservableTask.m @@ -0,0 +1,215 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageObservableTask.h" +#import "FIRStorageObservableTask_Private.h" +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageObservableTask { + @private + // Handlers for pause, resume, progress, success, and failure callbacks + NSMutableDictionary *_resumeHandlers; + NSMutableDictionary *_pauseHandlers; + NSMutableDictionary *_progressHandlers; + NSMutableDictionary *_successHandlers; + NSMutableDictionary *_failureHandlers; + // Reverse map of fetcher handles to status types + NSMutableDictionary *_handleToStatusMap; +} + +@synthesize state = _state; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _pauseHandlers = [[NSMutableDictionary alloc] init]; + _resumeHandlers = [[NSMutableDictionary alloc] init]; + _progressHandlers = [[NSMutableDictionary alloc] init]; + _successHandlers = [[NSMutableDictionary alloc] init]; + _failureHandlers = [[NSMutableDictionary alloc] init]; + _handleToStatusMap = [[NSMutableDictionary alloc] init]; + } + return self; +} + +#pragma mark - Observers + +- (FIRStorageHandle)observeStatus:(FIRStorageTaskStatus)status + handler:(FIRStorageVoidSnapshot)handler { + FIRStorageVoidSnapshot callback = handler; + + // Note: self.snapshot is synchronized + FIRStorageTaskSnapshot *snapshot = self.snapshot; + // TODO: use an increasing counter instead of a random UUID + NSString *UUIDString = [[NSUUID UUID] UUIDString]; + switch (status) { + case FIRStorageTaskStatusPause: + @synchronized(self) { + [_pauseHandlers setValue:callback forKey:UUIDString]; + } // @synchronized(self) + if (_state == FIRStorageTaskStatePausing || _state == FIRStorageTaskStatePaused) { + [self fireHandlers:_pauseHandlers snapshot:snapshot]; + } + break; + + case FIRStorageTaskStatusResume: + @synchronized(self) { + [_resumeHandlers setValue:callback forKey:UUIDString]; + } // @synchronized(self) + if (_state == FIRStorageTaskStateResuming || _state == FIRStorageTaskStateRunning) { + [self fireHandlers:_resumeHandlers snapshot:snapshot]; + } + break; + + case FIRStorageTaskStatusProgress: + @synchronized(self) { + [_progressHandlers setValue:callback forKey:UUIDString]; + } // @synchronized(self) + if (_state == FIRStorageTaskStateRunning || _state == FIRStorageTaskStateProgress) { + [self fireHandlers:_progressHandlers snapshot:snapshot]; + } + break; + + case FIRStorageTaskStatusSuccess: + @synchronized(self) { + [_successHandlers setValue:callback forKey:UUIDString]; + } // @synchronized(self) + if (_state == FIRStorageTaskStateSuccess) { + [self fireHandlers:_successHandlers snapshot:snapshot]; + } + break; + + case FIRStorageTaskStatusFailure: + @synchronized(self) { + [_failureHandlers setValue:callback forKey:UUIDString]; + } // @synchronized(self) + if (_state == FIRStorageTaskStateFailing || _state == FIRStorageTaskStateFailed) { + [self fireHandlers:_failureHandlers snapshot:snapshot]; + } + break; + + case FIRStorageTaskStatusUnknown: + // Fall through to exception case if an unknown status is passed + + default: + [NSException raise:NSInternalInconsistencyException + format:kFIRStorageInvalidObserverStatus, nil]; + break; + } + + @synchronized(self) { + _handleToStatusMap[UUIDString] = @(status); + } // @synchronized(self) + + return UUIDString; +} + +- (void)removeObserverWithHandle:(FIRStorageHandle)handle { + FIRStorageTaskStatus status = [_handleToStatusMap[handle] intValue]; + NSMutableDictionary *observerDictionary = + [self handlerDictionaryForStatus:status]; + + @synchronized(self) { + [observerDictionary removeObjectForKey:handle]; + [_handleToStatusMap removeObjectForKey:handle]; + } // @synchronized(self) +} + +- (void)removeAllObserversForStatus:(FIRStorageTaskStatus)status { + NSMutableDictionary *observerDictionary = + [self handlerDictionaryForStatus:status]; + [self removeHandlersFromStatusMapForDictionary:observerDictionary]; + + @synchronized(self) { + [observerDictionary removeAllObjects]; + } // @synchronized(self) +} + +- (void)removeAllObservers { + @synchronized(self) { + [_pauseHandlers removeAllObjects]; + [_resumeHandlers removeAllObjects]; + [_progressHandlers removeAllObjects]; + [_successHandlers removeAllObjects]; + [_failureHandlers removeAllObjects]; + [_handleToStatusMap removeAllObjects]; + } // @synchronized(self) +} + +- (NSMutableDictionary *)handlerDictionaryForStatus: + (FIRStorageTaskStatus)status { + switch (status) { + case FIRStorageTaskStatusPause: + return _pauseHandlers; + + case FIRStorageTaskStatusResume: + return _resumeHandlers; + + case FIRStorageTaskStatusProgress: + return _progressHandlers; + + case FIRStorageTaskStatusSuccess: + return _successHandlers; + + case FIRStorageTaskStatusFailure: + return _failureHandlers; + + case FIRStorageTaskStatusUnknown: + return [NSMutableDictionary dictionary]; + + default: + [NSException raise:NSInternalInconsistencyException + format:kFIRStorageInvalidObserverStatus, nil]; + return nil; + } +} + +- (void)removeHandlersFromStatusMapForDictionary: + (NSMutableDictionary *)dict { + @synchronized(self) { + [_handleToStatusMap removeObjectsForKeys:dict.allKeys]; + } // @synchronized(self) +} + +- (void)fireHandlersForStatus:(FIRStorageTaskStatus)status + snapshot:(FIRStorageTaskSnapshot *)snapshot { + NSMutableDictionary *observerDictionary = + [self handlerDictionaryForStatus:status]; + [self fireHandlers:observerDictionary snapshot:snapshot]; +} + +- (void)fireHandlers:(NSMutableDictionary *)handlers + snapshot:(FIRStorageTaskSnapshot *)snapshot { + dispatch_queue_t callbackQueue = self.fetcherService.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + // TODO: iterate over this list in a consistent order + NSMutableDictionary *handlersCopy; + @synchronized(self) { + handlersCopy = [handlers copy]; + } // @synchronized(self) + [handlersCopy + enumerateKeysAndObjectsUsingBlock:^( + NSString *_Nonnull key, FIRStorageVoidSnapshot _Nonnull handler, BOOL *_Nonnull stop) { + dispatch_async(callbackQueue, ^{ + handler(snapshot); + }); + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStoragePath.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStoragePath.m new file mode 100644 index 0000000..aa7f130 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStoragePath.m @@ -0,0 +1,200 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStoragePath.h" + +#import "FIRStorageConstants_Private.h" + +@implementation FIRStoragePath + +#pragma mark - Class methods + ++ (nullable FIRStoragePath *)pathFromString:(NSString *)string { + if ([string hasPrefix:@"gs://"]) { + // "gs://bucket/path/to/object" + return [FIRStoragePath pathFromGSURI:string]; + } else if ([string hasPrefix:@"http://"] || [string hasPrefix:@"https://"]) { + // "http[s]://firebasestorage.googleapis.com/bucket/path/to/object?signed_url_params" + return [FIRStoragePath pathFromHTTPURL:string]; + } else { + // Invalid scheme, raise an exception! + [NSException raise:NSInternalInconsistencyException + format:@"URL scheme must be one of gs://, http://, or https:// "]; + return nil; + } +} + ++ (nullable FIRStoragePath *)pathFromGSURI:(NSString *)aURIString { + NSString *bucketName; + NSString *objectName; + NSScanner *scanner = [NSScanner scannerWithString:aURIString]; + BOOL isGSURI = [scanner scanString:@"gs://" intoString:NULL]; + BOOL hasBucket = [scanner scanUpToString:@"/" intoString:&bucketName]; + [scanner scanString:@"/" intoString:NULL]; + [scanner scanUpToString:@"\n" intoString:&objectName]; + + if (!isGSURI || !hasBucket) { + [NSException raise:NSInternalInconsistencyException + format:@"URI must be in the form of gs:///"]; + return nil; + } + + return [[self alloc] initWithBucket:bucketName object:objectName]; +} + ++ (nullable FIRStoragePath *)pathFromHTTPURL:(NSString *)aURLString { + NSString *bucketName; + NSString *objectName; + NSURL *httpsURL = [NSURL URLWithString:aURLString]; + NSArray *pathComponents = httpsURL.pathComponents; // [/, v0, b, , o, ] + + if ([httpsURL.host isEqual:kFIRStorageHost]) { + // Have a bucket name + if ([pathComponents count] > 3) { + bucketName = pathComponents[3]; + } + + // Have an object name + if ([pathComponents count] > 5) { + NSRange objectRange = NSMakeRange(5, [pathComponents count] - 5); + objectName = [[pathComponents subarrayWithRange:objectRange] componentsJoinedByString:@"/"]; + } + } + + if (bucketName.length == 0) { + [NSException raise:NSInternalInconsistencyException + format: + @"URL must be in the form of " + @"http[s]://firebasestorage.googleapis.com/v0/b//o/[?token=signed_url_params]"]; + return nil; + } + + if (objectName.length == 0) { + objectName = nil; + } + + return [[self alloc] initWithBucket:bucketName object:objectName]; +} + +#pragma mark - Initializers + +- (instancetype)initWithBucket:(NSString *)bucket object:(nullable NSString *)object { + self = [super init]; + if (self) { + _bucket = [bucket copy]; + _object = [self standardizedPathForString:[object copy]]; + } + return self; +} + +#pragma mark - NSObject overrides + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithBucket:_bucket object:_object]; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[FIRStoragePath class]]) { + return NO; + } + + BOOL isObjectEqual = [self isEqualToFIRStoragePath:(FIRStoragePath *)object]; + return isObjectEqual; +} + +- (BOOL)isEqualToFIRStoragePath:(FIRStoragePath *)path { + BOOL isBucketEqual = _bucket == nil && path->_bucket == nil; + BOOL isObjectEqual = _object == nil && path->_object == nil; + + if (_bucket && path->_bucket) { + isBucketEqual = [_bucket isEqual:path->_bucket]; + } + + if (_object && path.object) { + isObjectEqual = [_object isEqual:path->_object]; + } + + BOOL isEqual = isBucketEqual && isObjectEqual; + return isEqual; +} + +- (NSUInteger)hash { + // "...because in those days, you could XOR anything with anything and get something useful..." + // https://www.usenix.org/system/files/1309_14-17_mickens.pdf + NSUInteger hash = [_bucket hash] ^ [_object hash]; + return hash; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p: %@", [self class], self, [self stringValue]]; +} + +- (NSString *)stringValue { + return [NSString stringWithFormat:@"gs://%@/%@", _bucket, _object ?: @""]; +} + +#pragma mark - Public methods + +- (FIRStoragePath *)child:(NSString *)path { + if (path.length == 0) { + return [self copy]; // Return a copy of the same path, nothing happened + } + + NSString *childObject; + if (_object == nil) { + childObject = path; + } else { + childObject = [_object stringByAppendingPathComponent:path]; + } + + FIRStoragePath *childPath = [[FIRStoragePath alloc] initWithBucket:_bucket object:childObject]; + return childPath; +} + +- (nullable FIRStoragePath *)parent { + if (_object.length == 0) { + return nil; + } + + NSString *parentObject = [_object stringByDeletingLastPathComponent]; + FIRStoragePath *parentPath = [[FIRStoragePath alloc] initWithBucket:_bucket object:parentObject]; + return parentPath; +} + +- (FIRStoragePath *)root { + FIRStoragePath *rootPath = [[FIRStoragePath alloc] initWithBucket:_bucket object:nil]; + return rootPath; +} + +#pragma mark - Private methods + +// Removes leading and trailing slashes, and compresses multiple slashes +// to create a canonical representation. +// Example: /foo//bar///baz//// -> foo/bar/baz +- (NSString *)standardizedPathForString:(NSString *)string { + NSMutableArray *components = [[string componentsSeparatedByString:@"/"] mutableCopy]; + NSIndexSet *removedPaths = + [components indexesOfObjectsPassingTest:^BOOL(NSString *string, NSUInteger idx, BOOL *stop) { + return (string.length == 0); + }]; + [components removeObjectsAtIndexes:removedPaths]; + return [components componentsJoinedByString:@"/"]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageReference.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageReference.m new file mode 100644 index 0000000..99f0099 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageReference.m @@ -0,0 +1,367 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageReference.h" + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageDeleteTask.h" +#import "FIRStorageDownloadTask_Private.h" +#import "FIRStorageGetDownloadURLTask.h" +#import "FIRStorageGetMetadataTask.h" +#import "FIRStorageMetadata_Private.h" +#import "FIRStorageReference_Private.h" +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageTaskSnapshot_Private.h" +#import "FIRStorageTask_Private.h" +#import "FIRStorageUpdateMetadataTask.h" +#import "FIRStorageUploadTask_Private.h" +#import "FIRStorageUtils.h" +#import "FIRStorage_Private.h" + +#import +#import + +#import +#import "GTMSessionFetcherService.h" + +@implementation FIRStorageReference + +- (instancetype)init { + FIRStorage *storage = [FIRStorage storage]; + NSString *storageBucket = storage.app.options.storageBucket; + FIRStoragePath *path = [[FIRStoragePath alloc] initWithBucket:storageBucket object:nil]; + FIRStorageReference *reference = [self initWithStorage:storage path:path]; + return reference; +} + +- (instancetype)initWithStorage:(FIRStorage *)storage path:(FIRStoragePath *)path { + self = [super init]; + if (self) { + _storage = storage; + _path = path; + } + return self; +} + +#pragma mark - NSObject overrides + +- (instancetype)copyWithZone:(NSZone *)zone { + FIRStorageReference *copiedReference = + [[[self class] allocWithZone:zone] initWithStorage:_storage path:_path]; + return copiedReference; +} + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[FIRStorageReference class]]) { + return NO; + } + + BOOL isObjectEqual = [self isEqualToFIRStorageReference:(FIRStorageReference *)object]; + return isObjectEqual; +} + +- (BOOL)isEqualToFIRStorageReference:(FIRStorageReference *)reference { + BOOL isEqual = [_storage isEqual:reference.storage] && [_path isEqual:reference.path]; + return isEqual; +} + +- (NSUInteger)hash { + NSUInteger hash = [_storage hash] ^ [_path hash]; + return hash; +} + +- (NSString *)description { + return [self stringValue]; +} + +- (NSString *)stringValue { + NSString *value = [NSString stringWithFormat:@"gs://%@/%@", _path.bucket, _path.object ?: @""]; + return value; +} + +#pragma mark - Property Getters + +- (NSString *)bucket { + NSString *bucket = _path.bucket; + return bucket; +} + +- (NSString *)fullPath { + NSString *path = _path.object; + if (!path) { + path = @""; + } + return path; +} + +- (NSString *)name { + NSString *name = [_path.object lastPathComponent]; + if (!name) { + name = @""; + } + return name; +} + +#pragma mark - Path Operations + +- (FIRStorageReference *)root { + FIRStoragePath *rootPath = [_path root]; + FIRStorageReference *rootReference = + [[FIRStorageReference alloc] initWithStorage:_storage path:rootPath]; + return rootReference; +} + +- (nullable FIRStorageReference *)parent { + FIRStoragePath *parentPath = [_path parent]; + if (!parentPath) { + return nil; + } + + FIRStorageReference *parentReference = + [[FIRStorageReference alloc] initWithStorage:_storage path:parentPath]; + return parentReference; +} + +- (FIRStorageReference *)child:(NSString *)path { + FIRStoragePath *childPath = [_path child:path]; + FIRStorageReference *childReference = + [[FIRStorageReference alloc] initWithStorage:_storage path:childPath]; + return childReference; +} + +#pragma mark - Uploads + +- (FIRStorageUploadTask *)putData:(NSData *)uploadData { + return [self putData:uploadData metadata:nil completion:nil]; +} + +- (FIRStorageUploadTask *)putData:(NSData *)uploadData + metadata:(nullable FIRStorageMetadata *)metadata { + return [self putData:uploadData metadata:metadata completion:nil]; +} + +- (FIRStorageUploadTask *)putData:(NSData *)uploadData + metadata:(nullable FIRStorageMetadata *)metadata + completion:(nullable FIRStorageVoidMetadataError)completion { + if (!metadata) { + metadata = [[FIRStorageMetadata alloc] init]; + } + + metadata.path = _path.object; + metadata.name = [_path.object lastPathComponent]; + FIRStorageUploadTask *task = + [[FIRStorageUploadTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + data:uploadData + metadata:metadata]; + + if (completion) { + dispatch_queue_t callbackQueue = _storage.fetcherServiceForApp.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + [task observeStatus:FIRStorageTaskStatusSuccess + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(snapshot.metadata, nil); + }); + }]; + [task observeStatus:FIRStorageTaskStatusFailure + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(nil, snapshot.error); + }); + }]; + } + [task enqueue]; + return task; +} + +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL { + return [self putFile:fileURL metadata:nil completion:nil]; +} + +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL + metadata:(nullable FIRStorageMetadata *)metadata { + return [self putFile:fileURL metadata:metadata completion:nil]; +} + +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL + metadata:(nullable FIRStorageMetadata *)metadata + completion:(nullable FIRStorageVoidMetadataError)completion { + if (!metadata) { + metadata = [[FIRStorageMetadata alloc] init]; + } + + metadata.path = _path.object; + metadata.name = [_path.object lastPathComponent]; + FIRStorageUploadTask *task = + [[FIRStorageUploadTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + file:fileURL + metadata:metadata]; + + if (completion) { + dispatch_queue_t callbackQueue = _storage.fetcherServiceForApp.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + [task observeStatus:FIRStorageTaskStatusSuccess + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(snapshot.metadata, nil); + }); + }]; + [task observeStatus:FIRStorageTaskStatusFailure + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(nil, snapshot.error); + }); + }]; + } + [task enqueue]; + return task; +} + +#pragma mark - Downloads + +- (FIRStorageDownloadTask *)dataWithMaxSize:(int64_t)size + completion:(FIRStorageVoidDataError)completion { + FIRStorageDownloadTask *task = + [[FIRStorageDownloadTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + file:nil]; + + dispatch_queue_t callbackQueue = _storage.fetcherServiceForApp.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + [task observeStatus:FIRStorageTaskStatusSuccess + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + FIRStorageDownloadTask *task = snapshot.task; + dispatch_async(callbackQueue, ^{ + completion(task.downloadData, nil); + }); + }]; + [task observeStatus:FIRStorageTaskStatusFailure + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(nil, snapshot.error); + }); + }]; + [task + observeStatus:FIRStorageTaskStatusProgress + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + FIRStorageDownloadTask *task = snapshot.task; + if (task.progress.totalUnitCount > size || task.progress.completedUnitCount > size) { + NSDictionary *infoDictionary = + @{@"totalSize" : @(task.progress.totalUnitCount), + @"maxAllowedSize" : @(size)}; + NSError *error = + [FIRStorageErrors errorWithCode:FIRStorageErrorCodeDownloadSizeExceeded + infoDictionary:infoDictionary]; + [task cancelWithError:error]; + } + }]; + [task enqueue]; + return task; +} + +- (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL { + return [self writeToFile:fileURL completion:nil]; +} + +- (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL + completion:(FIRStorageVoidURLError)completion { + FIRStorageDownloadTask *task = + [[FIRStorageDownloadTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + file:fileURL]; + if (completion) { + dispatch_queue_t callbackQueue = _storage.fetcherServiceForApp.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + [task observeStatus:FIRStorageTaskStatusSuccess + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(fileURL, nil); + }); + }]; + [task observeStatus:FIRStorageTaskStatusFailure + handler:^(FIRStorageTaskSnapshot *_Nonnull snapshot) { + dispatch_async(callbackQueue, ^{ + completion(nil, snapshot.error); + }); + }]; + } + [task enqueue]; + return task; +} + +- (void)downloadURLWithCompletion:(FIRStorageVoidURLError)completion { + FIRStorageGetDownloadURLTask *task = + [[FIRStorageGetDownloadURLTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + completion:completion]; + [task enqueue]; +} + +#pragma mark - Metadata Operations + +- (void)metadataWithCompletion:(FIRStorageVoidMetadataError)completion { + FIRStorageGetMetadataTask *task = + [[FIRStorageGetMetadataTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + completion:completion]; + [task enqueue]; +} + +- (void)updateMetadata:(FIRStorageMetadata *)metadata + completion:(nullable FIRStorageVoidMetadataError)completion { + FIRStorageUpdateMetadataTask *task = + [[FIRStorageUpdateMetadataTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + metadata:metadata + completion:completion]; + [task enqueue]; +} + +#pragma mark - Delete + +- (void)deleteWithCompletion:(nullable FIRStorageVoidError)completion { + FIRStorageDeleteTask *task = + [[FIRStorageDeleteTask alloc] initWithReference:self + fetcherService:_storage.fetcherServiceForApp + dispatchQueue:_storage.dispatchQueue + completion:completion]; + [task enqueue]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTask.m new file mode 100644 index 0000000..c0848df --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTask.m @@ -0,0 +1,68 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageTask.h" + +#import "FIRStorage.h" +#import "FIRStorageReference.h" +#import "FIRStorageReference_Private.h" +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageTaskSnapshot_Private.h" +#import "FIRStorageTask_Private.h" +#import "FIRStorage_Private.h" + +#import "GTMSessionFetcherService.h" + +@implementation FIRStorageTask + +- (instancetype)init { + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." + reason:@"init unavailable, use designated initializer" + userInfo:nil]; +} + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue { + self = [super init]; + if (self) { + _reference = reference; + _baseRequest = [FIRStorageUtils defaultRequestForPath:reference.path]; + _fetcherService = service; + _fetcherService.maxRetryInterval = _reference.storage.maxOperationRetryTime; + _dispatchQueue = queue; + } + return self; +} + +- (FIRStorageTaskSnapshot *)snapshot { + @synchronized(self) { + NSProgress *progress = [NSProgress progressWithTotalUnitCount:self.progress.totalUnitCount]; + progress.completedUnitCount = self.progress.completedUnitCount; + FIRStorageTaskSnapshot *snapshot = + [[FIRStorageTaskSnapshot alloc] initWithTask:self + state:self.state + metadata:self.metadata + reference:self.reference + progress:progress + error:[self.error copy]]; + return snapshot; + } +} + +- (void)dispatchAsync:(void (^)(void))block { + dispatch_async(self.dispatchQueue, block); +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTaskSnapshot.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTaskSnapshot.m new file mode 100644 index 0000000..c964993 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTaskSnapshot.m @@ -0,0 +1,87 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageTaskSnapshot_Private.h" + +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageTaskSnapshot + +- (instancetype)initWithTask:(__kindof FIRStorageTask *)task + state:(FIRStorageTaskState)state + metadata:(nullable FIRStorageMetadata *)metadata + reference:(FIRStorageReference *)reference + progress:(nullable NSProgress *)progress + error:(nullable NSError *)error { + self = [super init]; + if (self) { + _task = task; + _metadata = metadata; + _reference = reference; + _progress = progress; + _error = error; + + switch (state) { + case FIRStorageTaskStateQueueing: + case FIRStorageTaskStateRunning: + case FIRStorageTaskStateResuming: + _status = FIRStorageTaskStatusResume; + break; + + case FIRStorageTaskStateProgress: + _status = FIRStorageTaskStatusProgress; + break; + + case FIRStorageTaskStatePaused: + case FIRStorageTaskStatePausing: + _status = FIRStorageTaskStatusPause; + break; + + case FIRStorageTaskStateSuccess: + case FIRStorageTaskStateCompleting: + _status = FIRStorageTaskStatusSuccess; + break; + + case FIRStorageTaskStateCancelled: + case FIRStorageTaskStateFailing: + case FIRStorageTaskStateFailed: + _status = FIRStorageTaskStatusFailure; + break; + + default: + _status = FIRStorageTaskStatusUnknown; + } + } + return self; +} + +- (NSString *)description { + switch (_status) { + case FIRStorageTaskStatusResume: + return @""; + case FIRStorageTaskStatusProgress: + return [NSString stringWithFormat:@"", _progress]; + case FIRStorageTaskStatusPause: + return @""; + case FIRStorageTaskStatusSuccess: + return @""; + case FIRStorageTaskStatusFailure: + return [NSString stringWithFormat:@"", _error]; + default: + return @""; + }; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTokenAuthorizer.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTokenAuthorizer.m new file mode 100644 index 0000000..dbeac9d --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageTokenAuthorizer.m @@ -0,0 +1,133 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageTokenAuthorizer.h" + +#import "FIRStorageConstants.h" +#import "FIRStorageConstants_Private.h" +#import "FIRStorageErrors.h" + +#import "FirebaseStorage.h" + +#import + +@implementation FIRStorageTokenAuthorizer { + @private + /// Google App ID to pass along with each request. + NSString *_googleAppID; + + /// Auth provider. + id _auth; +} + +@synthesize fetcherService = _fetcherService; + +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID + fetcherService:(GTMSessionFetcherService *)service + authProvider:(nullable id)auth { + self = [super init]; + if (self) { + _googleAppID = googleAppID; + _fetcherService = service; + _auth = auth; + } + return self; +} + +#pragma mark - GTMFetcherAuthorizationProtocol methods + +- (void)authorizeRequest:(NSMutableURLRequest *)request + delegate:(id)delegate + didFinishSelector:(SEL)sel { + // Set version header on each request + NSString *versionString = [NSString stringWithFormat:@"ios/%s", FIRStorageVersionString]; + [request setValue:versionString forHTTPHeaderField:@"x-firebase-storage-version"]; + + // Set GMP ID on each request + [request setValue:_googleAppID forHTTPHeaderField:@"x-firebase-gmpid"]; + + if (delegate && sel) { + id selfParam = self; + NSMethodSignature *sig = [delegate methodSignatureForSelector:sel]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; + [invocation setSelector:sel]; + [invocation setTarget:delegate]; + [invocation setArgument:&selfParam atIndex:2]; + [invocation setArgument:&request atIndex:3]; + + dispatch_queue_t callbackQueue = self.fetcherService.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + + [invocation retainArguments]; + if (_auth) { + [_auth getTokenForcingRefresh:NO + withCallback:^(NSString *_Nullable token, NSError *_Nullable error) { + if (error) { + NSMutableDictionary *errorDictionary = + [NSMutableDictionary dictionaryWithDictionary:error.userInfo]; + errorDictionary[kFIRStorageResponseErrorDomain] = error.domain; + errorDictionary[kFIRStorageResponseErrorCode] = @(error.code); + + NSError *tokenError = + [FIRStorageErrors errorWithCode:FIRStorageErrorCodeUnauthenticated + infoDictionary:errorDictionary]; + [invocation setArgument:&tokenError atIndex:4]; + } else if (token) { + NSString *firebaseToken = + [NSString stringWithFormat:kFIRStorageAuthTokenFormat, token]; + [request setValue:firebaseToken forHTTPHeaderField:@"Authorization"]; + } + dispatch_async(callbackQueue, ^{ + [invocation invoke]; + }); + }]; + } else { + dispatch_async(callbackQueue, ^{ + [invocation invoke]; + }); + } + } +} + +// Note that stopAuthorization, isAuthorizingRequest, and userEmail +// aren't relevant with the Firebase App/Auth implementation of tokens, +// and thus aren't implemented. Token refresh is handled transparently +// for us, and we don't allow the auth request to be stopped. +// Auth is also not required so the world doesn't stop. +- (void)stopAuthorization { + // Noop +} + +- (void)stopAuthorizationForRequest:(NSURLRequest *)request { + // Noop +} + +- (BOOL)isAuthorizingRequest:(NSURLRequest *)request { + return NO; +} + +- (BOOL)isAuthorizedRequest:(NSURLRequest *)request { + NSString *authHeader = request.allHTTPHeaderFields[@"Authorization"]; + BOOL isFirebaseToken = [authHeader hasPrefix:@"Firebase"]; + return isFirebaseToken; +} + +- (NSString *)userEmail { + // Noop + return nil; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUpdateMetadataTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUpdateMetadataTask.m new file mode 100644 index 0000000..70665b1 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUpdateMetadataTask.m @@ -0,0 +1,107 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageUpdateMetadataTask.h" + +#import "FIRStorageMetadata_Private.h" +#import "FIRStorageTask_Private.h" + +@implementation FIRStorageUpdateMetadataTask { + @private + FIRStorageVoidMetadataError _completion; + // Metadata used in the update request + FIRStorageMetadata *_updateMetadata; +} + +@synthesize fetcher = _fetcher; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + metadata:(FIRStorageMetadata *)metadata + completion:(FIRStorageVoidMetadataError)completion { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _updateMetadata = [metadata copy]; + _completion = [completion copy]; + } + return self; +} + +- (void)dealloc { + [_fetcher stopFetching]; +} + +- (void)enqueue { + __weak FIRStorageUpdateMetadataTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageUpdateMetadataTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + NSDictionary *updateDictionary = [strongSelf->_updateMetadata updatedMetadata]; + NSData *updateData = [NSData frs_dataFromJSONDictionary:updateDictionary]; + request.HTTPMethod = @"PATCH"; + request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime; + request.HTTPBody = updateData; + NSString *typeString = @"application/json; charset=UTF-8"; + [request setValue:typeString forHTTPHeaderField:@"Content-Type"]; + NSString *lengthString = [NSString stringWithFormat:@"%zu", (unsigned long)[updateData length]]; + [request setValue:lengthString forHTTPHeaderField:@"Content-Length"]; + + FIRStorageVoidMetadataError callback = strongSelf->_completion; + strongSelf->_completion = nil; + + GTMSessionFetcher *fetcher = [strongSelf.fetcherService fetcherWithRequest:request]; + strongSelf->_fetcher = fetcher; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *data, NSError *error) { + FIRStorageMetadata *metadata; + if (error) { + if (!self.error) { + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + } + } else { + NSDictionary *responseDictionary = [NSDictionary frs_dictionaryFromJSONData:data]; + if (responseDictionary) { + metadata = [[FIRStorageMetadata alloc] initWithDictionary:responseDictionary]; + [metadata setType:FIRStorageMetadataTypeFile]; + } else { + self.error = [FIRStorageErrors errorWithInvalidRequest:data]; + } + } + + if (callback) { + callback(metadata, self.error); + } + self->_fetcherCompletion = nil; + }; +#pragma clang diagnostic pop + + fetcher.comment = @"UpdateMetadataTask"; + + [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUploadTask.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUploadTask.m new file mode 100644 index 0000000..8c299e7 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUploadTask.m @@ -0,0 +1,223 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "FIRStorageUploadTask.h" + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageMetadata_Private.h" +#import "FIRStorageObservableTask_Private.h" +#import "FIRStorageTask_Private.h" +#import "FIRStorageUploadTask_Private.h" + +#import "GTMSessionUploadFetcher.h" + +@implementation FIRStorageUploadTask + +@synthesize progress = _progress; +@synthesize fetcherCompletion = _fetcherCompletion; + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + data:(NSData *)uploadData + metadata:(FIRStorageMetadata *)metadata { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _uploadMetadata = [metadata copy]; + _uploadData = [uploadData copy]; + _progress = [NSProgress progressWithTotalUnitCount:[_uploadData length]]; + + if (!_uploadMetadata.contentType) { + _uploadMetadata.contentType = @"application/octet-stream"; + } + } + return self; +} + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + file:(NSURL *)fileURL + metadata:(FIRStorageMetadata *)metadata { + self = [super initWithReference:reference fetcherService:service dispatchQueue:queue]; + if (self) { + _uploadMetadata = [metadata copy]; + _fileURL = [fileURL copy]; + _progress = [NSProgress progressWithTotalUnitCount:0]; + + NSString *mimeType = [FIRStorageUtils MIMETypeForExtension:[_fileURL pathExtension]]; + + if (!_uploadMetadata.contentType) { + _uploadMetadata.contentType = mimeType ?: @"application/octet-stream"; + } + } + return self; +} + +- (void)dealloc { + [_uploadFetcher stopFetching]; +} + +- (void)enqueue { + __weak FIRStorageUploadTask *weakSelf = self; + + [self dispatchAsync:^() { + FIRStorageUploadTask *strongSelf = weakSelf; + + if (!strongSelf) { + return; + } + + strongSelf.state = FIRStorageTaskStateQueueing; + + NSMutableURLRequest *request = [strongSelf.baseRequest mutableCopy]; + request.HTTPMethod = @"POST"; + request.timeoutInterval = strongSelf.reference.storage.maxUploadRetryTime; + NSData *bodyData = + [NSData frs_dataFromJSONDictionary:[strongSelf->_uploadMetadata dictionaryRepresentation]]; + request.HTTPBody = bodyData; + [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; + NSString *contentLengthString = + [NSString stringWithFormat:@"%zu", (unsigned long)[bodyData length]]; + [request setValue:contentLengthString forHTTPHeaderField:@"Content-Length"]; + + NSURLComponents *components = + [NSURLComponents componentsWithURL:request.URL resolvingAgainstBaseURL:NO]; + + if ([components.host isEqual:kGCSHost]) { + [components setPercentEncodedPath:[@"/upload" stringByAppendingString:components.path]]; + } + + NSDictionary *queryParams = @{@"uploadType" : @"resumable", @"name" : self.uploadMetadata.path}; + [components setPercentEncodedQuery:[FIRStorageUtils queryStringForDictionary:queryParams]]; + request.URL = components.URL; + + GTMSessionUploadFetcher *uploadFetcher = + [GTMSessionUploadFetcher uploadFetcherWithRequest:request + uploadMIMEType:strongSelf->_uploadMetadata.contentType + chunkSize:kGTMSessionUploadFetcherStandardChunkSize + fetcherService:self.fetcherService]; + + if (strongSelf->_uploadData) { + [uploadFetcher setUploadData:strongSelf->_uploadData]; + uploadFetcher.comment = @"Data UploadTask"; + } else if (strongSelf->_fileURL) { + [uploadFetcher setUploadFileURL:strongSelf->_fileURL]; + uploadFetcher.comment = @"File UploadTask"; + } + + uploadFetcher.maxRetryInterval = self.reference.storage.maxUploadRetryTime; + + [uploadFetcher setSendProgressBlock:^(int64_t bytesSent, int64_t totalBytesSent, + int64_t totalBytesExpectedToSend) { + weakSelf.state = FIRStorageTaskStateProgress; + weakSelf.progress.completedUnitCount = totalBytesSent; + weakSelf.progress.totalUnitCount = totalBytesExpectedToSend; + weakSelf.metadata = self->_uploadMetadata; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:weakSelf.snapshot]; + weakSelf.state = FIRStorageTaskStateRunning; + }]; + + strongSelf->_uploadFetcher = uploadFetcher; + + // Process fetches + strongSelf.state = FIRStorageTaskStateRunning; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" + strongSelf->_fetcherCompletion = ^(NSData *_Nullable data, NSError *_Nullable error) { + // Fire last progress updates + [self fireHandlersForStatus:FIRStorageTaskStatusProgress snapshot:self.snapshot]; + + // Handle potential issues with upload + if (error) { + self.state = FIRStorageTaskStateFailed; + self.error = [FIRStorageErrors errorWithServerError:error reference:self.reference]; + self.metadata = self->_uploadMetadata; + [self fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:self.snapshot]; + [self removeAllObservers]; + self->_fetcherCompletion = nil; + return; + } + + // Upload completed successfully, fire completion callbacks + self.state = FIRStorageTaskStateSuccess; + + NSDictionary *responseDictionary = [NSDictionary frs_dictionaryFromJSONData:data]; + if (responseDictionary) { + FIRStorageMetadata *metadata = + [[FIRStorageMetadata alloc] initWithDictionary:responseDictionary]; + [metadata setType:FIRStorageMetadataTypeFile]; + self.metadata = metadata; + } else { + self.error = [FIRStorageErrors errorWithInvalidRequest:data]; + } + + [self fireHandlersForStatus:FIRStorageTaskStatusSuccess snapshot:self.snapshot]; + [self removeAllObservers]; + self->_fetcherCompletion = nil; + }; +#pragma clang diagnostic pop + + [strongSelf->_uploadFetcher + beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) { + weakSelf.fetcherCompletion(data, error); + }]; + }]; +} + +#pragma mark - Upload Management + +- (void)cancel { + __weak FIRStorageUploadTask *weakSelf = self; + + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStateCancelled; + [weakSelf.uploadFetcher stopFetching]; + if (weakSelf.state != FIRStorageTaskStateSuccess) { + weakSelf.metadata = weakSelf.uploadMetadata; + } + weakSelf.error = [FIRStorageErrors errorWithCode:FIRStorageErrorCodeCancelled]; + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusFailure snapshot:weakSelf.snapshot]; + }]; +} + +- (void)pause { + __weak FIRStorageUploadTask *weakSelf = self; + + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStatePaused; + [weakSelf.uploadFetcher pauseFetching]; + if (weakSelf.state != FIRStorageTaskStateSuccess) { + weakSelf.metadata = weakSelf.uploadMetadata; + } + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusPause snapshot:weakSelf.snapshot]; + }]; +} + +- (void)resume { + __weak FIRStorageUploadTask *weakSelf = self; + + [self dispatchAsync:^() { + weakSelf.state = FIRStorageTaskStateResuming; + [weakSelf.uploadFetcher resumeFetching]; + if (weakSelf.state != FIRStorageTaskStateSuccess) { + weakSelf.metadata = weakSelf.uploadMetadata; + } + [weakSelf fireHandlersForStatus:FIRStorageTaskStatusResume snapshot:weakSelf.snapshot]; + weakSelf.state = FIRStorageTaskStateRunning; + }]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUtils.m b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUtils.m new file mode 100644 index 0000000..66869ec --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/FIRStorageUtils.m @@ -0,0 +1,127 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_OSX +#import +#endif + +#import "FIRStorageUtils.h" + +#import "FIRStorageConstants_Private.h" +#import "FIRStoragePath.h" + +#import "FirebaseStorage.h" + +#import "GTMSessionFetcher.h" + +// This is the list at https://cloud.google.com/storage/docs/json_api/ without &, ; and +. +NSString *const kGCSObjectAllowedCharacterSet = + @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*,=:@"; + +@implementation FIRStorageUtils + ++ (nullable NSString *)GCSEscapedString:(NSString *)string { + NSCharacterSet *allowedCharacters = + [NSCharacterSet characterSetWithCharactersInString:kGCSObjectAllowedCharacterSet]; + + return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; +} + ++ (nullable NSString *)MIMETypeForExtension:(NSString *)extension { + if (extension == nil) { + return nil; + } + + CFStringRef pathExtension = (__bridge_retained CFStringRef)extension; + CFStringRef type = + UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL); + NSString *mimeType = + (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType); + CFRelease(pathExtension); + if (type != NULL) { + CFRelease(type); + } + + return mimeType; +} + ++ (NSString *)queryStringForDictionary:(nullable NSDictionary *)dictionary { + if (!dictionary) { + return @""; + } + + __block NSMutableArray *queryItems = [[NSMutableArray alloc] initWithCapacity:[dictionary count]]; + [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull name, NSString *_Nonnull value, + BOOL *_Nonnull stop) { + NSString *item = + [FIRStorageUtils GCSEscapedString:[NSString stringWithFormat:@"%@=%@", name, value]]; + [queryItems addObject:item]; + }]; + return [queryItems componentsJoinedByString:@"&"]; +} + ++ (NSURLRequest *)defaultRequestForPath:(FIRStoragePath *)path { + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; + NSURLComponents *components = [[NSURLComponents alloc] init]; + [components setScheme:kFIRStorageScheme]; + [components setHost:kFIRStorageHost]; + NSString *encodedPath = [self encodedURLForPath:path]; + [components setPercentEncodedPath:encodedPath]; + [request setURL:components.URL]; + return request; +} + ++ (NSString *)encodedURLForPath:(FIRStoragePath *)path { + NSString *bucketName = [FIRStorageUtils GCSEscapedString:path.bucket]; + NSString *objectName = [FIRStorageUtils GCSEscapedString:path.object]; + NSString *bucketFormat = [NSString stringWithFormat:kFIRStorageBucketPathFormat, bucketName]; + NSString *urlPath = [@"/" stringByAppendingPathComponent:bucketFormat]; + if (objectName) { + NSString *objectFormat = [NSString stringWithFormat:kFIRStorageObjectPathFormat, objectName]; + urlPath = [urlPath stringByAppendingFormat:@"/%@", objectFormat]; + } else { + urlPath = [urlPath stringByAppendingString:@"/o"]; + } + return [@"/" stringByAppendingString:[kFIRStorageVersionPath stringByAppendingString:urlPath]]; +} + +@end + +@implementation NSDictionary (FIRStorageNSDictionaryJSONHelpers) + ++ (nullable instancetype)frs_dictionaryFromJSONData:(nullable NSData *)data { + if (!data) { + return nil; + } + return [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingMutableContainers + error:nil]; +} + +@end + +@implementation NSData (FIRStorageNSDataJSONHelpers) + ++ (nullable instancetype)frs_dataFromJSONDictionary:(nullable NSDictionary *)dictionary { + if (!dictionary) { + return nil; + } + return [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil]; +} + +@end diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageComponent.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageComponent.h new file mode 100644 index 0000000..ac3637b --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageComponent.h @@ -0,0 +1,45 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +@class FIRApp; +@class FIRStorage; + +NS_ASSUME_NONNULL_BEGIN + +/// This protocol is used in the interop registration process to register an instance provider for +/// individual FIRApps. +@protocol FIRStorageMultiBucketProvider + +/// Default method for creating a Storage instance. +- (FIRStorage *)storageForBucket:(NSString *)bucket; + +@end + +/// A concrete implementation for FIRStorageMultiBucketProvider to create Storage instances. +@interface FIRStorageComponent : NSObject + +/// The FIRApp that instances will be set up with. +@property(nonatomic, weak, readonly) FIRApp *app; + +/// Default method for creating a Storage instance. +- (FIRStorage *)storageForBucket:(NSString *)bucket; + +/// Unavailable, use `storageForApp:storageURL:` instead. +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageConstants_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageConstants_Private.h new file mode 100644 index 0000000..cf12337 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageConstants_Private.h @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRStorageMetadata; + +NS_ASSUME_NONNULL_BEGIN + +FOUNDATION_EXPORT NSString *const kGCSScheme; +FOUNDATION_EXPORT NSString *const kGCSHost; +FOUNDATION_EXPORT NSString *const kGCSUploadPath; +FOUNDATION_EXPORT NSString *const kGCSStorageVersionPath; +FOUNDATION_EXPORT NSString *const kGCSBucketPathFormat; +FOUNDATION_EXPORT NSString *const kGCSObjectPathFormat; + +FOUNDATION_EXPORT NSString *const kFIRStorageScheme; +FOUNDATION_EXPORT NSString *const kFIRStorageHost; +FOUNDATION_EXPORT NSString *const kFIRStorageVersionPath; +FOUNDATION_EXPORT NSString *const kFIRStorageBucketPathFormat; +FOUNDATION_EXPORT NSString *const kFIRStorageObjectPathFormat; +FOUNDATION_EXPORT NSString *const kFIRStorageFullPathFormat; + +FOUNDATION_EXPORT NSString *const kFIRStorageAuthTokenFormat; +FOUNDATION_EXPORT NSString *const kFIRStorageDefaultBucketFormat; + +FOUNDATION_EXPORT NSString *const kFIRStorageResponseErrorDomain; +FOUNDATION_EXPORT NSString *const kFIRStorageResponseErrorCode; +FOUNDATION_EXPORT NSString *const kFIRStorageResponseBody; + +FOUNDATION_EXPORT NSString *const kFIRStorageTaskStatusResumeNotification; +FOUNDATION_EXPORT NSString *const kFIRStorageTaskStatusPauseNotification; +FOUNDATION_EXPORT NSString *const kFIRStorageTaskStatusProgressNotification; +FOUNDATION_EXPORT NSString *const kFIRStorageTaskStatusCompleteNotification; +FOUNDATION_EXPORT NSString *const kFIRStorageTaskStatusFailureNotification; + +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataBucket; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataCacheControl; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataContentDisposition; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataContentEncoding; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataContentLanguage; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataContentType; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataCustomMetadata; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataSize; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataGeneration; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataMetageneration; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataTimeCreated; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataUpdated; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataName; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataDownloadTokens; +FOUNDATION_EXPORT NSString *const kFIRStorageMetadataMd5Hash; + +FOUNDATION_EXPORT NSString *const kFIRStorageInvalidDataFormat; +FOUNDATION_EXPORT NSString *const kFIRStorageInvalidObserverStatus; + +FOUNDATION_EXPORT NSString *const kFIRStorageBundleIdentifier; + +/** + * Enum representing the internal state of an upload or download task. + */ +typedef NS_ENUM(NSInteger, FIRStorageTaskState) { + /** + * Unknown task state + */ + FIRStorageTaskStateUnknown, + + /** + * Task is being queued is ready to run + */ + FIRStorageTaskStateQueueing, + + /** + * Task is resuming from a paused state + */ + FIRStorageTaskStateResuming, + + /** + * Task is currently running + */ + FIRStorageTaskStateRunning, + + /** + * Task reporting a progress event + */ + FIRStorageTaskStateProgress, + + /** + * Task is pausing + */ + FIRStorageTaskStatePausing, + + /** + * Task is completing successfully + */ + FIRStorageTaskStateCompleting, + + /** + * Task is failing unrecoverably + */ + FIRStorageTaskStateFailing, + + /** + * Task paused successfully + */ + FIRStorageTaskStatePaused, + + /** + * Task cancelled successfully + */ + FIRStorageTaskStateCancelled, + + /** + * Task completed successfully + */ + FIRStorageTaskStateSuccess, + + /** + * Task failed unrecoverably + */ + FIRStorageTaskStateFailed +}; + +/** + * Represents the various types of metadata: Files or Folders. + */ +typedef NS_ENUM(NSUInteger, FIRStorageMetadataType) { + FIRStorageMetadataTypeUnknown, + FIRStorageMetadataTypeFile, + FIRStorageMetadataTypeFolder, +}; + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDeleteTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDeleteTask.h new file mode 100644 index 0000000..5eeaa88 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDeleteTask.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageTask.h" + +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Task which provides the ability to delete an object in Firebase Storage. + */ +@interface FIRStorageDeleteTask : FIRStorageTask + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidError)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDownloadTask_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDownloadTask_Private.h new file mode 100644 index 0000000..8b5a0d8 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageDownloadTask_Private.h @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorageDownloadTask () + +/** + * Bytes which have been downloaded so far. + */ +@property(readonly, nonatomic) NSData *downloadData; + +/** + * The file on disk to write to. + */ +@property(copy, nonatomic) NSURL *fileURL; + +/** + * Initializes a download task with a base FIRStorageReference and GTMSessionFetcherService. + * @param reference The base FIRStorageReference which fetchers use for configuration. + * @param service The GTMSessionFetcherService which will create fetchers. + * @param queue The shared queue to use for all Storage operations. + * @param fileURL The system URL to download to. If nil, download in memory as bytes. + * @return Returns an instance of FIRStorageDownloadTask + */ +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + file:(nullable NSURL *)fileURL; + +/** + * Cancels the download task and passes an appropriate error to the developer. + * @param error NSError to propegate to the developer. + */ +- (void)cancelWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageErrors.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageErrors.h new file mode 100644 index 0000000..a76a6aa --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageErrors.h @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageConstants.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRStorageReference; + +/** + * Adds wrappers for common Firebase Storage errors (including creating errors from GCS errors). + * For more information on unwrapping GCS errors, see the GCS errors docs: + * https://cloud.google.com/storage/docs/json_api/v1/status-codes + * This is never publicly exposed to end developers (as they will simply see an NSError). + */ +@interface FIRStorageErrors : NSObject + +/** + * Creates a Firebase Storage error from a specific FIRStorageErrorCode. + */ ++ (NSError *)errorWithCode:(FIRStorageErrorCode)code; + +/** + * Creates a Firebase Storage error from a specific FIRStorageErrorCode while adding + * custom info from an optionally provided info dictionary. + */ ++ (NSError *)errorWithCode:(FIRStorageErrorCode)code + infoDictionary:(nullable NSDictionary *)dictionary; + +/** + * Creates a Firebase Storage error from a specific GCS error and FIRStorageReference. + * @param error Server error to wrap and return as a Firebase Storage error. + * @param reference FIRStorageReference which provides context about the request being made. + * @return Returns a Firebase Storage error, or nil if no error is provided. + */ ++ (nullable NSError *)errorWithServerError:(nullable NSError *)error + reference:(nullable FIRStorageReference *)reference; + +/** + * Creates a Firebase Storage error from an invalid request. + * + * @param request The NSData representation of the invalid user request. + * @return Returns the corresponding Firebase Storage error. + */ ++ (NSError *)errorWithInvalidRequest:(NSData *)request; + +/** + * Creates a Firebase Storage error with a custom error message. + * + * @param errorMessage A custom error message. + * @return Returns the corresponding Firebase Storage error. + */ ++ (NSError *)errorWithCustomMessage:(NSString *)errorMessage; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask.h new file mode 100644 index 0000000..0dc8179 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask.h @@ -0,0 +1,35 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageTask.h" + +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Task which provides the ability to get a download URL for an object in Firebase Storage. + */ +@interface FIRStorageGetDownloadURLTask : FIRStorageTask + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidURLError)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask_Private.h new file mode 100644 index 0000000..0da04a4 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetDownloadURLTask_Private.h @@ -0,0 +1,31 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageGetDownloadURLTask.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * Task which provides the ability to get a download URL for an object in Firebase Storage. + */ +@interface FIRStorageGetDownloadURLTask () + +/** Extracts a download URL from the StorageMetadata dictonary representation. */ ++ (nullable NSURL *)downloadURLFromMetadataDictionary:(NSDictionary *)dictionary; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetMetadataTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetMetadataTask.h new file mode 100644 index 0000000..e98d6d1 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageGetMetadataTask.h @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageTask.h" + +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Task which provides the ability to get metadata on an object in Firebase Storage. + */ +@interface FIRStorageGetMetadataTask : FIRStorageTask + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + completion:(FIRStorageVoidMetadataError)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageMetadata_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageMetadata_Private.h new file mode 100644 index 0000000..ad8cc94 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageMetadata_Private.h @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageMetadata.h" + +@class FIRStorageReference; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorageMetadata () + +@property(readwrite, nonatomic) NSString *name; + +@property(readwrite, nonatomic) NSString *path; + +@property(readwrite, nonatomic) FIRStorageReference *reference; + +/** + * The type of the object, either a "File" or a "Folder". + */ +@property(readwrite) FIRStorageMetadataType type; + +/** + * The original metadata representation received from the server or an empty dictionary + * if the metadata object was initialized by the user. + */ +@property(copy, nonatomic) NSDictionary *initialMetadata; + +/** + * Recursively removes entries in 'metadata' that are unmodified from 'oldMetadata'. + * Adds 'NSNull' for entries that only exist in oldMetadata. + */ ++ (void)removeMatchingMetadata:(NSMutableDictionary *)metadata + oldMetadata:(NSDictionary *)oldMetadata; + +/** + * Computes the updates between the state at initialization and the current state. + * Returns a dictionary with only the updated data. Removed keys are set to NSNull. + */ +- (NSDictionary *)updatedMetadata; + +/** + * Returns an RFC3339 formatted date from a string. + * @param dateString An NSString of the form: yyyy-MM-ddTHH:mm:ss.SSSZ. + * @return An NSDate populated from the string or nil if conversion isn't possible. + */ +- (nullable NSDate *)dateFromRFC3339String:(NSString *)dateString; + +/** + * Returns an RFC3339 formatted string from an NSDate object. + * @param date The NSDate object to be converted to a string. + * @return An NSString of the form: yyyy-MM-ddTHH:mm:ss.SSSZ or nil if conversion isn't possible. + */ +- (nullable NSString *)RFC3339StringFromDate:(NSDate *)date; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageObservableTask_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageObservableTask_Private.h new file mode 100644 index 0000000..404ec9e --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageObservableTask_Private.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +NS_ASSUME_NONNULL_BEGIN + +@class FIRStorageTaskSnapshot; + +@class GTMSessionFetcherService; + +@interface FIRStorageObservableTask () + +/** + * Creates a new FIRStorageTask initialized with a FIRStorageReference and GTMSessionFetcherService. + * @param reference A FIRStorageReference the task will be performed on. + * @param service A GTMSessionFetcherService which provides the fetchers and configuration for + * requests. + * @param queue The shared queue to use for all Storage operations. + * @return A new FIRStorageTask representing the current task. + */ +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue; + +/** + * Raise events for a given task status by passing along a snapshot of existing task state. + * @param status A FIRStorageTaskStatus to raise events for. + * @param snapshot A FIRStorageTaskSnapshot snapshot of task state to pass through the handler. + */ +- (void)fireHandlersForStatus:(FIRStorageTaskStatus)status + snapshot:(FIRStorageTaskSnapshot *)snapshot; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStoragePath.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStoragePath.h new file mode 100644 index 0000000..53ff7ef --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStoragePath.h @@ -0,0 +1,106 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * Represents a path in GCS, which can be represented as: gs://bucket/path/to/object + * or http[s]://firebasestorage.googleapis.com/v0/b/bucket/o/path/to/object?token=<12345> + * This class also includes helper methods to parse those URI/Ls, as well as to + * add and remove path segments. + */ +@interface FIRStoragePath : NSObject + +/** + * The GCS bucket in the path. + */ +@property(copy, nonatomic) NSString *bucket; + +/** + * The GCS object in the path. + */ +@property(copy, nonatomic, nullable) NSString *object; + +/** + * Parses a generic string (representing some URI or URL) and returns the appropriate path. + * @param string String which is parsed into a path. + * @return Returns an instance of FIRStoragePath or nil if one can't be created. + * @throws Throws an exception if the string is not a valid gs:// URI or http[s]:// URL. + */ ++ (nullable FIRStoragePath *)pathFromString:(NSString *)string; + +/** + * Parses a gs://bucket/path/to/object URI into a GCS path. + * @param aURIString gs:// URI which is parsed into a path. + * @return Returns an instance of FIRStoragePath or nil if one can't be created. + * @throws Throws an exception if the string is not a valid gs:// URI. + */ ++ (nullable FIRStoragePath *)pathFromGSURI:(NSString *)aURIString; + +- (instancetype)init NS_UNAVAILABLE; + +/** + * Constructs an FIRStoragePath object that represents the given bucket and object. + * @param bucket The name of the bucket. + * @param object The name of the object. + * @return An instance of FIRStoragePath representing the @a bucket and @a object. + */ +- (instancetype)initWithBucket:(NSString *)bucket + object:(nullable NSString *)object NS_DESIGNATED_INITIALIZER; + +/** + * Parses a http[s]://firebasestorage.googleapis.com/v0/b/bucket/o/path/to/object...?token=<12345> + * URL into a GCS path. + * @param aURLString http[s]:// URL which is parsed into a path. + * string which is parsed into a path. + * @return Returns an instance of FIRStoragePath or nil if one can't be created. + * @throws Throws an exception if the string is not a valid http[s]:// URL. + */ ++ (nullable FIRStoragePath *)pathFromHTTPURL:(NSString *)aURLString; + +/** + * Creates a new path based off of the current path and a string appended to it. + * Note that all slashes are compressed to a single slash, and leading and trailing slashes + * are removed. + * @param path String to append to the current path. + * @return Returns a new instance of FIRStoragePath with the new path appended. + */ +- (FIRStoragePath *)child:(NSString *)path; + +/** + * Creates a new path based off of the current path with the last path segment removed. + * @return Returns a new instance of FIRStoragePath pointing to the parent path, + * or nil if the current path points to the root. + */ +- (nullable FIRStoragePath *)parent; + +/** + * Creates a new path based off of the root of the bucket. + * @return Returns a new instance of FIRStoragePath pointing to the root of the bucket. + */ +- (FIRStoragePath *)root; + +/** + * Returns a GS URI representing the current path. + * @return Returns a gs://bucket/path/to/object URI representing the current path. + */ +- (NSString *)stringValue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageReference_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageReference_Private.h new file mode 100644 index 0000000..568fcb0 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageReference_Private.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageReference.h" + +#import "FIRStoragePath.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorageReference () + +@property(nonatomic, readwrite) FIRStorage *storage; + +/** + * The current path which points to an object in the Google Cloud Storage bucket. + */ +@property(strong, nonatomic) FIRStoragePath *path; + +- (instancetype)initWithStorage:(FIRStorage *)storage + path:(FIRStoragePath *)path NS_DESIGNATED_INITIALIZER; + +- (NSString *)stringValue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTaskSnapshot_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTaskSnapshot_Private.h new file mode 100644 index 0000000..1762a61 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTaskSnapshot_Private.h @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageConstants_Private.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRStorageMetadata; +@class FIRStorageReference; +@class FIRStorageTask; + +@interface FIRStorageTaskSnapshot () + +@property(readwrite, copy, nonatomic) FIRStorageTask *task; +@property(readwrite, copy, nonatomic) FIRStorageMetadata *metadata; +@property(readwrite, copy, nonatomic) FIRStorageReference *reference; +@property(readwrite, strong, nonatomic) NSProgress *progress; +@property(readwrite, copy, nonatomic) NSError *error; + +/** + * Creates a new task snapshot from the given properties. + * @param task The task being represented in this snapshot. + * @param state The current state of the parent task. + * @param metadata The FIRStorageMetadata of a task. Before upload/update, contains the metadata + * to be updated; after, contains the returned metadata. May be nil if no metadata is provided + * or returned. + * @param reference The FIRStorageReference that spawned the task this snapshot is based on. + * @param progress An NSProgress object containing progress of the task this snapshot is based on, + * or nil if the task doesn't report progress. + * @param error An NSError object containing an error that occurred during the task, + * if one occurred. + * @return Returns the constructed snapshot. + */ +- (instancetype)initWithTask:(__kindof FIRStorageTask *)task + state:(FIRStorageTaskState)state + metadata:(nullable FIRStorageMetadata *)metadata + reference:(FIRStorageReference *)reference + progress:(nullable NSProgress *)progress + error:(nullable NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTask_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTask_Private.h new file mode 100644 index 0000000..582043e --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTask_Private.h @@ -0,0 +1,91 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageConstants_Private.h" +#import "FIRStorageErrors.h" +#import "FIRStorageReference.h" +#import "FIRStorageReference_Private.h" +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageTaskSnapshot_Private.h" +#import "FIRStorageUtils.h" + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorageTask () + +/** + * State for the current task in progress. + */ +@property(atomic) FIRStorageTaskState state; + +/** + * FIRStorageMetadata for the task in progress, or nil if none present. + */ +@property(strong, nonatomic, nullable) FIRStorageMetadata *metadata; + +/** + * Error which occurred during task execution, or nil if no error occurred. + */ +@property(strong, nonatomic, nullable) NSError *error; + +/** + * NSProgress object which tracks the progess of an observable task. + */ +@property(strong, nonatomic) NSProgress *progress; + +/** + * Reference pointing to the location the task is being performed against. + */ +@property(strong, nonatomic) FIRStorageReference *reference; + +/** + * A serial queue for all storage operations. + */ +@property(nonatomic, readonly) dispatch_queue_t dispatchQueue; + +@property(strong, readwrite, nonatomic, nonnull) FIRStorageTaskSnapshot *snapshot; + +@property(readonly, copy, nonatomic) NSURLRequest *baseRequest; + +@property(strong, atomic) GTMSessionFetcher *fetcher; + +@property(readonly, nonatomic) GTMSessionFetcherService *fetcherService; + +@property(readonly, copy) GTMSessionFetcherCompletionHandler fetcherCompletion; + +- (instancetype)init NS_UNAVAILABLE; + +/** + * Creates a new FIRStorageTask initialized with a FIRStorageReference and GTMSessionFetcherService. + * @param reference A FIRStorageReference the task will be performed on. + * @param service A GTMSessionFetcherService which provides the fetchers and configuration for + * requests. + * @param queue The shared queue to use for all Storage operations. + * @return A new FIRStorageTask representing the current task. + */ +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER; + +/** Dispatches a block on the shared Storage queue. */ +- (void)dispatchAsync:(void (^)(void))block; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTokenAuthorizer.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTokenAuthorizer.h new file mode 100644 index 0000000..75893dd --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageTokenAuthorizer.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@protocol FIRAuthInterop; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Wrapper class for FIRAuthInterop that implements the GTMFetcherAuthorizationProtocol, + * so as to easily provide GTMSessionFetcher fetches a Firebase Authentication JWT + * for the current logged in user. Handles token expiration and other failure cases. + * If no authentication provider exists or no token is found, no token is added + * and the request is passed. + */ +@interface FIRStorageTokenAuthorizer : NSObject + +/** + * Initializes the token authorizer with an instance of FIRApp. + * @param googleAppID The Google AppID of the app to send with the request. + * @param auth An instance that provides access to Auth functionality, if it exists. + * @return Returns an instance of FIRStorageTokenAuthorizer which adds the appropriate + * "Authorization" header to all outbound requests. Note that a token may not be added + * if the Auth instance is nil. This allows for unauthenticated access, if Firebase + * Storage rules allow for it. + */ +- (instancetype)initWithGoogleAppID:(NSString *)googleAppID + fetcherService:(GTMSessionFetcherService *)service + authProvider:(nullable id)auth; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUpdateMetadataTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUpdateMetadataTask.h new file mode 100644 index 0000000..23c6c34 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUpdateMetadataTask.h @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageTask.h" + +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Task which provides the ability update the metadata on an object in Firebase Storage. + */ +@interface FIRStorageUpdateMetadataTask : FIRStorageTask + +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + metadata:(FIRStorageMetadata *)metadata + completion:(FIRStorageVoidMetadataError)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUploadTask_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUploadTask_Private.h new file mode 100644 index 0000000..8d37a8b --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUploadTask_Private.h @@ -0,0 +1,73 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@class GTMSessionUploadFetcher; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorageUploadTask () + +/** + * The data to be uploaded (if uploading bytes). + */ +@property(readonly, copy, nonatomic, nullable) NSData *uploadData; + +/** + * The name of a file on disk to be uploaded (if uploading from a file). + */ +@property(readonly, copy, nonatomic, nullable) NSURL *fileURL; + +/** + * The FIRStorageMetadata about the object being uploaded. + */ +@property(readonly, copy, nonatomic) FIRStorageMetadata *uploadMetadata; + +/** + * GTMSessionUploadFetcher used by all uploads. + */ +@property(strong, atomic) GTMSessionUploadFetcher *uploadFetcher; + +/** + * Initializes an upload task with a base FIRStorageReference and GTMSessionFetcherService. + * @param reference The base FIRStorageReference which fetchers use for configuration. + * @param service The GTMSessionFetcherService which will create fetchers. + * @param queue The shared queue to use for all Storage operations. + * @param uploadData The NSData object to be uploaded. + * @return Returns an instance of FIRStorageUploadTask. + */ +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + data:(NSData *)uploadData + metadata:(FIRStorageMetadata *)metadata; + +/** + * Initializes an upload task with a base FIRStorageReference and GTMSessionFetcherService. + * @param reference The base FIRStorageReference which fetchers use for configuration. + * @param service The GTMSessionFetcherService which will create fetchers. + * @param queue The shared queue to use for all Storage operations. + * @param fileURL The system file URL to upload from. + * @return Returns an instance of FIRStorageUploadTask. + */ +- (instancetype)initWithReference:(FIRStorageReference *)reference + fetcherService:(GTMSessionFetcherService *)service + dispatchQueue:(dispatch_queue_t)queue + file:(NSURL *)fileURL + metadata:(FIRStorageMetadata *)metadata; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUtils.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUtils.h new file mode 100644 index 0000000..e687c82 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorageUtils.h @@ -0,0 +1,93 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRStoragePath; + +NS_ASSUME_NONNULL_BEGIN + +/** + * FIRStorageUtils provides a number of helper methods for commonly used operations + * in Firebase Storage, such as JSON parsing, escaping, and file extensions. + */ +@interface FIRStorageUtils : NSObject + +/** + * Returns a percent encoded string appropriate for GCS. + * See https://cloud.google.com/storage/docs/naming for more details. + * @param string A path to escape characters according to the GCS + * @return A percent encoded string appropriate for GCS operations or nil if string is nil + * or can't be escaped. + */ ++ (nullable NSString *)GCSEscapedString:(NSString *)string; + +/** + * Returns the MIME type for a file extension. + * Example of how to get MIME type here: http://ddeville.me/2011/12/mime-to-UTI-cocoa/ + * @param extension A file extension such as "txt", "png", etc. + * @return The MIME type for the input extension such as "text/plain", "image/png", etc. + * or nil if no type is found. + */ ++ (nullable NSString *)MIMETypeForExtension:(NSString *)extension; + +/** + * Returns a properly escaped query string from a given dictionary of query items to values. + * @param dictionary A dictionary containing query items and associated values. + * @return A properly escaped query string or the empty string for a nil or empty dictionary. + */ ++ (NSString *)queryStringForDictionary:(nullable NSDictionary *)dictionary; + +/** + * Returns a base NSURLRequest used by all tasks. + * @param path The FIRStoragePath to create a request for. + * @return Returns a properly formatted NSURLRequest of the form: + * scheme://host/version/b//o[/path/to/object] + */ ++ (NSURLRequest *)defaultRequestForPath:(FIRStoragePath *)path; + +/** + * Creates the appropriate GCS percent escaped path for a given FIRStoragePath. + * @param path The FIRStoragePath to encode. + * @return Returns the GCS encoded URL for a given FIRStoragePath. + */ ++ (NSString *)encodedURLForPath:(FIRStoragePath *)path; + +@end + +@interface NSDictionary (FIRStorageNSDictionaryJSONHelpers) + +/** + * Returns a dictionary representation of the data in @a data. + * @param data NSData containing JSON data. + * @return An NSDictionary representation of the JSON, or nil if serialization failed. + */ ++ (nullable instancetype)frs_dictionaryFromJSONData:(nullable NSData *)data; + +@end + +@interface NSData (FIRStorageNSDataJSONHelpers) + +/** + * Returns an NSData instance containing JSON serialized from @a dictionary. + * @param dictionary An NSDictionary containing only types serializable to JSON. + * @return An NSData object representing the binary JSON, or nil if serialization failed. + */ ++ (nullable instancetype)frs_dataFromJSONDictionary:(nullable NSDictionary *)dictionary; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorage_Private.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorage_Private.h new file mode 100644 index 0000000..04cecc1 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Private/FIRStorage_Private.h @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@class FIRApp; +@class GTMSessionFetcherService; + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRStorage () + +@property(strong, nonatomic, readwrite) FIRApp *app; + +@property(strong, nonatomic) GTMSessionFetcherService *fetcherServiceForApp; + +@property(nonatomic, readonly) dispatch_queue_t dispatchQueue; + +@property(strong, nonatomic) NSString *storageBucket; + +/** + * Enables/disables GTMSessionFetcher HTTP logging + * @param isLoggingEnabled Boolean passed through to enable/disable GTMSessionFetcher logging + */ ++ (void)setGTMSessionFetcherLoggingEnabled:(BOOL)isLoggingEnabled; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorage.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorage.h new file mode 100644 index 0000000..baa8122 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorage.h @@ -0,0 +1,129 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorageConstants.h" + +@class FIRApp; +@class FIRStorageReference; + +NS_ASSUME_NONNULL_BEGIN + +/** Project version string for FirebaseStorage. */ +FOUNDATION_EXPORT const unsigned char *const FIRStorageVersionString + NS_SWIFT_NAME(StorageVersionString); + +/** + * FirebaseStorage is a service that supports uploading and downloading binary objects, + * such as images, videos, and other files to Google Cloud Storage. + * + * If you call [FIRStorage storage], the instance will initialize with the default FIRApp, + * [FIRApp defaultApp], and the storage location will come from the provided + * GoogleService-Info.plist. + * + * If you call [FIRStorage storageForApp:] and provide a custom instance of FIRApp, + * the storage location will be specified via the FIROptions#storageBucket property. + */ +NS_SWIFT_NAME(Storage) +@interface FIRStorage : NSObject + +/** + * Creates an instance of FIRStorage, configured with the default FIRApp. + * @return the FIRStorage instance, initialized with the default FIRApp. + */ ++ (instancetype)storage NS_SWIFT_NAME(storage()); + +/** + * Creates an instance of FIRStorage, configured with the custom FIRApp @a app. + * @param app The custom FIRApp used for initialization. + * @return the FIRStorage instance, initialized with the custom FIRApp. + */ ++ (instancetype)storageForApp:(FIRApp *)app NS_SWIFT_NAME(storage(app:)); + +/** + * Creates an instance of FIRStorage, configured with a custom storage bucket @a url. + * @param url The gs:// url to your Firebase Storage Bucket. + * @return the FIRStorage instance, initialized with the custom FIRApp. + */ ++ (instancetype)storageWithURL:(NSString *)url NS_SWIFT_NAME(storage(url:)); + +/** + * Creates an instance of FIRStorage, configured with a custom FIRApp @a app and a custom storage + * bucket @a url. + * @param app The custom FIRApp used for initialization. + * @param url The gs:// url to your Firebase Storage Bucket. + * @return the FIRStorage instance, initialized with the custom FIRApp. + */ ++ (instancetype)storageForApp:(FIRApp *)app URL:(NSString *)url NS_SWIFT_NAME(storage(app:url:)); + +/** + * The Firebase App associated with this Firebase Storage instance. + */ +@property(strong, nonatomic, readonly) FIRApp *app; + +/** + * Maximum time in seconds to retry an upload if a failure occurs. + * Defaults to 10 minutes (600 seconds). + */ +@property NSTimeInterval maxUploadRetryTime; + +/** + * Maximum time in seconds to retry a download if a failure occurs. + * Defaults to 10 minutes (600 seconds). + */ +@property NSTimeInterval maxDownloadRetryTime; + +/** + * Maximum time in seconds to retry operations other than upload and download if a failure occurs. + * Defaults to 2 minutes (120 seconds). + */ +@property NSTimeInterval maxOperationRetryTime; + +/** + * Queue that all developer callbacks are fired on. Defaults to the main queue. + */ +@property(strong, nonatomic) dispatch_queue_t callbackQueue; + +/** + * Creates a FIRStorageReference initialized at the root Firebase Storage location. + * @return An instance of FIRStorageReference initialized at the root. + */ +- (FIRStorageReference *)reference; + +/** + * Creates a FIRStorageReference given a gs:// or https:// URL pointing to a Firebase Storage + * location. For example, you can pass in an https:// download URL retrieved from + * [FIRStorageReference downloadURLWithCompletion] or the gs:// URI from + * [FIRStorageReference description]. + * @param string A gs:// or https:// URL to initialize the reference with. + * @return An instance of FIRStorageReference at the given child path. + * @throws Throws an exception if passed in URL is not associated with the FIRApp used to initialize + * this FIRStorage. + */ +- (FIRStorageReference *)referenceForURL:(NSString *)string; + +/** + * Creates a FIRStorageReference initialized at a child Firebase Storage location. + * @param string A relative path from the root to initialize the reference with, + * for instance @"path/to/object". + * @return An instance of FIRStorageReference at the given child path. + */ +- (FIRStorageReference *)referenceWithPath:(NSString *)string; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageConstants.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageConstants.h new file mode 100644 index 0000000..be20135 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageConstants.h @@ -0,0 +1,171 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRStorageDownloadTask; +@class FIRStorageMetadata; +@class FIRStorageTaskSnapshot; +@class FIRStorageUploadTask; + +NS_ASSUME_NONNULL_BEGIN + +/** + * NSString typedef representing a task listener handle. + */ +typedef NSString *FIRStorageHandle NS_SWIFT_NAME(StorageHandle); + +/** + * Block typedef typically used when downloading data. + * @param data The data returned by the download, or nil if no data available or download failed. + * @param error The error describing failure, if one occurred. + */ +typedef void (^FIRStorageVoidDataError)(NSData *_Nullable data, NSError *_Nullable error) + NS_SWIFT_NAME(StorageVoidDataError); + +/** + * Block typedef typically used when performing "binary" async operations such as delete, + * where the operation either succeeds without an error or fails with an error. + * @param error The error describing failure, if one occurred. + */ +typedef void (^FIRStorageVoidError)(NSError *_Nullable error) NS_SWIFT_NAME(StorageVoidError); + +/** + * Block typedef typically used when retrieving metadata. + * @param metadata The metadata returned by the operation, if metadata exists. + */ +typedef void (^FIRStorageVoidMetadata)(FIRStorageMetadata *_Nullable metadata) + NS_SWIFT_NAME(StorageVoidMetadata); + +/** + * Block typedef typically used when retrieving metadata with the possibility of an error. + * @param metadata The metadata returned by the operation, if metadata exists. + * @param error The error describing failure, if one occurred. + */ +typedef void (^FIRStorageVoidMetadataError)(FIRStorageMetadata *_Nullable metadata, + NSError *_Nullable error) + NS_SWIFT_NAME(StorageVoidMetadataError); + +/** + * Block typedef typically used to asynchronously return a storage task snapshot. + * @param snapshot The returned task snapshot. + */ +typedef void (^FIRStorageVoidSnapshot)(FIRStorageTaskSnapshot *snapshot) + NS_SWIFT_NAME(StorageVoidSnapshot); + +/** + * Block typedef typically used when retrieving a download URL. + * @param URL The download URL associated with the operation. + * @param error The error describing failure, if one occurred. + */ +typedef void (^FIRStorageVoidURLError)(NSURL *_Nullable URL, NSError *_Nullable error) + NS_SWIFT_NAME(StorageVoidURLError); + +/** + * Enum representing the upload and download task status. + */ +typedef NS_ENUM(NSInteger, FIRStorageTaskStatus) { + /** + * Unknown task status. + */ + FIRStorageTaskStatusUnknown, + + /** + * Task is being resumed. + */ + FIRStorageTaskStatusResume, + + /** + * Task reported a progress event. + */ + FIRStorageTaskStatusProgress, + + /** + * Task is paused. + */ + FIRStorageTaskStatusPause, + + /** + * Task has completed successfully. + */ + FIRStorageTaskStatusSuccess, + + /** + * Task has failed and is unrecoverable. + */ + FIRStorageTaskStatusFailure +} NS_SWIFT_NAME(StorageTaskStatus); + +/** + * Firebase Storage error domain. + */ +FOUNDATION_EXPORT NSString *const FIRStorageErrorDomain NS_SWIFT_NAME(StorageErrorDomain); + +/** + * Enum representing the errors raised by Firebase Storage. + */ +typedef NS_ENUM(NSInteger, FIRStorageErrorCode) { + /** An unknown error occurred. */ + FIRStorageErrorCodeUnknown = -13000, + + /** No object exists at the desired reference. */ + FIRStorageErrorCodeObjectNotFound = -13010, + + /** No bucket is configured for Firebase Storage. */ + FIRStorageErrorCodeBucketNotFound = -13011, + + /** No project is configured for Firebase Storage. */ + FIRStorageErrorCodeProjectNotFound = -13012, + + /** + * Quota on your Firebase Storage bucket has been exceeded. + * If you're on the free tier, upgrade to a paid plan. + * If you're on a paid plan, reach out to Firebase support. + */ + FIRStorageErrorCodeQuotaExceeded = -13013, + + /** User is unauthenticated. Authenticate and try again. */ + FIRStorageErrorCodeUnauthenticated = -13020, + + /** + * User is not authorized to perform the desired action. + * Check your rules to ensure they are correct. + */ + FIRStorageErrorCodeUnauthorized = -13021, + + /** + * The maximum time limit on an operation (upload, download, delete, etc.) has been exceeded. + * Try uploading again. + */ + FIRStorageErrorCodeRetryLimitExceeded = -13030, + + /** + * File on the client does not match the checksum of the file received by the server. + * Try uploading again. + */ + FIRStorageErrorCodeNonMatchingChecksum = -13031, + + /** + * Size of the downloaded file exceeds the amount of memory allocated for the download. + * Increase memory cap and try downloading again. + */ + FIRStorageErrorCodeDownloadSizeExceeded = -13032, + + /** User cancelled the operation. */ + FIRStorageErrorCodeCancelled = -13040 +} NS_SWIFT_NAME(StorageErrorCode); + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageDownloadTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageDownloadTask.h new file mode 100644 index 0000000..c11373f --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageDownloadTask.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorageObservableTask.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * FIRStorageDownloadTask implements resumable downloads from an object in Firebase Storage. + * Downloads can be returned on completion with a completion handler, and can be monitored + * by attaching observers, or controlled by calling FIRStorageTask#pause, FIRStorageTask#resume, + * or FIRStorageTask#cancel. + * Downloads can currently be returned as NSData in memory, or as an NSURL to a file on disk. + * Downloads are performed on a background queue, and callbacks are raised on the developer + * specified callbackQueue in FIRStorage, or the main queue if left unspecified. + * Currently all uploads must be initiated and managed on the main queue. + */ +NS_SWIFT_NAME(StorageDownloadTask) +@interface FIRStorageDownloadTask : FIRStorageObservableTask + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageMetadata.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageMetadata.h new file mode 100644 index 0000000..63b8798 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageMetadata.h @@ -0,0 +1,140 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class FIRStorageReference; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Class which represents the metadata on an object in Firebase Storage. This metadata is + * returned on successful operations, and can be used to retrieve download URLs, content types, + * and a FIRStorage reference to the object in question. Full documentation can be found at the GCS + * Objects#resource docs. + * @see https://cloud.google.com/storage/docs/json_api/v1/objects#resource + */ +NS_SWIFT_NAME(StorageMetadata) +@interface FIRStorageMetadata : NSObject + +/** + * The name of the bucket containing this object. + */ +@property(copy, nonatomic, readonly) NSString *bucket; + +/** + * Cache-Control directive for the object data. + */ +@property(copy, nonatomic, nullable) NSString *cacheControl; + +/** + * Content-Disposition of the object data. + */ +@property(copy, nonatomic, nullable) NSString *contentDisposition; + +/** + * Content-Encoding of the object data. + */ +@property(copy, nonatomic, nullable) NSString *contentEncoding; + +/** + * Content-Language of the object data. + */ +@property(copy, nonatomic, nullable) NSString *contentLanguage; + +/** + * Content-Type of the object data. + */ +@property(copy, nonatomic, nullable) NSString *contentType; + +/** + * MD5 hash of the data; encoded using base64. + */ +@property(copy, nonatomic, nullable, readonly) NSString *md5Hash; + +/** + * The content generation of this object. Used for object versioning. + */ +@property(readonly) int64_t generation; + +/** + * User-provided metadata, in key/value pairs. + */ +@property(copy, nonatomic, nullable) NSDictionary *customMetadata; + +/** + * The version of the metadata for this object at this generation. Used + * for preconditions and for detecting changes in metadata. A metageneration number is only + * meaningful in the context of a particular generation of a particular object. + */ +@property(readonly) int64_t metageneration; + +/** + * The name of this object, in gs://bucket/path/to/object.txt, this is object.txt. + */ +@property(copy, nonatomic, readonly, nullable) NSString *name; + +/** + * The full path of this object, in gs://bucket/path/to/object.txt, this is path/to/object.txt. + */ +@property(copy, nonatomic, readonly, nullable) NSString *path; + +/** + * Content-Length of the data in bytes. + */ +@property(readonly) int64_t size; + +/** + * The creation time of the object in RFC 3339 format. + */ +@property(copy, nonatomic, readonly, nullable) NSDate *timeCreated; + +/** + * The modification time of the object metadata in RFC 3339 format. + */ +@property(copy, nonatomic, readonly, nullable) NSDate *updated; + +/** + * A reference to the object in Firebase Storage. + */ +@property(strong, nonatomic, readonly, nullable) FIRStorageReference *storageReference; + +/** + * Creates an instanece of FIRStorageMetadata from the contents of a dictionary. + * @return An instance of FIRStorageMetadata that represents the contents of a dictionary. + */ +- (nullable instancetype)initWithDictionary:(NSDictionary *)dictionary + NS_DESIGNATED_INITIALIZER; + +/** + * Creates an NSDictionary from the contents of the metadata. + * @return An NSDictionary that represents the contents of the metadata. + */ +- (NSDictionary *)dictionaryRepresentation; + +/** + * Determines if the current metadata represents a "file". + */ +@property(readonly, getter=isFile) BOOL file; + +/** + * Determines if the current metadata represents a "folder". + */ +@property(readonly, getter=isFolder) BOOL folder; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageObservableTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageObservableTask.h new file mode 100644 index 0000000..d8ad401 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageObservableTask.h @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorageTask.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRStorageReference; +@class FIRStorageTaskSnapshot; + +/** + * Extends FIRStorageTask to provide observable semantics such as adding and removing observers. + * Observers produce a FIRStorageHandle, which is used to keep track of and remove specific + * observers at a later date. + * This class is currently not thread safe and can only be called on the main thread. + */ +NS_SWIFT_NAME(StorageObservableTask) +@interface FIRStorageObservableTask : FIRStorageTask + +/** + * Observes changes in the upload status: Resume, Pause, Progress, Success, and Failure. + * @param status The FIRStorageTaskStatus change to observe. + * @param handler A callback that fires every time the status event occurs, + * returns a FIRStorageTaskSnapshot containing the state of the task. + * @return A task handle that can be used to remove the observer at a later date. + */ +- (FIRStorageHandle)observeStatus:(FIRStorageTaskStatus)status + handler:(void (^)(FIRStorageTaskSnapshot *snapshot))handler; + +/** + * Removes the single observer with the provided handle. + * @param handle The handle of the task to remove. + */ +- (void)removeObserverWithHandle:(FIRStorageHandle)handle; + +/** + * Removes all observers for a single status. + * @param status A FIRStorageTaskStatus to remove listeners for. + */ +- (void)removeAllObserversForStatus:(FIRStorageTaskStatus)status; + +/** + * Removes all observers. + */ +- (void)removeAllObservers; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageReference.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageReference.h new file mode 100644 index 0000000..a63c127 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageReference.h @@ -0,0 +1,256 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorage.h" +#import "FIRStorageConstants.h" +#import "FIRStorageDownloadTask.h" +#import "FIRStorageMetadata.h" +#import "FIRStorageTask.h" +#import "FIRStorageUploadTask.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * FIRStorageReference represents a reference to a Google Cloud Storage object. Developers can + * upload and download objects, as well as get/set object metadata, and delete an object at the + * path. + * @see https://cloud.google.com/storage/ + */ +NS_SWIFT_NAME(StorageReference) +@interface FIRStorageReference : NSObject + +/** + * The FIRStorage service object which created this reference. + */ +@property(nonatomic, readonly) FIRStorage *storage; + +/** + * The name of the Google Cloud Storage bucket associated with this reference, + * in gs://bucket/path/to/object.txt, the bucket would be: 'bucket' + */ +@property(nonatomic, readonly) NSString *bucket; + +/** + * The full path to this object, not including the Google Cloud Storage bucket. + * In gs://bucket/path/to/object.txt, the full path would be: 'path/to/object.txt' + */ +@property(nonatomic, readonly) NSString *fullPath; + +/** + * The short name of the object associated with this reference, + * in gs://bucket/path/to/object.txt, the name of the object would be: 'object.txt' + */ +@property(nonatomic, readonly) NSString *name; + +#pragma mark - Path Operations + +/** + * Creates a new FIRStorageReference pointing to the root object. + * @return A new FIRStorageReference pointing to the root object. + */ +- (FIRStorageReference *)root; + +/** + * Creates a new FIRStorageReference pointing to the parent of the current reference + * or nil if this instance references the root location. + * For example: + * path = foo/bar/baz parent = foo/bar + * path = foo parent = (root) + * path = (root) parent = nil + * @return A new FIRStorageReference pointing to the parent of the current reference. + */ +- (nullable FIRStorageReference *)parent; + +/** + * Creates a new FIRStorageReference pointing to a child object of the current reference. + * path = foo child = bar newPath = foo/bar + * path = foo/bar child = baz newPath = foo/bar/baz + * All leading and trailing slashes will be removed, and consecutive slashes will be + * compressed to single slashes. For example: + * child = /foo/bar newPath = foo/bar + * child = foo/bar/ newPath = foo/bar + * child = foo///bar newPath = foo/bar + * @param path Path to append to the current path. + * @return A new FIRStorageReference pointing to a child location of the current reference. + */ +- (FIRStorageReference *)child:(NSString *)path; + +#pragma mark - Uploads + +/** + * Asynchronously uploads data to the currently specified FIRStorageReference, + * without additional metadata. + * This is not recommended for large files, and one should instead upload a file from disk. + * @param uploadData The NSData to upload. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +- (FIRStorageUploadTask *)putData:(NSData *)uploadData NS_SWIFT_NAME(putData(_:)); + +/** + * Asynchronously uploads data to the currently specified FIRStorageReference. + * This is not recommended for large files, and one should instead upload a file from disk. + * @param uploadData The NSData to upload. + * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) + * about the object being uploaded. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +// clang-format off +- (FIRStorageUploadTask *)putData:(NSData *)uploadData + metadata:(nullable FIRStorageMetadata *)metadata +NS_SWIFT_NAME(putData(_:metadata:)); +// clang-format on + +/** + * Asynchronously uploads data to the currently specified FIRStorageReference. + * This is not recommended for large files, and one should instead upload a file from disk. + * @param uploadData The NSData to upload. + * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) + * about the object being uploaded. + * @param completion A completion block that either returns the object metadata on success, + * or an error on failure. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +// clang-format off +- (FIRStorageUploadTask *)putData:(NSData *)uploadData + metadata:(nullable FIRStorageMetadata *)metadata + completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, + NSError *_Nullable error))completion + NS_SWIFT_NAME(putData(_:metadata:completion:)); +// clang-format on + +/** + * Asynchronously uploads a file to the currently specified FIRStorageReference, + * without additional metadata. + * @param fileURL A URL representing the system file path of the object to be uploaded. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL NS_SWIFT_NAME(putFile(from:)); + +/** + * Asynchronously uploads a file to the currently specified FIRStorageReference. + * @param fileURL A URL representing the system file path of the object to be uploaded. + * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) + * about the object being uploaded. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +// clang-format off +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL + metadata:(nullable FIRStorageMetadata *)metadata + NS_SWIFT_NAME(putFile(from:metadata:)); +// clang-format on + +/** + * Asynchronously uploads a file to the currently specified FIRStorageReference. + * @param fileURL A URL representing the system file path of the object to be uploaded. + * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) + * about the object being uploaded. + * @param completion A completion block that either returns the object metadata on success, + * or an error on failure. + * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. + */ +// clang-format off +- (FIRStorageUploadTask *)putFile:(NSURL *)fileURL + metadata:(nullable FIRStorageMetadata *)metadata + completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, + NSError *_Nullable error))completion + NS_SWIFT_NAME(putFile(from:metadata:completion:)); +// clang-format on + +#pragma mark - Downloads + +/** + * Asynchronously downloads the object at the FIRStorageReference to an NSData object in memory. + * An NSData of the provided max size will be allocated, so ensure that the device has enough free + * memory to complete the download. For downloading large files, writeToFile may be a better option. + * @param size The maximum size in bytes to download. If the download exceeds this size + * the task will be cancelled and an error will be returned. + * @param completion A completion block that either returns the object data on success, + * or an error on failure. + * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. + */ +// clang-format off +- (FIRStorageDownloadTask *)dataWithMaxSize:(int64_t)size + completion:(void (^)(NSData *_Nullable data, + NSError *_Nullable error))completion + NS_SWIFT_NAME(getData(maxSize:completion:)); +// clang-format on + +/** + * Asynchronously retrieves a long lived download URL with a revokable token. + * This can be used to share the file with others, but can be revoked by a developer + * in the Firebase Console if desired. + * @param completion A completion block that either returns the URL on success, + * or an error on failure. + */ +- (void)downloadURLWithCompletion:(void (^)(NSURL *_Nullable URL, + NSError *_Nullable error))completion; + +/** + * Asynchronously downloads the object at the current path to a specified system filepath. + * @param fileURL A file system URL representing the path the object should be downloaded to. + * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. + */ +- (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL; + +/** + * Asynchronously downloads the object at the current path to a specified system filepath. + * @param fileURL A file system URL representing the path the object should be downloaded to. + * @param completion A completion block that fires when the file download completes. + * Returns an NSURL pointing to the file path of the downloaded file on success, + * or an error on failure. + * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. + */ +- (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL + completion:(nullable void (^)(NSURL *_Nullable URL, + NSError *_Nullable error))completion; + +#pragma mark - Metadata Operations + +/** + * Retrieves metadata associated with an object at the current path. + * @param completion A completion block which returns the object metadata on success, + * or an error on failure. + */ +- (void)metadataWithCompletion: + (void (^)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error))completion + NS_SWIFT_NAME(getMetadata(completion:)); + +/** + * Updates the metadata associated with an object at the current path. + * @param metadata An FIRStorageMetadata object with the metadata to update. + * @param completion A completion block which returns the FIRStorageMetadata on success, + * or an error on failure. + */ +// clang-format off +- (void)updateMetadata:(FIRStorageMetadata *)metadata + completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, + NSError *_Nullable error))completion +NS_SWIFT_NAME(updateMetadata(_:completion:)); +// clang-format on + +#pragma mark - Delete + +/** + * Deletes the object at the current path. + * @param completion A completion block which returns nil on success, or an error on failure. + */ +- (void)deleteWithCompletion:(nullable void (^)(NSError *_Nullable error))completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTask.h new file mode 100644 index 0000000..e889d5e --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTask.h @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorageConstants.h" +#import "FIRStorageMetadata.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * A superclass to all FIRStorage*Tasks, including FIRStorageUploadTask + * and FIRStorageDownloadTask, to provide state transitions, event raising, and common storage + * or metadata and errors. + * Callbacks are always fired on the developer specified callback queue. + * If no queue is specified by the developer, it defaults to the main queue. + * Currently not thread safe, so only call methods on the main thread. + */ +NS_SWIFT_NAME(StorageTask) +@interface FIRStorageTask : NSObject + +/** + * An immutable view of the task and associated metadata, progress, error, etc. + */ +@property(strong, readonly, nonatomic, nonnull) FIRStorageTaskSnapshot *snapshot; + +@end + +/** + * Defines task operations such as pause, resume, cancel, and enqueue for all tasks. + * All tasks are required to implement enqueue, which begins the task, and may optionally + * implement pause, resume, and cancel, which operate on the task to pause, resume, and cancel + * operations. + */ +NS_SWIFT_NAME(StorageTaskManagement) +@protocol FIRStorageTaskManagement + +@required +/** + * Prepares a task and begins execution. + */ +- (void)enqueue; + +@optional +/** + * Pauses a task currently in progress. + */ +- (void)pause; + +/** + * Cancels a task currently in progress. + */ +- (void)cancel; + +/** + * Resumes a task that is paused. + */ +- (void)resume; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTaskSnapshot.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTaskSnapshot.h new file mode 100644 index 0000000..7d14202 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageTaskSnapshot.h @@ -0,0 +1,67 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorageConstants.h" + +NS_ASSUME_NONNULL_BEGIN + +@class FIRStorageMetadata; +@class FIRStorageReference; +@class FIRStorageTask; + +/** + * FIRStorageTaskSnapshot represents an immutable view of a task. + * A Snapshot contains a task, storage reference, metadata (if it exists), + * progress, and an error (if one occurred). + */ +NS_SWIFT_NAME(StorageTaskSnapshot) +@interface FIRStorageTaskSnapshot : NSObject + +/** + * Subclass of FIRStorageTask this snapshot represents. + */ +@property(readonly, copy, nonatomic) __kindof FIRStorageTask *task; + +/** + * Metadata returned by the task, or nil if no metadata returned. + */ +@property(readonly, copy, nonatomic, nullable) FIRStorageMetadata *metadata; + +/** + * FIRStorageReference this task is operates on. + */ +@property(readonly, copy, nonatomic) FIRStorageReference *reference; + +/** + * NSProgress object which tracks the progess of an upload or download. + */ +@property(readonly, strong, nonatomic, nullable) NSProgress *progress; + +/** + * Error during task execution, or nil if no error occurred. + */ +@property(readonly, copy, nonatomic, nullable) NSError *error; + +/** + * Status of the task. + */ +@property(readonly, nonatomic) FIRStorageTaskStatus status; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageUploadTask.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageUploadTask.h new file mode 100644 index 0000000..c753500 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FIRStorageUploadTask.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FIRStorageObservableTask.h" + +NS_ASSUME_NONNULL_BEGIN + +/** + * FIRStorageUploadTask implements resumable uploads to a file in Firebase Storage. + * Uploads can be returned on completion with a completion callback, and can be monitored + * by attaching observers, or controlled by calling FIRStorageTask#pause, FIRStorageTask#resume, + * or FIRStorageTask#cancel. + * Uploads can take NSData in memory, or an NSURL to a file on disk. + * Uploads are performed on a background queue, and callbacks are raised on the developer + * specified callbackQueue in FIRStorage, or the main queue if left unspecified. + * Currently all uploads must be initiated and managed on the main queue. + */ +NS_SWIFT_NAME(StorageUploadTask) +@interface FIRStorageUploadTask : FIRStorageObservableTask + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FirebaseStorage.h b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FirebaseStorage.h new file mode 100644 index 0000000..1e5dfa4 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/Firebase/Storage/Public/FirebaseStorage.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FIRStorage.h" +#import "FIRStorageConstants.h" +#import "FIRStorageDownloadTask.h" +#import "FIRStorageMetadata.h" +#import "FIRStorageObservableTask.h" +#import "FIRStorageReference.h" +#import "FIRStorageTask.h" +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageUploadTask.h" diff --git a/My Mind/Pods/FirebaseStorage/LICENSE b/My Mind/Pods/FirebaseStorage/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/FirebaseStorage/README.md b/My Mind/Pods/FirebaseStorage/README.md new file mode 100644 index 0000000..00e6ade --- /dev/null +++ b/My Mind/Pods/FirebaseStorage/README.md @@ -0,0 +1,185 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/GTMSessionFetcher/LICENSE b/My Mind/Pods/GTMSessionFetcher/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/GTMSessionFetcher/README.md b/My Mind/Pods/GTMSessionFetcher/README.md new file mode 100644 index 0000000..478efde --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/README.md @@ -0,0 +1,23 @@ +# Google Toolbox for Mac - Session Fetcher # + +**Project site**
+**Discussion group** + +[![Build Status](https://travis-ci.org/google/gtm-session-fetcher.svg?branch=master)](https://travis-ci.org/google/gtm-session-fetcher) + +`GTMSessionFetcher` makes it easy for Cocoa applications to perform http +operations. The fetcher is implemented as a wrapper on `NSURLSession`, so its +behavior is asynchronous and uses operating-system settings on iOS and Mac OS X. + +Features include: +- Simple to build; only one source/header file pair is required +- Simple to use: takes just two lines of code to fetch a request +- Supports upload and download sessions +- Flexible cookie storage +- Automatic retry on errors, with exponential backoff +- Support for generating multipart MIME upload streams +- Easy, convenient logging of http requests and responses +- Supports plug-in authentication such as with GTMAppAuth +- Easily testable; self-mocking +- Automatic rate limiting when created by the `GTMSessionFetcherService` factory class +- Fully independent of other projects diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h new file mode 100644 index 0000000..7f5fcda --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h @@ -0,0 +1,1305 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// GTMSessionFetcher is a wrapper around NSURLSession for http operations. +// +// What does this offer on top of of NSURLSession? +// +// - Block-style callbacks for useful functionality like progress rather +// than delegate methods. +// - Out-of-process uploads and downloads using NSURLSession, including +// management of fetches after relaunch. +// - Integration with GTMAppAuth for invisible management and refresh of +// authorization tokens. +// - Pretty-printed http logging. +// - Cookies handling that does not interfere with or get interfered with +// by WebKit cookies or on Mac by Safari and other apps. +// - Credentials handling for the http operation. +// - Rate-limiting and cookie grouping when fetchers are created with +// GTMSessionFetcherService. +// +// If the bodyData or bodyFileURL property is set, then a POST request is assumed. +// +// Each fetcher is assumed to be for a one-shot fetch request; don't reuse the object +// for a second fetch. +// +// The fetcher will be self-retained as long as a connection is pending. +// +// To keep user activity private, URLs must have an https scheme (unless the property +// allowedInsecureSchemes is set to permit the scheme.) +// +// Callbacks will be released when the fetch completes or is stopped, so there is no need +// to use weak self references in the callback blocks. +// +// Sample usage: +// +// _fetcherService = [[GTMSessionFetcherService alloc] init]; +// +// GTMSessionFetcher *myFetcher = [_fetcherService fetcherWithURLString:myURLString]; +// myFetcher.retryEnabled = YES; +// myFetcher.comment = @"First profile image"; +// +// // Optionally specify a file URL or NSData for the request body to upload. +// myFetcher.bodyData = [postString dataUsingEncoding:NSUTF8StringEncoding]; +// +// [myFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { +// if (error != nil) { +// // Server status code or network error. +// // +// // If the domain is kGTMSessionFetcherStatusDomain then the error code +// // is a failure status from the server. +// } else { +// // Fetch succeeded. +// } +// }]; +// +// There is also a beginFetch call that takes a pointer and selector for the completion handler; +// a pointer and selector is a better style when the callback is a substantial, separate method. +// +// NOTE: Fetches may retrieve data from the server even though the server +// returned an error, so the criteria for success is a non-nil error. +// The completion handler is called when the server status is >= 300 with an NSError +// having domain kGTMSessionFetcherStatusDomain and code set to the server status. +// +// Status codes are at +// +// +// Background session support: +// +// Out-of-process uploads and downloads may be created by setting the fetcher's +// useBackgroundSession property. Data to be uploaded should be provided via +// the uploadFileURL property; the download destination should be specified with +// the destinationFileURL. NOTE: Background upload files should be in a location +// that will be valid even after the device is restarted, so the file should not +// be uploaded from a system temporary or cache directory. +// +// Background session transfers are slower, and should typically be used only +// for very large downloads or uploads (hundreds of megabytes). +// +// When background sessions are used in iOS apps, the application delegate must +// pass through the parameters from UIApplicationDelegate's +// application:handleEventsForBackgroundURLSession:completionHandler: to the +// fetcher class. +// +// When the application has been relaunched, it may also create a new fetcher +// instance to handle completion of the transfers. +// +// - (void)application:(UIApplication *)application +// handleEventsForBackgroundURLSession:(NSString *)identifier +// completionHandler:(void (^)())completionHandler { +// // Application was re-launched on completing an out-of-process download. +// +// // Pass the URLSession info related to this re-launch to the fetcher class. +// [GTMSessionFetcher application:application +// handleEventsForBackgroundURLSession:identifier +// completionHandler:completionHandler]; +// +// // Get a fetcher related to this re-launch and re-hook up a completionHandler to it. +// GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithSessionIdentifier:identifier]; +// NSURL *destinationFileURL = fetcher.destinationFileURL; +// fetcher.completionHandler = ^(NSData *data, NSError *error) { +// [self downloadCompletedToFile:destinationFileURL error:error]; +// }; +// } +// +// +// Threading and queue support: +// +// Networking always happens on a background thread; there is no advantage to +// changing thread or queue to create or start a fetcher. +// +// Callbacks are run on the main thread; alternatively, the app may set the +// fetcher's callbackQueue to a dispatch queue. +// +// Once the fetcher's beginFetch method has been called, the fetcher's methods and +// properties may be accessed from any thread. +// +// Downloading to disk: +// +// To have downloaded data saved directly to disk, specify a file URL for the +// destinationFileURL property. +// +// HTTP methods and headers: +// +// Alternative HTTP methods, like PUT, and custom headers can be specified by +// creating the fetcher with an appropriate NSMutableURLRequest. +// +// +// Caching: +// +// The fetcher avoids caching. That is best for API requests, but may hurt +// repeat fetches of static data. Apps may enable a persistent disk cache by +// customizing the config: +// +// fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, +// NSURLSessionConfiguration *config) { +// config.URLCache = [NSURLCache sharedURLCache]; +// }; +// +// Or use the standard system config to share cookie storage with web views +// and to enable disk caching: +// +// fetcher.configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +// +// +// Cookies: +// +// There are three supported mechanisms for remembering cookies between fetches. +// +// By default, a standalone GTMSessionFetcher uses a mutable array held +// statically to track cookies for all instantiated fetchers. This avoids +// cookies being set by servers for the application from interfering with +// Safari and WebKit cookie settings, and vice versa. +// The fetcher cookies are lost when the application quits. +// +// To rely instead on WebKit's global NSHTTPCookieStorage, set the fetcher's +// cookieStorage property: +// myFetcher.cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; +// +// To share cookies with other apps, use the method introduced in iOS 9/OS X 10.11: +// myFetcher.cookieStorage = +// [NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:kMyCompanyContainedID]; +// +// To ignore existing cookies and only have cookies related to the single fetch +// be applied, make a temporary cookie storage object: +// myFetcher.cookieStorage = [[GTMSessionCookieStorage alloc] init]; +// +// Note: cookies set while following redirects will be sent to the server, as +// the redirects are followed by the fetcher. +// +// To completely disable cookies, similar to setting cookieStorageMethod to +// kGTMHTTPFetcherCookieStorageMethodNone, adjust the session configuration +// appropriately in the fetcher or fetcher service: +// fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, +// NSURLSessionConfiguration *config) { +// config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; +// config.HTTPShouldSetCookies = NO; +// }; +// +// If the fetcher is created from a GTMSessionFetcherService object +// then the cookie storage mechanism is set to use the cookie storage in the +// service object rather than the static storage. Disabling cookies in the +// session configuration set on a service object will disable cookies for all +// fetchers created from that GTMSessionFetcherService object, since the session +// configuration is propagated to the fetcher. +// +// +// Monitoring data transfers. +// +// The fetcher supports a variety of properties for progress monitoring +// progress with callback blocks. +// GTMSessionFetcherSendProgressBlock sendProgressBlock +// GTMSessionFetcherReceivedProgressBlock receivedProgressBlock +// GTMSessionFetcherDownloadProgressBlock downloadProgressBlock +// +// If supplied by the server, the anticipated total download size is available +// as [[myFetcher response] expectedContentLength] (and may be -1 for unknown +// download sizes.) +// +// +// Automatic retrying of fetches +// +// The fetcher can optionally create a timer and reattempt certain kinds of +// fetch failures (status codes 408, request timeout; 502, gateway failure; +// 503, service unavailable; 504, gateway timeout; networking errors +// NSURLErrorTimedOut and NSURLErrorNetworkConnectionLost.) The user may +// set a retry selector to customize the type of errors which will be retried. +// +// Retries are done in an exponential-backoff fashion (that is, after 1 second, +// 2, 4, 8, and so on.) +// +// Enabling automatic retries looks like this: +// myFetcher.retryEnabled = YES; +// +// With retries enabled, the completion callbacks are called only +// when no more retries will be attempted. Calling the fetcher's stopFetching +// method will terminate the retry timer, without the finished or failure +// selectors being invoked. +// +// Optionally, the client may set the maximum retry interval: +// myFetcher.maxRetryInterval = 60.0; // in seconds; default is 60 seconds +// // for downloads, 600 for uploads +// +// Servers should never send a 400 or 500 status for errors that are retryable +// by clients, as those values indicate permanent failures. In nearly all +// cases, the default standard retry behavior is correct for clients, and no +// custom client retry behavior is needed or appropriate. Servers that send +// non-retryable status codes and expect the client to retry the request are +// faulty. +// +// Still, the client may provide a block to determine if a status code or other +// error should be retried. The block returns YES to set the retry timer or NO +// to fail without additional fetch attempts. +// +// The retry method may return the |suggestedWillRetry| argument to get the +// default retry behavior. Server status codes are present in the +// error argument, and have the domain kGTMSessionFetcherStatusDomain. The +// user's method may look something like this: +// +// myFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error, +// GTMSessionFetcherRetryResponse response) { +// // Perhaps examine error.domain and error.code, or fetcher.retryCount +// // +// // Respond with YES to start the retry timer, NO to proceed to the failure +// // callback, or suggestedWillRetry to get default behavior for the +// // current error domain and code values. +// response(suggestedWillRetry); +// }; + + +#import + +#if TARGET_OS_IPHONE +#import +#endif +#if TARGET_OS_WATCH +#import +#endif + +// By default it is stripped from non DEBUG builds. Developers can override +// this in their project settings. +#ifndef STRIP_GTM_FETCH_LOGGING + #if !DEBUG + #define STRIP_GTM_FETCH_LOGGING 1 + #else + #define STRIP_GTM_FETCH_LOGGING 0 + #endif +#endif + +// Logs in debug builds. +#ifndef GTMSESSION_LOG_DEBUG + #if DEBUG + #define GTMSESSION_LOG_DEBUG(...) NSLog(__VA_ARGS__) + #else + #define GTMSESSION_LOG_DEBUG(...) do { } while (0) + #endif +#endif + +// Asserts in debug builds (or logs in debug builds if GTMSESSION_ASSERT_AS_LOG +// or NS_BLOCK_ASSERTIONS are defined.) +#ifndef GTMSESSION_ASSERT_DEBUG + #if DEBUG && !defined(NS_BLOCK_ASSERTIONS) && !GTMSESSION_ASSERT_AS_LOG + #undef GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_AS_LOG 1 + #endif + + #if DEBUG && !GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_DEBUG(...) NSAssert(__VA_ARGS__) + #elif DEBUG + #define GTMSESSION_ASSERT_DEBUG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } + #else + #define GTMSESSION_ASSERT_DEBUG(pred, ...) do { } while (0) + #endif +#endif + +// Asserts in debug builds, logs in release builds (or logs in debug builds if +// GTMSESSION_ASSERT_AS_LOG is defined.) +#ifndef GTMSESSION_ASSERT_DEBUG_OR_LOG + #if DEBUG && !GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_DEBUG_OR_LOG(...) NSAssert(__VA_ARGS__) + #else + #define GTMSESSION_ASSERT_DEBUG_OR_LOG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } + #endif +#endif + +// Macro useful for examining messages from NSURLSession during debugging. +#if 0 +#define GTM_LOG_SESSION_DELEGATE(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) +#else +#define GTM_LOG_SESSION_DELEGATE(...) +#endif + +#ifndef GTM_NULLABLE + #if __has_feature(nullability) // Available starting in Xcode 6.3 + #define GTM_NULLABLE_TYPE __nullable + #define GTM_NONNULL_TYPE __nonnull + #define GTM_NULLABLE nullable + #define GTM_NONNULL_DECL nonnull // GTM_NONNULL is used by GTMDefines.h + #define GTM_NULL_RESETTABLE null_resettable + + #define GTM_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN + #define GTM_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END + #else + #define GTM_NULLABLE_TYPE + #define GTM_NONNULL_TYPE + #define GTM_NULLABLE + #define GTM_NONNULL_DECL + #define GTM_NULL_RESETTABLE + #define GTM_ASSUME_NONNULL_BEGIN + #define GTM_ASSUME_NONNULL_END + #endif // __has_feature(nullability) +#endif // GTM_NULLABLE + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0)) +#define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) __attribute__((deprecated("" _MSG))) +#else +#define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) +#endif + +#ifndef GTM_DECLARE_GENERICS + #if __has_feature(objc_generics) + #define GTM_DECLARE_GENERICS 1 + #else + #define GTM_DECLARE_GENERICS 0 + #endif +#endif + +#ifndef GTM_NSArrayOf + #if GTM_DECLARE_GENERICS + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #else + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #endif // __has_feature(objc_generics) +#endif // GTM_NSArrayOf + +// For iOS, the fetcher can declare itself a background task to allow fetches +// to finish when the app leaves the foreground. +// +// (This is unrelated to providing a background configuration, which allows +// out-of-process uploads and downloads.) +// +// To disallow use of background tasks during fetches, the target should define +// GTM_BACKGROUND_TASK_FETCHING to 0, or alternatively may set the +// skipBackgroundTask property to YES. +#if TARGET_OS_IPHONE && !TARGET_OS_WATCH && !defined(GTM_BACKGROUND_TASK_FETCHING) + #define GTM_BACKGROUND_TASK_FETCHING 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) + #ifndef GTM_USE_SESSION_FETCHER + #define GTM_USE_SESSION_FETCHER 1 + #endif +#endif + +#if !defined(GTMBridgeFetcher) + // These bridge macros should be identical in GTMHTTPFetcher.h and GTMSessionFetcher.h + #if GTM_USE_SESSION_FETCHER + // Macros to new fetcher class. + #define GTMBridgeFetcher GTMSessionFetcher + #define GTMBridgeFetcherService GTMSessionFetcherService + #define GTMBridgeFetcherServiceProtocol GTMSessionFetcherServiceProtocol + #define GTMBridgeAssertValidSelector GTMSessionFetcherAssertValidSelector + #define GTMBridgeCookieStorage GTMSessionCookieStorage + #define GTMBridgeCleanedUserAgentString GTMFetcherCleanedUserAgentString + #define GTMBridgeSystemVersionString GTMFetcherSystemVersionString + #define GTMBridgeApplicationIdentifier GTMFetcherApplicationIdentifier + #define kGTMBridgeFetcherStatusDomain kGTMSessionFetcherStatusDomain + #define kGTMBridgeFetcherStatusBadRequest GTMSessionFetcherStatusBadRequest + #else + // Macros to old fetcher class. + #define GTMBridgeFetcher GTMHTTPFetcher + #define GTMBridgeFetcherService GTMHTTPFetcherService + #define GTMBridgeFetcherServiceProtocol GTMHTTPFetcherServiceProtocol + #define GTMBridgeAssertValidSelector GTMAssertSelectorNilOrImplementedWithArgs + #define GTMBridgeCookieStorage GTMCookieStorage + #define GTMBridgeCleanedUserAgentString GTMCleanedUserAgentString + #define GTMBridgeSystemVersionString GTMSystemVersionString + #define GTMBridgeApplicationIdentifier GTMApplicationIdentifier + #define kGTMBridgeFetcherStatusDomain kGTMHTTPFetcherStatusDomain + #define kGTMBridgeFetcherStatusBadRequest kGTMHTTPFetcherStatusBadRequest + #endif // GTM_USE_SESSION_FETCHER +#endif + +GTM_ASSUME_NONNULL_BEGIN + +// Notifications +// +// Fetch started and stopped, and fetch retry delay started and stopped. +extern NSString *const kGTMSessionFetcherStartedNotification; +extern NSString *const kGTMSessionFetcherStoppedNotification; +extern NSString *const kGTMSessionFetcherRetryDelayStartedNotification; +extern NSString *const kGTMSessionFetcherRetryDelayStoppedNotification; + +// Completion handler notification. This is intended for use by code capturing +// and replaying fetch requests and results for testing. For fetches where +// destinationFileURL or accumulateDataBlock is set for the fetcher, the data +// will be nil for successful fetches. +// +// This notification is posted on the main thread. +extern NSString *const kGTMSessionFetcherCompletionInvokedNotification; +extern NSString *const kGTMSessionFetcherCompletionDataKey; +extern NSString *const kGTMSessionFetcherCompletionErrorKey; + +// Constants for NSErrors created by the fetcher (excluding server status errors, +// and error objects originating in the OS.) +extern NSString *const kGTMSessionFetcherErrorDomain; + +// The fetcher turns server error status values (3XX, 4XX, 5XX) into NSErrors +// with domain kGTMSessionFetcherStatusDomain. +// +// Any server response body data accompanying the status error is added to the +// userInfo dictionary with key kGTMSessionFetcherStatusDataKey. +extern NSString *const kGTMSessionFetcherStatusDomain; +extern NSString *const kGTMSessionFetcherStatusDataKey; +extern NSString *const kGTMSessionFetcherStatusDataContentTypeKey; + +// When a fetch fails with an error, these keys are included in the error userInfo +// dictionary if retries were attempted. +extern NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey; +extern NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey; + +// Background session support requires access to NSUserDefaults. +// If [NSUserDefaults standardUserDefaults] doesn't yield the correct NSUserDefaults for your usage, +// ie for an App Extension, then implement this class/method to return the correct NSUserDefaults. +// https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6 +@interface GTMSessionFetcherUserDefaultsFactory : NSObject + ++ (NSUserDefaults *)fetcherUserDefaults; + +@end + +#ifdef __cplusplus +} +#endif + +typedef NS_ENUM(NSInteger, GTMSessionFetcherError) { + GTMSessionFetcherErrorDownloadFailed = -1, + GTMSessionFetcherErrorUploadChunkUnavailable = -2, + GTMSessionFetcherErrorBackgroundExpiration = -3, + GTMSessionFetcherErrorBackgroundFetchFailed = -4, + GTMSessionFetcherErrorInsecureRequest = -5, + GTMSessionFetcherErrorTaskCreationFailed = -6, +}; + +typedef NS_ENUM(NSInteger, GTMSessionFetcherStatus) { + // Standard http status codes. + GTMSessionFetcherStatusNotModified = 304, + GTMSessionFetcherStatusBadRequest = 400, + GTMSessionFetcherStatusUnauthorized = 401, + GTMSessionFetcherStatusForbidden = 403, + GTMSessionFetcherStatusPreconditionFailed = 412 +}; + +#ifdef __cplusplus +extern "C" { +#endif + +@class GTMSessionCookieStorage; +@class GTMSessionFetcher; + +// The configuration block is for modifying the NSURLSessionConfiguration only. +// DO NOT change any fetcher properties in the configuration block. +typedef void (^GTMSessionFetcherConfigurationBlock)(GTMSessionFetcher *fetcher, + NSURLSessionConfiguration *configuration); +typedef void (^GTMSessionFetcherSystemCompletionHandler)(void); +typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); +typedef void (^GTMSessionFetcherBodyStreamProviderResponse)(NSInputStream *bodyStream); +typedef void (^GTMSessionFetcherBodyStreamProvider)(GTMSessionFetcherBodyStreamProviderResponse response); +typedef void (^GTMSessionFetcherDidReceiveResponseDispositionBlock)(NSURLSessionResponseDisposition disposition); +typedef void (^GTMSessionFetcherDidReceiveResponseBlock)(NSURLResponse *response, + GTMSessionFetcherDidReceiveResponseDispositionBlock dispositionBlock); +typedef void (^GTMSessionFetcherChallengeDispositionBlock)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential); +typedef void (^GTMSessionFetcherChallengeBlock)(GTMSessionFetcher *fetcher, + NSURLAuthenticationChallenge *challenge, + GTMSessionFetcherChallengeDispositionBlock dispositionBlock); +typedef void (^GTMSessionFetcherWillRedirectResponse)(NSURLRequest * GTM_NULLABLE_TYPE redirectedRequest); +typedef void (^GTMSessionFetcherWillRedirectBlock)(NSHTTPURLResponse *redirectResponse, + NSURLRequest *redirectRequest, + GTMSessionFetcherWillRedirectResponse response); +typedef void (^GTMSessionFetcherAccumulateDataBlock)(NSData * GTM_NULLABLE_TYPE buffer); +typedef void (^GTMSessionFetcherSimulateByteTransferBlock)(NSData * GTM_NULLABLE_TYPE buffer, + int64_t bytesWritten, + int64_t totalBytesWritten, + int64_t totalBytesExpectedToWrite); +typedef void (^GTMSessionFetcherReceivedProgressBlock)(int64_t bytesWritten, + int64_t totalBytesWritten); +typedef void (^GTMSessionFetcherDownloadProgressBlock)(int64_t bytesWritten, + int64_t totalBytesWritten, + int64_t totalBytesExpectedToWrite); +typedef void (^GTMSessionFetcherSendProgressBlock)(int64_t bytesSent, + int64_t totalBytesSent, + int64_t totalBytesExpectedToSend); +typedef void (^GTMSessionFetcherWillCacheURLResponseResponse)(NSCachedURLResponse * GTM_NULLABLE_TYPE cachedResponse); +typedef void (^GTMSessionFetcherWillCacheURLResponseBlock)(NSCachedURLResponse *proposedResponse, + GTMSessionFetcherWillCacheURLResponseResponse responseBlock); +typedef void (^GTMSessionFetcherRetryResponse)(BOOL shouldRetry); +typedef void (^GTMSessionFetcherRetryBlock)(BOOL suggestedWillRetry, + NSError * GTM_NULLABLE_TYPE error, + GTMSessionFetcherRetryResponse response); + +typedef void (^GTMSessionFetcherTestResponse)(NSHTTPURLResponse * GTM_NULLABLE_TYPE response, + NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); +typedef void (^GTMSessionFetcherTestBlock)(GTMSessionFetcher *fetcherToTest, + GTMSessionFetcherTestResponse testResponse); + +void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...); + +// Utility functions for applications self-identifying to servers via a +// user-agent header + +// The "standard" user agent includes the application identifier, taken from the bundle, +// followed by a space and the system version string. Pass nil to use +mainBundle as the source +// of the bundle identifier. +// +// Applications may use this as a starting point for their own user agent strings, perhaps +// with additional sections appended. Use GTMFetcherCleanedUserAgentString() below to +// clean up any string being added to the user agent. +NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle); + +// Make a generic name and version for the current application, like +// com.example.MyApp/1.2.3 relying on the bundle identifier and the +// CFBundleShortVersionString or CFBundleVersion. +// +// The bundle ID may be overridden as the base identifier string by +// adding to the bundle's Info.plist a "GTMUserAgentID" key. +// +// If no bundle ID or override is available, the process name preceded +// by "proc_" is used. +NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle); + +// Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1" +NSString *GTMFetcherSystemVersionString(void); + +// Make a parseable user-agent identifier from the given string, replacing whitespace +// and commas with underscores, and removing other characters that may interfere +// with parsing of the full user-agent string. +// +// For example, @"[My App]" would become @"My_App" +NSString *GTMFetcherCleanedUserAgentString(NSString *str); + +// Grab the data from an input stream. Since streams cannot be assumed to be rewindable, +// this may be destructive; the caller can try to rewind the stream (by setting the +// NSStreamFileCurrentOffsetKey property) or can just use the NSData to make a new +// NSInputStream. This function is intended to facilitate testing rather than be used in +// production. +// +// This function operates synchronously on the current thread. Depending on how the +// input stream is implemented, it may be appropriate to dispatch to a different +// queue before calling this function. +// +// Failure is indicated by a returned data value of nil. +NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError); + +#ifdef __cplusplus +} // extern "C" +#endif + + +#if !GTM_USE_SESSION_FETCHER +@protocol GTMHTTPFetcherServiceProtocol; +#endif + +// This protocol allows abstract references to the fetcher service, primarily for +// fetchers (which may be compiled without the fetcher service class present.) +// +// Apps should not need to use this protocol. +@protocol GTMSessionFetcherServiceProtocol +// This protocol allows us to call into the service without requiring +// GTMSessionFetcherService sources in this project + +@property(atomic, strong) dispatch_queue_t callbackQueue; + +- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher; + +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; + +@property(atomic, assign) BOOL reuseSession; +- (GTM_NULLABLE NSURLSession *)session; +- (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; +- (GTM_NULLABLE id)sessionDelegate; +- (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; + +// Methods for compatibility with the old GTMHTTPFetcher. +@property(readonly, strong, GTM_NULLABLE) NSOperationQueue *delegateQueue; + +@end // @protocol GTMSessionFetcherServiceProtocol + +#ifndef GTM_FETCHER_AUTHORIZATION_PROTOCOL +#define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1 +@protocol GTMFetcherAuthorizationProtocol +@required +// This protocol allows us to call the authorizer without requiring its sources +// in this project. +- (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request + delegate:(id)delegate + didFinishSelector:(SEL)sel; + +- (void)stopAuthorization; + +- (void)stopAuthorizationForRequest:(NSURLRequest *)request; + +- (BOOL)isAuthorizingRequest:(NSURLRequest *)request; + +- (BOOL)isAuthorizedRequest:(NSURLRequest *)request; + +@property(strong, readonly, GTM_NULLABLE) NSString *userEmail; + +@optional + +// Indicate if authorization may be attempted. Even if this succeeds, +// authorization may fail if the user's permissions have been revoked. +@property(readonly) BOOL canAuthorize; + +// For development only, allow authorization of non-SSL requests, allowing +// transmission of the bearer token unencrypted. +@property(assign) BOOL shouldAuthorizeAllRequests; + +- (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request + completionHandler:(void (^)(NSError * GTM_NULLABLE_TYPE error))handler; + +#if GTM_USE_SESSION_FETCHER +@property (weak, GTM_NULLABLE) id fetcherService; +#else +@property (weak, GTM_NULLABLE) id fetcherService; +#endif + +- (BOOL)primeForRefresh; + +@end +#endif // GTM_FETCHER_AUTHORIZATION_PROTOCOL + +#if GTM_BACKGROUND_TASK_FETCHING +// A protocol for an alternative target for messages from GTMSessionFetcher to UIApplication. +// Set the target using +[GTMSessionFetcher setSubstituteUIApplication:] +@protocol GTMUIApplicationProtocol +- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName + expirationHandler:(void(^ __nullable)(void))handler; +- (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier; +@end +#endif + +#pragma mark - + +// GTMSessionFetcher objects are used for async retrieval of an http get or post +// +// See additional comments at the beginning of this file +@interface GTMSessionFetcher : NSObject + +// Create a fetcher +// +// fetcherWithRequest will return an autoreleased fetcher, but if +// the connection is successfully created, the connection should retain the +// fetcher for the life of the connection as well. So the caller doesn't have +// to retain the fetcher explicitly unless they want to be able to cancel it. ++ (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request; + +// Convenience methods that make a request, like +fetcherWithRequest ++ (instancetype)fetcherWithURL:(NSURL *)requestURL; ++ (instancetype)fetcherWithURLString:(NSString *)requestURLString; + +// Methods for creating fetchers to continue previous fetches. ++ (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData; ++ (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier; + +// Returns an array of currently active fetchers for background sessions, +// both restarted and newly created ones. ++ (GTM_NSArrayOf(GTMSessionFetcher *) *)fetchersForBackgroundSessions; + +// Designated initializer. +// +// Applications should create fetchers with a "fetcherWith..." method on a fetcher +// service or a class method, not with this initializer. +// +// The configuration should typically be nil. Applications needing to customize +// the configuration may do so by setting the configurationBlock property. +- (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request + configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration; + +// The fetcher's request. This may not be set after beginFetch has been invoked. The request +// may change due to redirects. +@property(strong, GTM_NULLABLE) NSURLRequest *request; + +// Set a header field value on the request. Header field value changes will not +// affect a fetch after the fetch has begun. +- (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field; + +// Data used for resuming a download task. +@property(atomic, readonly, GTM_NULLABLE) NSData *downloadResumeData; + +// The configuration; this must be set before the fetch begins. If no configuration is +// set or inherited from the fetcher service, then the fetcher uses an ephemeral config. +// +// NOTE: This property should typically be nil. Applications needing to customize +// the configuration should do so by setting the configurationBlock property. +// That allows the fetcher to pick an appropriate base configuration, with the +// application setting only the configuration properties it needs to customize. +@property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; + +// A block the client may use to customize the configuration used to create the session. +// +// This is called synchronously, either on the thread that begins the fetch or, during a retry, +// on the main thread. The configuration block may be called repeatedly if multiple fetchers are +// created. +// +// The configuration block is for modifying the NSURLSessionConfiguration only. +// DO NOT change any fetcher properties in the configuration block. Fetcher properties +// may be set in the fetcher service prior to fetcher creation, or on the fetcher prior +// to invoking beginFetch. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; + +// A session is created as needed by the fetcher. A fetcher service object +// may maintain sessions for multiple fetches to the same host. +@property(atomic, strong, GTM_NULLABLE) NSURLSession *session; + +// The task in flight. +@property(atomic, readonly, GTM_NULLABLE) NSURLSessionTask *sessionTask; + +// The background session identifier. +@property(atomic, readonly, GTM_NULLABLE) NSString *sessionIdentifier; + +// Indicates a fetcher created to finish a background session task. +@property(atomic, readonly) BOOL wasCreatedFromBackgroundSession; + +// Additional user-supplied data to encode into the session identifier. Since session identifier +// length limits are unspecified, this should be kept small. Key names beginning with an underscore +// are reserved for use by the fetcher. +@property(atomic, strong, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *sessionUserInfo; + +// The human-readable description to be assigned to the task. +@property(atomic, copy, GTM_NULLABLE) NSString *taskDescription; + +// The priority assigned to the task, if any. Use NSURLSessionTaskPriorityLow, +// NSURLSessionTaskPriorityDefault, or NSURLSessionTaskPriorityHigh. +@property(atomic, assign) float taskPriority; + +// The fetcher encodes information used to resume a session in the session identifier. +// This method, intended for internal use returns the encoded information. The sessionUserInfo +// dictionary is stored as identifier metadata. +- (GTM_NULLABLE GTM_NSDictionaryOf(NSString *, NSString *) *)sessionIdentifierMetadata; + +#if TARGET_OS_IPHONE && !TARGET_OS_WATCH +// The app should pass to this method the completion handler passed in the app delegate method +// application:handleEventsForBackgroundURLSession:completionHandler: ++ (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler; +#endif + +// Indicate that a newly created session should be a background session. +// A new session identifier will be created by the fetcher. +// +// Warning: The only thing background sessions are for is rare download +// of huge, batched files of data. And even just for those, there's a lot +// of pain and hackery needed to get transfers to actually happen reliably +// with background sessions. +// +// Don't try to upload or download in many background sessions, since the system +// will impose an exponentially increasing time penalty to prevent the app from +// getting too much background execution time. +// +// References: +// +// "Moving to Fewer, Larger Transfers" +// https://forums.developer.apple.com/thread/14853 +// +// "NSURLSession’s Resume Rate Limiter" +// https://forums.developer.apple.com/thread/14854 +// +// "Background Session Task state persistence" +// https://forums.developer.apple.com/thread/11554 +// +@property(assign) BOOL useBackgroundSession; + +// Indicates if the fetcher was started using a background session. +@property(atomic, readonly, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; + +// Indicates if uploads should use an upload task. This is always set for file or stream-provider +// bodies, but may be set explicitly for NSData bodies. +@property(atomic, assign) BOOL useUploadTask; + +// Indicates that the fetcher is using a session that may be shared with other fetchers. +@property(atomic, readonly) BOOL canShareSession; + +// By default, the fetcher allows only secure (https) schemes unless this +// property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. +// +// For example, during debugging when fetching from a development server that lacks SSL support, +// this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files, +// this may be set to @[ @"file" ]. +// +// This should be left as nil for release builds to avoid creating the opportunity for +// leaking private user behavior and data. If a server is providing insecure URLs +// for fetching by the client app, report the problem as server security & privacy bug. +// +// For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when +// the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. +@property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; + +// By default, the fetcher prohibits localhost requests unless this property is set, +// or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. +// +// For localhost requests, the URL scheme is not checked when this property is set. +// +// For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when +// the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. +@property(atomic, assign) BOOL allowLocalhostRequest; + +// By default, the fetcher requires valid server certs. This may be bypassed +// temporarily for development against a test server with an invalid cert. +@property(atomic, assign) BOOL allowInvalidServerCertificates; + +// Cookie storage object for this fetcher. If nil, the fetcher will use a static cookie +// storage instance shared among fetchers. If this fetcher was created by a fetcher service +// object, it will be set to use the service object's cookie storage. See Cookies section above for +// the full discussion. +// +// Because as of Jan 2014 standalone instances of NSHTTPCookieStorage do not actually +// store any cookies (Radar 15735276) we use our own subclass, GTMSessionCookieStorage, +// to hold cookies in memory. +@property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; + +// Setting the credential is optional; it is used if the connection receives +// an authentication challenge. +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; + +// Setting the proxy credential is optional; it is used if the connection +// receives an authentication challenge from a proxy. +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *proxyCredential; + +// If body data, body file URL, or body stream provider is not set, then a GET request +// method is assumed. +@property(atomic, strong, GTM_NULLABLE) NSData *bodyData; + +// File to use as the request body. This forces use of an upload task. +@property(atomic, strong, GTM_NULLABLE) NSURL *bodyFileURL; + +// Length of body to send, expected or actual. +@property(atomic, readonly) int64_t bodyLength; + +// The body stream provider may be called repeatedly to provide a body. +// Setting a body stream provider forces use of an upload task. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherBodyStreamProvider bodyStreamProvider; + +// Object to add authorization to the request, if needed. +// +// This may not be changed once beginFetch has been invoked. +@property(atomic, strong, GTM_NULLABLE) id authorizer; + +// The service object that created and monitors this fetcher, if any. +@property(atomic, strong) id service; + +// The host, if any, used to classify this fetcher in the fetcher service. +@property(atomic, copy, GTM_NULLABLE) NSString *serviceHost; + +// The priority, if any, used for starting fetchers in the fetcher service. +// +// Lower values are higher priority; the default is 0, and values may +// be negative or positive. This priority affects only the start order of +// fetchers that are being delayed by a fetcher service when the running fetchers +// exceeds the service's maxRunningFetchersPerHost. A priority of NSIntegerMin will +// exempt this fetcher from delay. +@property(atomic, assign) NSInteger servicePriority; + +// The delegate's optional didReceiveResponse block may be used to inspect or alter +// the session task response. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock; + +// The delegate's optional challenge block may be used to inspect or alter +// the session task challenge. +// +// If this block is not set, the fetcher's default behavior for the NSURLSessionTask +// didReceiveChallenge: delegate method is to use the fetcher's respondToChallenge: method +// which relies on the fetcher's credential and proxyCredential properties. +// +// Warning: This may be called repeatedly if the challenge fails. Check +// challenge.previousFailureCount to identify repeated invocations. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; + +// The delegate's optional willRedirect block may be used to inspect or alter +// the redirection. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillRedirectBlock willRedirectBlock; + +// The optional send progress block reports body bytes uploaded. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherSendProgressBlock sendProgressBlock; + +// The optional accumulate block may be set by clients wishing to accumulate data +// themselves rather than let the fetcher append each buffer to an NSData. +// +// When this is called with nil data (such as on redirect) the client +// should empty its accumulation buffer. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherAccumulateDataBlock accumulateDataBlock; + +// The optional received progress block may be used to monitor data +// received from a data task. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherReceivedProgressBlock receivedProgressBlock; + +// The delegate's optional downloadProgress block may be used to monitor download +// progress in writing to disk. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDownloadProgressBlock downloadProgressBlock; + +// The delegate's optional willCacheURLResponse block may be used to alter the cached +// NSURLResponse. The user may prevent caching by passing nil to the block's response. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock; + +// Enable retrying; see comments at the top of this file. Setting +// retryEnabled=YES resets the min and max retry intervals. +@property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; + +// Retry block is optional for retries. +// +// If present, this block should call the response block with YES to cause a retry or NO to end the +// fetch. +// See comments at the top of this file. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; + +// Retry intervals must be strictly less than maxRetryInterval, else +// they will be limited to maxRetryInterval and no further retries will +// be attempted. Setting maxRetryInterval to 0.0 will reset it to the +// default value, 60 seconds for downloads and 600 seconds for uploads. +@property(atomic, assign) NSTimeInterval maxRetryInterval; + +// Starting retry interval. Setting minRetryInterval to 0.0 will reset it +// to a random value between 1.0 and 2.0 seconds. Clients should normally not +// set this except for unit testing. +@property(atomic, assign) NSTimeInterval minRetryInterval; + +// Multiplier used to increase the interval between retries, typically 2.0. +// Clients should not need to set this. +@property(atomic, assign) double retryFactor; + +// Number of retries attempted. +@property(atomic, readonly) NSUInteger retryCount; + +// Interval delay to precede next retry. +@property(atomic, readonly) NSTimeInterval nextRetryInterval; + +#if GTM_BACKGROUND_TASK_FETCHING +// Skip use of a UIBackgroundTask, thus requiring fetches to complete when the app is in the +// foreground. +// +// Targets should define GTM_BACKGROUND_TASK_FETCHING to 0 to avoid use of a UIBackgroundTask +// on iOS to allow fetches to complete in the background. This property is available when +// it's not practical to set the preprocessor define. +@property(atomic, assign) BOOL skipBackgroundTask; +#endif // GTM_BACKGROUND_TASK_FETCHING + +// Begin fetching the request +// +// The delegate may optionally implement the callback or pass nil for the selector or handler. +// +// The delegate and all callback blocks are retained between the beginFetch call until after the +// finish callback, or until the fetch is stopped. +// +// An error is passed to the callback for server statuses 300 or +// higher, with the status stored as the error object's code. +// +// finishedSEL has a signature like: +// - (void)fetcher:(GTMSessionFetcher *)fetcher +// finishedWithData:(NSData *)data +// error:(NSError *)error; +// +// If the application has specified a destinationFileURL or an accumulateDataBlock +// for the fetcher, the data parameter passed to the callback will be nil. + +- (void)beginFetchWithDelegate:(GTM_NULLABLE id)delegate + didFinishSelector:(GTM_NULLABLE SEL)finishedSEL; + +- (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler; + +// Returns YES if this fetcher is in the process of fetching a URL. +@property(atomic, readonly, getter=isFetching) BOOL fetching; + +// Cancel the fetch of the request that's currently in progress. The completion handler +// will not be called. +- (void)stopFetching; + +// A block to be called when the fetch completes. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherCompletionHandler completionHandler; + +// A block to be called if download resume data becomes available. +@property(atomic, strong, GTM_NULLABLE) void (^resumeDataBlock)(NSData *); + +// Return the status code from the server response. +@property(atomic, readonly) NSInteger statusCode; + +// Return the http headers from the response. +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *responseHeaders; + +// The response, once it's been received. +@property(atomic, strong, readonly, GTM_NULLABLE) NSURLResponse *response; + +// Bytes downloaded so far. +@property(atomic, readonly) int64_t downloadedLength; + +// Buffer of currently-downloaded data, if available. +@property(atomic, readonly, strong, GTM_NULLABLE) NSData *downloadedData; + +// Local path to which the downloaded file will be moved. +// +// If a file already exists at the path, it will be overwritten. +// Will create the enclosing folders if they are not present. +@property(atomic, strong, GTM_NULLABLE) NSURL *destinationFileURL; + +// The time this fetcher originally began fetching. This is useful as a time +// barrier for ignoring irrelevant fetch notifications or callbacks. +@property(atomic, strong, readonly, GTM_NULLABLE) NSDate *initialBeginFetchDate; + +// userData is retained solely for the convenience of the client. +@property(atomic, strong, GTM_NULLABLE) id userData; + +// Stored property values are retained solely for the convenience of the client. +@property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; + +- (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key; // Pass nil for obj to remove the property. +- (GTM_NULLABLE id)propertyForKey:(NSString *)key; + +- (void)addPropertiesFromDictionary:(GTM_NSDictionaryOf(NSString *, id) *)dict; + +// Comments are useful for logging, so are strongly recommended for each fetcher. +@property(atomic, copy, GTM_NULLABLE) NSString *comment; + +- (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2); + +// Log of request and response, if logging is enabled +@property(atomic, copy, GTM_NULLABLE) NSString *log; + +// Callbacks are run on this queue. If none is supplied, the main queue is used. +@property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; + +// The queue used internally by the session to invoke its delegate methods in the fetcher. +// +// Application callbacks are always called by the fetcher on the callbackQueue above, +// not on this queue. Apps should generally not change this queue. +// +// The default delegate queue is the main queue. +// +// This value is ignored after the session has been created, so this +// property should be set in the fetcher service rather in the fetcher as it applies +// to a shared session. +@property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; + +// Spin the run loop or sleep the thread, discarding events, until the fetch has completed. +// +// This is only for use in testing or in tools without a user interface. +// +// Note: Synchronous fetches should never be used by shipping apps; they are +// sufficient reason for rejection from the app store. +// +// Returns NO if timed out. +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds; + +// Test block is optional for testing. +// +// If present, this block will cause the fetcher to skip starting the session, and instead +// use the test block response values when calling the completion handler and delegate code. +// +// Test code can set this on the fetcher or on the fetcher service. For testing libraries +// that use a fetcher without exposing either the fetcher or the fetcher service, the global +// method setGlobalTestBlock: will set the block for all fetchers that do not have a test +// block set. +// +// The test code can pass nil for all response parameters to indicate that the fetch +// should proceed. +// +// Applications can exclude test block support by setting GTM_DISABLE_FETCHER_TEST_BLOCK. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; + ++ (void)setGlobalTestBlock:(GTM_NULLABLE GTMSessionFetcherTestBlock)block; + +// When using the testBlock, |testBlockAccumulateDataChunkCount| is the desired number of chunks to +// divide the response data into if the client has streaming enabled. The data will be divided up to +// |testBlockAccumulateDataChunkCount| chunks; however, the exact amount may vary depending on the +// size of the response data (e.g. a 1-byte response can only be divided into one chunk). +@property(atomic, readwrite) NSUInteger testBlockAccumulateDataChunkCount; + +#if GTM_BACKGROUND_TASK_FETCHING +// For testing or to override UIApplication invocations, apps may specify an alternative +// target for messages to UIApplication. ++ (void)setSubstituteUIApplication:(nullable id)substituteUIApplication; ++ (nullable id)substituteUIApplication; +#endif // GTM_BACKGROUND_TASK_FETCHING + +// Exposed for testing. ++ (GTMSessionCookieStorage *)staticCookieStorage; ++ (BOOL)appAllowsInsecureRequests; + +#if STRIP_GTM_FETCH_LOGGING +// If logging is stripped, provide a stub for the main method +// for controlling logging. ++ (void)setLoggingEnabled:(BOOL)flag; ++ (BOOL)isLoggingEnabled; + +#else + +// These methods let an application log specific body text, such as the text description of a binary +// request or response. The application should set the fetcher to defer response body logging until +// the response has been received and the log response body has been set by the app. For example: +// +// fetcher.logRequestBody = [binaryObject stringDescription]; +// fetcher.deferResponseBodyLogging = YES; +// [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { +// if (error == nil) { +// fetcher.logResponseBody = [[[MyThing alloc] initWithData:data] stringDescription]; +// } +// fetcher.deferResponseBodyLogging = NO; +// }]; + +@property(atomic, copy, GTM_NULLABLE) NSString *logRequestBody; +@property(atomic, assign) BOOL deferResponseBodyLogging; +@property(atomic, copy, GTM_NULLABLE) NSString *logResponseBody; + +// Internal logging support. +@property(atomic, readonly) NSData *loggedStreamData; +@property(atomic, assign) BOOL hasLoggedError; +@property(atomic, strong, GTM_NULLABLE) NSURL *redirectedFromURL; +- (void)appendLoggedStreamData:(NSData *)dataToAdd; +- (void)clearLoggedStreamData; + +#endif // STRIP_GTM_FETCH_LOGGING + +@end + +@interface GTMSessionFetcher (BackwardsCompatibilityOnly) +// Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. +// This method is just for compatibility with the old GTMHTTPFetcher class. +- (void)setCookieStorageMethod:(NSInteger)method; +@end + +// Until we can just instantiate NSHTTPCookieStorage for local use, we'll +// implement all the public methods ourselves. This stores cookies only in +// memory. Additional methods are provided for testing. +// +// iOS 9/OS X 10.11 added +[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:] +// which may also be used to create cookie storage. +@interface GTMSessionCookieStorage : NSHTTPCookieStorage + +// Add the array off cookies to the storage, replacing duplicates. +// Also removes expired cookies from the storage. +- (void)setCookies:(GTM_NULLABLE GTM_NSArrayOf(NSHTTPCookie *) *)cookies; + +- (void)removeAllCookies; + +@end + +// Macros to monitor synchronization blocks in debug builds. +// These report problems using GTMSessionCheckDebug. +// +// GTMSessionMonitorSynchronized Start monitoring a top-level-only +// @sync scope. +// GTMSessionMonitorRecursiveSynchronized Start monitoring a top-level or +// recursive @sync scope. +// GTMSessionCheckSynchronized Verify that the current execution +// is inside a @sync scope. +// GTMSessionCheckNotSynchronized Verify that the current execution +// is not inside a @sync scope. +// +// Example usage: +// +// - (void)myExternalMethod { +// @synchronized(self) { +// GTMSessionMonitorSynchronized(self) +// +// - (void)myInternalMethod { +// GTMSessionCheckSynchronized(self); +// +// - (void)callMyCallbacks { +// GTMSessionCheckNotSynchronized(self); +// +// GTMSessionCheckNotSynchronized is available for verifying the code isn't +// in a deadlockable @sync state when posting notifications and invoking +// callbacks. Don't use GTMSessionCheckNotSynchronized immediately before a +// @sync scope; the normal recursiveness check of GTMSessionMonitorSynchronized +// can catch those. + +#ifdef __OBJC__ +// If asserts are entirely no-ops, the synchronization monitor is just a bunch +// of counting code that doesn't report exceptional circumstances in any way. +// Only build the synchronization monitor code if NS_BLOCK_ASSERTIONS is not +// defined or asserts are being logged instead. +#if DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG) + #define __GTMSessionMonitorSynchronizedVariableInner(varname, counter) \ + varname ## counter + #define __GTMSessionMonitorSynchronizedVariable(varname, counter) \ + __GTMSessionMonitorSynchronizedVariableInner(varname, counter) + + #define GTMSessionMonitorSynchronized(obj) \ + NS_VALID_UNTIL_END_OF_SCOPE id \ + __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ + [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ + allowRecursive:NO \ + functionName:__func__] + + #define GTMSessionMonitorRecursiveSynchronized(obj) \ + NS_VALID_UNTIL_END_OF_SCOPE id \ + __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ + [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ + allowRecursive:YES \ + functionName:__func__] + + #define GTMSessionCheckSynchronized(obj) { \ + GTMSESSION_ASSERT_DEBUG( \ + [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + @"GTMSessionCheckSynchronized(" #obj ") failed: not sync'd" \ + @" on " #obj " in %s. Call stack:\n%@", \ + __func__, [NSThread callStackSymbols]); \ + } + + #define GTMSessionCheckNotSynchronized(obj) { \ + GTMSESSION_ASSERT_DEBUG( \ + ![GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + @"GTMSessionCheckNotSynchronized(" #obj ") failed: was sync'd" \ + @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \ + [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + [NSThread callStackSymbols]); \ + } + +// GTMSessionSyncMonitorInternal is a private class that keeps track of the +// beginning and end of synchronized scopes. +// +// This class should not be used directly, but only via the +// GTMSessionMonitorSynchronized macro. +@interface GTMSessionSyncMonitorInternal : NSObject +- (instancetype)initWithSynchronizationObject:(id)object + allowRecursive:(BOOL)allowRecursive + functionName:(const char *)functionName; +// Return the names of the functions that hold sync on the object, or nil if none. ++ (NSArray *)functionsHoldingSynchronizationOnObject:(id)object; +@end + +#else + #define GTMSessionMonitorSynchronized(obj) do { } while (0) + #define GTMSessionMonitorRecursiveSynchronized(obj) do { } while (0) + #define GTMSessionCheckSynchronized(obj) do { } while (0) + #define GTMSessionCheckNotSynchronized(obj) do { } while (0) +#endif // !DEBUG +#endif // __OBJC__ + + +GTM_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m new file mode 100644 index 0000000..f61d9d7 --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m @@ -0,0 +1,4579 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionFetcher.h" + +#import + +#ifndef STRIP_GTM_FETCH_LOGGING + #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. +#endif + +GTM_ASSUME_NONNULL_BEGIN + +NSString *const kGTMSessionFetcherStartedNotification = @"kGTMSessionFetcherStartedNotification"; +NSString *const kGTMSessionFetcherStoppedNotification = @"kGTMSessionFetcherStoppedNotification"; +NSString *const kGTMSessionFetcherRetryDelayStartedNotification = @"kGTMSessionFetcherRetryDelayStartedNotification"; +NSString *const kGTMSessionFetcherRetryDelayStoppedNotification = @"kGTMSessionFetcherRetryDelayStoppedNotification"; + +NSString *const kGTMSessionFetcherCompletionInvokedNotification = @"kGTMSessionFetcherCompletionInvokedNotification"; +NSString *const kGTMSessionFetcherCompletionDataKey = @"data"; +NSString *const kGTMSessionFetcherCompletionErrorKey = @"error"; + +NSString *const kGTMSessionFetcherErrorDomain = @"com.google.GTMSessionFetcher"; +NSString *const kGTMSessionFetcherStatusDomain = @"com.google.HTTPStatus"; +NSString *const kGTMSessionFetcherStatusDataKey = @"data"; // data returned with a kGTMSessionFetcherStatusDomain error +NSString *const kGTMSessionFetcherStatusDataContentTypeKey = @"data_content_type"; + +NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey = @"kGTMSessionFetcherNumberOfRetriesDoneKey"; +NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey = @"kGTMSessionFetcherElapsedIntervalWithRetriesKey"; + +static NSString *const kGTMSessionIdentifierPrefix = @"com.google.GTMSessionFetcher"; +static NSString *const kGTMSessionIdentifierDestinationFileURLMetadataKey = @"_destURL"; +static NSString *const kGTMSessionIdentifierBodyFileURLMetadataKey = @"_bodyURL"; + +// The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH), +// 1 minute for downloads. +static const NSTimeInterval kUnsetMaxRetryInterval = -1.0; +static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0; +static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.; + +// The maximum data length that can be loaded to the error userInfo +static const int64_t kMaximumDownloadErrorDataLength = 20000; + +#ifdef GTMSESSION_PERSISTED_DESTINATION_KEY +// Projects using unique class names should also define a unique persisted destination key. +static NSString * const kGTMSessionFetcherPersistedDestinationKey = + GTMSESSION_PERSISTED_DESTINATION_KEY; +#else +static NSString * const kGTMSessionFetcherPersistedDestinationKey = + @"com.google.GTMSessionFetcher.downloads"; +#endif + +GTM_ASSUME_NONNULL_END + +// +// GTMSessionFetcher +// + +#if 0 +#define GTM_LOG_BACKGROUND_SESSION(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) +#else +#define GTM_LOG_BACKGROUND_SESSION(...) +#endif + +#ifndef GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY + #if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) + #define GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY 1 + #endif +#endif + +@interface GTMSessionFetcher () + +@property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadedData; +@property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadResumeData; + +#if GTM_BACKGROUND_TASK_FETCHING +// Should always be accessed within an @synchronized(self). +@property(assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier; +#endif + +@property(atomic, readwrite, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; + +@end + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (GTMSessionFetcherLoggingInternal) +- (void)logFetchWithError:(NSError *)error; +- (void)logNowWithError:(GTM_NULLABLE NSError *)error; +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider; +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +GTM_ASSUME_NONNULL_BEGIN + +static NSTimeInterval InitialMinRetryInterval(void) { + return 1.0 + ((double)(arc4random_uniform(0x0FFFF)) / (double) 0x0FFFF); +} + +static BOOL IsLocalhost(NSString * GTM_NULLABLE_TYPE host) { + // We check if there's host, and then make the comparisons. + if (host == nil) return NO; + return ([host caseInsensitiveCompare:@"localhost"] == NSOrderedSame + || [host isEqual:@"::1"] + || [host isEqual:@"127.0.0.1"]); +} + +static NSDictionary *GTM_NULLABLE_TYPE GTMErrorUserInfoForData( + NSData *GTM_NULLABLE_TYPE data, NSDictionary *GTM_NULLABLE_TYPE responseHeaders) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + + if (data.length > 0) { + userInfo[kGTMSessionFetcherStatusDataKey] = data; + + NSString *contentType = responseHeaders[@"Content-Type"]; + if (contentType) { + userInfo[kGTMSessionFetcherStatusDataContentTypeKey] = contentType; + } + } + + return userInfo.count > 0 ? userInfo : nil; +} + +static GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE gGlobalTestBlock; + +@implementation GTMSessionFetcher { + NSMutableURLRequest *_request; // after beginFetch, changed only in delegate callbacks + BOOL _useUploadTask; // immutable after beginFetch + NSURL *_bodyFileURL; // immutable after beginFetch + GTMSessionFetcherBodyStreamProvider _bodyStreamProvider; // immutable after beginFetch + NSURLSession *_session; + BOOL _shouldInvalidateSession; // immutable after beginFetch + NSURLSession *_sessionNeedingInvalidation; + NSURLSessionConfiguration *_configuration; + NSURLSessionTask *_sessionTask; + NSString *_taskDescription; + float _taskPriority; + NSURLResponse *_response; + NSString *_sessionIdentifier; + BOOL _wasCreatedFromBackgroundSession; + BOOL _didCreateSessionIdentifier; + NSString *_sessionIdentifierUUID; + BOOL _userRequestedBackgroundSession; + BOOL _usingBackgroundSession; + NSMutableData * GTM_NULLABLE_TYPE _downloadedData; + NSError *_downloadFinishedError; + NSData *_downloadResumeData; // immutable after construction + NSData * GTM_NULLABLE_TYPE _downloadTaskErrorData; // Data for when download task fails + NSURL *_destinationFileURL; + int64_t _downloadedLength; + NSURLCredential *_credential; // username & password + NSURLCredential *_proxyCredential; // credential supplied to proxy servers + BOOL _isStopNotificationNeeded; // set when start notification has been sent + BOOL _isUsingTestBlock; // set when a test block was provided (remains set when the block is released) + id _userData; // retained, if set by caller + NSMutableDictionary *_properties; // more data retained for caller + dispatch_queue_t _callbackQueue; + dispatch_group_t _callbackGroup; // read-only after creation + NSOperationQueue *_delegateQueue; // immutable after beginFetch + + id _authorizer; // immutable after beginFetch + + // The service object that created and monitors this fetcher, if any. + id _service; // immutable; set by the fetcher service upon creation + NSString *_serviceHost; + NSInteger _servicePriority; // immutable after beginFetch + BOOL _hasStoppedFetching; // counterpart to _initialBeginFetchDate + BOOL _userStoppedFetching; + + BOOL _isRetryEnabled; // user wants auto-retry + NSTimer *_retryTimer; + NSUInteger _retryCount; + NSTimeInterval _maxRetryInterval; // default 60 (download) or 600 (upload) seconds + NSTimeInterval _minRetryInterval; // random between 1 and 2 seconds + NSTimeInterval _retryFactor; // default interval multiplier is 2 + NSTimeInterval _lastRetryInterval; + NSDate *_initialBeginFetchDate; // date that beginFetch was first invoked; immutable after initial beginFetch + NSDate *_initialRequestDate; // date of first request to the target server (ignoring auth) + BOOL _hasAttemptedAuthRefresh; // accessed only in shouldRetryNowForStatus: + + NSString *_comment; // comment for log + NSString *_log; +#if !STRIP_GTM_FETCH_LOGGING + NSMutableData *_loggedStreamData; + NSURL *_redirectedFromURL; + NSString *_logRequestBody; + NSString *_logResponseBody; + BOOL _hasLoggedError; + BOOL _deferResponseBodyLogging; +#endif +} + +#if !GTMSESSION_UNIT_TESTING ++ (void)load { + [self fetchersForBackgroundSessions]; +} +#endif + ++ (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request { + return [[self alloc] initWithRequest:request configuration:nil]; +} + ++ (instancetype)fetcherWithURL:(NSURL *)requestURL { + return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; +} + ++ (instancetype)fetcherWithURLString:(NSString *)requestURLString { + return [self fetcherWithURL:(NSURL *)[NSURL URLWithString:requestURLString]]; +} + ++ (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData { + GTMSessionFetcher *fetcher = [self fetcherWithRequest:nil]; + fetcher.comment = @"Resuming download"; + fetcher.downloadResumeData = resumeData; + return fetcher; +} + ++ (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (!fetcher && [sessionIdentifier hasPrefix:kGTMSessionIdentifierPrefix]) { + fetcher = [self fetcherWithRequest:nil]; + [fetcher setSessionIdentifier:sessionIdentifier]; + [sessionIdentifierToFetcherMap setObject:fetcher forKey:sessionIdentifier]; + fetcher->_wasCreatedFromBackgroundSession = YES; + [fetcher setCommentWithFormat:@"Resuming %@", + fetcher && fetcher->_sessionIdentifierUUID ? fetcher->_sessionIdentifierUUID : @"?"]; + } + return fetcher; +} + ++ (NSMapTable *)sessionIdentifierToFetcherMap { + // TODO: What if a service is involved in creating the fetcher? Currently, when re-creating + // fetchers, if a service was involved, it is not re-created. Should the service maintain a map? + static NSMapTable *gSessionIdentifierToFetcherMap = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gSessionIdentifierToFetcherMap = [NSMapTable strongToWeakObjectsMapTable]; + }); + return gSessionIdentifierToFetcherMap; +} + +#if !GTM_ALLOW_INSECURE_REQUESTS ++ (BOOL)appAllowsInsecureRequests { + // If the main bundle Info.plist key NSAppTransportSecurity is present, and it specifies + // NSAllowsArbitraryLoads, then we need to explicitly enforce secure schemes. +#if GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY + static BOOL allowsInsecureRequests; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *mainBundle = [NSBundle mainBundle]; + NSDictionary *appTransportSecurity = + [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; + allowsInsecureRequests = + [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue]; + }); + return allowsInsecureRequests; +#else + // For builds targeting iOS 8 or 10.10 and earlier, we want to require fetcher + // security checks. + return YES; +#endif // GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY +} +#else // GTM_ALLOW_INSECURE_REQUESTS ++ (BOOL)appAllowsInsecureRequests { + return YES; +} +#endif // !GTM_ALLOW_INSECURE_REQUESTS + + +- (instancetype)init { + return [self initWithRequest:nil configuration:nil]; +} + +- (instancetype)initWithRequest:(NSURLRequest *)request { + return [self initWithRequest:request configuration:nil]; +} + +- (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request + configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration { + self = [super init]; + if (self) { +#if GTM_BACKGROUND_TASK_FETCHING + _backgroundTaskIdentifier = UIBackgroundTaskInvalid; +#endif + _request = [request mutableCopy]; + _configuration = configuration; + + NSData *bodyData = request.HTTPBody; + if (bodyData) { + _bodyLength = (int64_t)bodyData.length; + } else { + _bodyLength = NSURLSessionTransferSizeUnknown; + } + + _callbackQueue = dispatch_get_main_queue(); + _callbackGroup = dispatch_group_create(); + _delegateQueue = [NSOperationQueue mainQueue]; + + _minRetryInterval = InitialMinRetryInterval(); + _maxRetryInterval = kUnsetMaxRetryInterval; + + _taskPriority = -1.0f; // Valid values if set are 0.0...1.0. + + _testBlockAccumulateDataChunkCount = 1; + +#if !STRIP_GTM_FETCH_LOGGING + // Encourage developers to set the comment property or use + // setCommentWithFormat: by providing a default string. + _comment = @"(No fetcher comment set)"; +#endif + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + // disallow use of fetchers in a copy property + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +- (NSString *)description { + NSString *requestStr = self.request.URL.description; + if (requestStr.length == 0) { + if (self.downloadResumeData.length > 0) { + requestStr = @""; + } else if (_wasCreatedFromBackgroundSession) { + requestStr = @""; + } else { + requestStr = @""; + } + } + return [NSString stringWithFormat:@"%@ %p (%@)", [self class], self, requestStr]; +} + +- (void)dealloc { + GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, + @"unbalanced fetcher notification for %@", _request.URL); + [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; + + // Note: if a session task or a retry timer was pending, then this instance + // would be retained by those so it wouldn't be getting dealloc'd, + // hence we don't need to stopFetch here +} + +#pragma mark - + +// Begin fetching the URL (or begin a retry fetch). The delegate is retained +// for the duration of the fetch connection. + +- (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler { + GTMSessionCheckNotSynchronized(self); + + _completionHandler = [handler copy]; + + // The user may have called setDelegate: earlier if they want to use other + // delegate-style callbacks during the fetch; otherwise, the delegate is nil, + // which is fine. + [self beginFetchMayDelay:YES mayAuthorize:YES]; +} + +// Begin fetching the URL for a retry fetch. The delegate and completion handler +// are already provided, and do not need to be copied. +- (void)beginFetchForRetry { + GTMSessionCheckNotSynchronized(self); + + [self beginFetchMayDelay:YES mayAuthorize:YES]; +} + +- (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(GTM_NULLABLE_TYPE id)target + didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { + GTMSessionFetcherAssertValidSelector(target, finishedSelector, @encode(GTMSessionFetcher *), + @encode(NSData *), @encode(NSError *), 0); + GTMSessionFetcherCompletionHandler completionHandler = ^(NSData *data, NSError *error) { + if (target && finishedSelector) { + id selfArg = self; // Placate ARC. + NSMethodSignature *sig = [target methodSignatureForSelector:finishedSelector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; + [invocation setSelector:(SEL)finishedSelector]; + [invocation setTarget:target]; + [invocation setArgument:&selfArg atIndex:2]; + [invocation setArgument:&data atIndex:3]; + [invocation setArgument:&error atIndex:4]; + [invocation invoke]; + } + }; + return completionHandler; +} + +- (void)beginFetchWithDelegate:(GTM_NULLABLE_TYPE id)target + didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { + GTMSessionCheckNotSynchronized(self); + + GTMSessionFetcherCompletionHandler handler = [self completionHandlerWithTarget:target + didFinishSelector:finishedSelector]; + [self beginFetchWithCompletionHandler:handler]; +} + +- (void)beginFetchMayDelay:(BOOL)mayDelay + mayAuthorize:(BOOL)mayAuthorize { + // This is the internal entry point for re-starting fetches. + GTMSessionCheckNotSynchronized(self); + + NSMutableURLRequest *fetchRequest = _request; // The request property is now externally immutable. + NSURL *fetchRequestURL = fetchRequest.URL; + NSString *priorSessionIdentifier = self.sessionIdentifier; + + // A utility block for creating error objects when we fail to start the fetch. + NSError *(^beginFailureError)(NSInteger) = ^(NSInteger code){ + NSString *urlString = fetchRequestURL.absoluteString; + NSDictionary *userInfo = @{ + NSURLErrorFailingURLStringErrorKey : (urlString ? urlString : @"(missing URL)") + }; + return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:code + userInfo:userInfo]; + }; + + // Catch delegate queue maxConcurrentOperationCount values other than 1, particularly + // NSOperationQueueDefaultMaxConcurrentOperationCount (-1), to avoid the additional complexity + // of simultaneous or out-of-order delegate callbacks. + GTMSESSION_ASSERT_DEBUG(_delegateQueue.maxConcurrentOperationCount == 1, + @"delegate queue %@ should support one concurrent operation, not %ld", + _delegateQueue.name, + (long)_delegateQueue.maxConcurrentOperationCount); + + if (!_initialBeginFetchDate) { + // This ivar is set only here on the initial beginFetch so need not be synchronized. + _initialBeginFetchDate = [[NSDate alloc] init]; + } + + if (self.sessionTask != nil) { + // If cached fetcher returned through fetcherWithSessionIdentifier:, then it's + // already begun, but don't consider this a failure, since the user need not know this. + if (self.sessionIdentifier != nil) { + return; + } + GTMSESSION_ASSERT_DEBUG(NO, @"Fetch object %@ being reused; this should never happen", self); + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; + return; + } + + if (fetchRequestURL == nil && !_downloadResumeData && !priorSessionIdentifier) { + GTMSESSION_ASSERT_DEBUG(NO, @"Beginning a fetch requires a request with a URL"); + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; + return; + } + + // We'll respect the user's request for a background session (unless this is + // an upload fetcher, which does its initial request foreground.) + self.usingBackgroundSession = self.useBackgroundSession && [self canFetchWithBackgroundSession]; + + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSError *fileCheckError; + if (![bodyFileURL checkResourceIsReachableAndReturnError:&fileCheckError]) { + // This assert fires when the file being uploaded no longer exists once + // the fetcher is ready to start the upload. + GTMSESSION_ASSERT_DEBUG_OR_LOG(0, @"Body file is unreachable: %@\n %@", + bodyFileURL.path, fileCheckError); + [self failToBeginFetchWithError:fileCheckError]; + return; + } + } + + NSString *requestScheme = fetchRequestURL.scheme; + BOOL isDataRequest = [requestScheme isEqual:@"data"]; + if (isDataRequest) { + // NSURLSession does not support data URLs in background sessions. +#if DEBUG + if (priorSessionIdentifier || self.sessionIdentifier) { + GTMSESSION_LOG_DEBUG(@"Converting background to foreground session for %@", + fetchRequest); + } +#endif + [self setSessionIdentifierInternal:nil]; + self.useBackgroundSession = NO; + } + +#if GTM_ALLOW_INSECURE_REQUESTS + BOOL shouldCheckSecurity = NO; +#else + BOOL shouldCheckSecurity = (fetchRequestURL != nil + && !isDataRequest + && [[self class] appAllowsInsecureRequests]); +#endif + + if (shouldCheckSecurity) { + // Allow https only for requests, unless overridden by the client. + // + // Non-https requests may too easily be snooped, so we disallow them by default. + // + // file: and data: schemes are usually safe if they are hardcoded in the client or provided + // by a trusted source, but since it's fairly rare to need them, it's safest to make clients + // explicitly whitelist them. + BOOL isSecure = + requestScheme != nil && [requestScheme caseInsensitiveCompare:@"https"] == NSOrderedSame; + if (!isSecure) { + BOOL allowRequest = NO; + NSString *host = fetchRequestURL.host; + + // Check schemes first. A file scheme request may be allowed here, or as a localhost request. + for (NSString *allowedScheme in _allowedInsecureSchemes) { + if (requestScheme != nil && + [requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) { + allowRequest = YES; + break; + } + } + if (!allowRequest) { + // Check for localhost requests. Security checks only occur for non-https requests, so + // this check won't happen for an https request to localhost. + BOOL isLocalhostRequest = (host.length == 0 && [fetchRequestURL isFileURL]) || IsLocalhost(host); + if (isLocalhostRequest) { + if (self.allowLocalhostRequest) { + allowRequest = YES; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Fetch request for localhost but fetcher" + @" allowLocalhostRequest is not set: %@", fetchRequestURL); + } + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Insecure fetch request has a scheme (%@)" + @" not found in fetcher allowedInsecureSchemes (%@): %@", + requestScheme, _allowedInsecureSchemes ?: @" @[] ", fetchRequestURL); + } + } + + if (!allowRequest) { +#if !DEBUG + NSLog(@"Insecure fetch disallowed for %@", fetchRequestURL.description ?: @"nil request URL"); +#endif + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorInsecureRequest)]; + return; + } + } // !isSecure + } // (requestURL != nil) && !isDataRequest + + if (self.cookieStorage == nil) { + self.cookieStorage = [[self class] staticCookieStorage]; + } + + BOOL isRecreatingSession = (self.sessionIdentifier != nil) && (fetchRequest == nil); + + self.canShareSession = !isRecreatingSession && !self.usingBackgroundSession; + + if (!self.session && self.canShareSession) { + self.session = [_service sessionForFetcherCreation]; + // If _session is nil, then the service's session creation semaphore will block + // until this fetcher invokes fetcherDidCreateSession: below, so this *must* invoke + // that method, even if the session fails to be created. + } + + if (!self.session) { + // Create a session. + if (!_configuration) { + if (priorSessionIdentifier || self.usingBackgroundSession) { + NSString *sessionIdentifier = priorSessionIdentifier; + if (!sessionIdentifier) { + sessionIdentifier = [self createSessionIdentifierWithMetadata:nil]; + } + NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; + [sessionIdentifierToFetcherMap setObject:self forKey:self.sessionIdentifier]; + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)) + // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; +#elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0) + // Do a runtime check to avoid a deprecation warning about using + // +backgroundSessionConfiguration: on iOS 8. + if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) { + // Running on iOS 8+/OS X 10.10+. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +// Disable unguarded availability warning as we can't use the @availability macro until we require +// all clients to build with Xcode 9 or above. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; +#pragma clang diagnostic pop + } else { + // Running on iOS 7/OS X 10.9. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; + } +#else + // Building with an SDK earlier than iOS 8/OS X 10.10. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; +#endif + self.usingBackgroundSession = YES; + self.canShareSession = NO; + } else { + _configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + } +#if !GTM_ALLOW_INSECURE_REQUESTS + _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12; +#endif + } // !_configuration + _configuration.HTTPCookieStorage = self.cookieStorage; + + if (_configurationBlock) { + _configurationBlock(self, _configuration); + } + + id delegate = [_service sessionDelegate]; + if (!delegate || !self.canShareSession) { + delegate = self; + } + self.session = [NSURLSession sessionWithConfiguration:_configuration + delegate:delegate + delegateQueue:self.sessionDelegateQueue]; + GTMSESSION_ASSERT_DEBUG(self.session, @"Couldn't create session"); + + // Tell the service about the session created by this fetcher. This also signals the + // service's semaphore to allow other fetchers to request this session. + [_service fetcherDidCreateSession:self]; + + // If this assertion fires, the client probably tried to use a session identifier that was + // already used. The solution is to make the client use a unique identifier (or better yet let + // the session fetcher assign the identifier). + GTMSESSION_ASSERT_DEBUG(self.session.delegate == delegate, @"Couldn't assign delegate."); + + if (self.session) { + BOOL isUsingSharedDelegate = (delegate != self); + if (!isUsingSharedDelegate) { + _shouldInvalidateSession = YES; + } + } + } + + if (isRecreatingSession) { + _shouldInvalidateSession = YES; + + // Let's make sure there are tasks still running or if not that we get a callback from a + // completed one; otherwise, we assume the tasks failed. + // This is the observed behavior perhaps 25% of the time within the Simulator running 7.0.3 on + // exiting the app after starting an upload and relaunching the app if we manage to relaunch + // after the task has completed, but before the system relaunches us in the background. + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, + NSArray *downloadTasks) { + if (dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0) { + double const kDelayInSeconds = 1.0; // We should get progress indication or completion soon + dispatch_time_t checkForFeedbackDelay = + dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDelayInSeconds * NSEC_PER_SEC)); + dispatch_after(checkForFeedbackDelay, dispatch_get_main_queue(), ^{ + if (!self.sessionTask && !fetchRequest) { + // If our task and/or request haven't been restored, then we assume task feedback lost. + [self removePersistedBackgroundSessionFromDefaults]; + NSError *sessionError = + [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorBackgroundFetchFailed + userInfo:nil]; + [self failToBeginFetchWithError:sessionError]; + } + }); + } + }]; + return; + } + + self.downloadedData = nil; + self.downloadedLength = 0; + + if (_servicePriority == NSIntegerMin) { + mayDelay = NO; + } + if (mayDelay && _service) { + BOOL shouldFetchNow = [_service fetcherShouldBeginFetching:self]; + if (!shouldFetchNow) { + // The fetch is deferred, but will happen later. + // + // If this session is held by the fetcher service, clear the session now so that we don't + // assume it's still valid after the fetcher is restarted. + if (self.canShareSession) { + self.session = nil; + } + return; + } + } + + NSString *effectiveHTTPMethod = [fetchRequest valueForHTTPHeaderField:@"X-HTTP-Method-Override"]; + if (effectiveHTTPMethod == nil) { + effectiveHTTPMethod = fetchRequest.HTTPMethod; + } + BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil + || [effectiveHTTPMethod isEqual:@"GET"]); + + BOOL needsUploadTask = (self.useUploadTask || self.bodyFileURL || self.bodyStreamProvider); + if (_bodyData || self.bodyStreamProvider || fetchRequest.HTTPBodyStream) { + if (isEffectiveHTTPGet) { + fetchRequest.HTTPMethod = @"POST"; + isEffectiveHTTPGet = NO; + } + + if (_bodyData) { + if (!needsUploadTask) { + fetchRequest.HTTPBody = _bodyData; + } +#if !STRIP_GTM_FETCH_LOGGING + } else if (fetchRequest.HTTPBodyStream) { + if ([self respondsToSelector:@selector(loggedInputStreamForInputStream:)]) { + fetchRequest.HTTPBodyStream = + [self performSelector:@selector(loggedInputStreamForInputStream:) + withObject:fetchRequest.HTTPBodyStream]; + } +#endif + } + } + + // We authorize after setting up the http method and body in the request + // because OAuth 1 may need to sign the request body + if (mayAuthorize && _authorizer && !isDataRequest) { + BOOL isAuthorized = [_authorizer isAuthorizedRequest:fetchRequest]; + if (!isAuthorized) { + // Authorization needed. + // + // If this session is held by the fetcher service, clear the session now so that we don't + // assume it's still valid after authorization completes. + if (self.canShareSession) { + self.session = nil; + } + + // Authorizing the request will recursively call this beginFetch:mayDelay: + // or failToBeginFetchWithError:. + [self authorizeRequest]; + return; + } + } + + // set the default upload or download retry interval, if necessary + if ([self isRetryEnabled] && self.maxRetryInterval <= 0) { + if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) { + [self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval]; + } else { + [self setMaxRetryInterval:kDefaultMaxUploadRetryInterval]; + } + } + + // finally, start the connection + NSURLSessionTask *newSessionTask; + BOOL needsDataAccumulator = NO; + if (_downloadResumeData) { + newSessionTask = [_session downloadTaskWithResumeData:_downloadResumeData]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed downloadTaskWithResumeData for %@, resume data %lu bytes", + _session, (unsigned long)_downloadResumeData.length); + } else if (_destinationFileURL && !isDataRequest) { + newSessionTask = [_session downloadTaskWithRequest:fetchRequest]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed downloadTaskWithRequest for %@, %@", + _session, fetchRequest); + } else if (needsUploadTask) { + if (bodyFileURL) { + newSessionTask = [_session uploadTaskWithRequest:fetchRequest + fromFile:bodyFileURL]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithRequest for %@, %@, file %@", + _session, fetchRequest, bodyFileURL.path); + } else if (self.bodyStreamProvider) { + newSessionTask = [_session uploadTaskWithStreamedRequest:fetchRequest]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithStreamedRequest for %@, %@", + _session, fetchRequest); + } else { + GTMSESSION_ASSERT_DEBUG_OR_LOG(_bodyData != nil, + @"Upload task needs body data, %@", fetchRequest); + newSessionTask = [_session uploadTaskWithRequest:fetchRequest + fromData:(NSData * GTM_NONNULL_TYPE)_bodyData]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithRequest for %@, %@, body data %lu bytes", + _session, fetchRequest, (unsigned long)_bodyData.length); + } + needsDataAccumulator = YES; + } else { + newSessionTask = [_session dataTaskWithRequest:fetchRequest]; + needsDataAccumulator = YES; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed dataTaskWithRequest for %@, %@", + _session, fetchRequest); + } + self.sessionTask = newSessionTask; + + if (!newSessionTask) { + // We shouldn't get here; if we're here, an earlier assertion should have fired to explain + // which session task creation failed. + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorTaskCreationFailed)]; + return; + } + + if (needsDataAccumulator && _accumulateDataBlock == nil) { + self.downloadedData = [NSMutableData data]; + } + if (_taskDescription) { + newSessionTask.taskDescription = _taskDescription; + } + if (_taskPriority >= 0) { +#if TARGET_OS_TV || TARGET_OS_WATCH + BOOL hasTaskPriority = YES; +#elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) + BOOL hasTaskPriority = YES; +#else + BOOL hasTaskPriority = [newSessionTask respondsToSelector:@selector(setPriority:)]; +#endif + if (hasTaskPriority) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +// Disable unguarded availability warning as we can't use the @availability macro until we require +// all clients to build with Xcode 9 or above. + newSessionTask.priority = _taskPriority; +#pragma clang diagnostic pop + } + } + +#if GTM_DISABLE_FETCHER_TEST_BLOCK + GTMSESSION_ASSERT_DEBUG(_testBlock == nil && gGlobalTestBlock == nil, @"test blocks disabled"); + _testBlock = nil; +#else + if (!_testBlock) { + if (gGlobalTestBlock) { + // Note that the test block may pass nil for all of its response parameters, + // indicating that the fetch should actually proceed. This is useful when the + // global test block has been set, and the app is only testing a specific + // fetcher. The block simulation code will then resume the task. + _testBlock = gGlobalTestBlock; + } + } + _isUsingTestBlock = (_testBlock != nil); +#endif // GTM_DISABLE_FETCHER_TEST_BLOCK + +#if GTM_BACKGROUND_TASK_FETCHING + id app = [[self class] fetcherUIApplication]; + // Background tasks seem to interfere with out-of-process uploads and downloads. + if (app && !self.skipBackgroundTask && !self.useBackgroundSession) { + // Tell UIApplication that we want to continue even when the app is in the + // background. +#if DEBUG + NSString *bgTaskName = [NSString stringWithFormat:@"%@-%@", + [self class], fetchRequest.URL.host]; +#else + NSString *bgTaskName = @"GTMSessionFetcher"; +#endif + __block UIBackgroundTaskIdentifier bgTaskID = [app beginBackgroundTaskWithName:bgTaskName + expirationHandler:^{ + // Background task expiration callback - this block is always invoked by + // UIApplication on the main thread. + if (bgTaskID != UIBackgroundTaskInvalid) { + @synchronized(self) { + if (bgTaskID == self.backgroundTaskIdentifier) { + self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + } + [app endBackgroundTask:bgTaskID]; + } + }]; + @synchronized(self) { + self.backgroundTaskIdentifier = bgTaskID; + } + } +#endif + + if (!_initialRequestDate) { + _initialRequestDate = [[NSDate alloc] init]; + } + + // We don't expect to reach here even on retry or auth until a stop notification has been sent + // for the previous task, but we should ensure that we don't unbalance that. + GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, @"Start notification without a prior stop"); + [self sendStopNotificationIfNeeded]; + + [self addPersistedBackgroundSessionToDefaults]; + + [self setStopNotificationNeeded:YES]; + + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStartedNotification + userInfo:nil + requireAsync:NO]; + + // The service needs to know our task if it is serving as NSURLSession delegate. + [_service fetcherDidBeginFetching:self]; + + if (_testBlock) { +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + [self simulateFetchForTestBlock]; +#endif + } else { + // We resume the session task after posting the notification since the + // delegate callbacks may happen immediately if the fetch is started off + // the main thread or the session delegate queue is on a background thread, + // and we don't want to post a start notification after a premature finish + // of the session task. + [newSessionTask resume]; + } +} + +NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError) { + NSMutableData *data = [NSMutableData data]; + + [inputStream open]; + NSInteger numberOfBytesRead = 0; + while ([inputStream hasBytesAvailable]) { + uint8_t buffer[512]; + numberOfBytesRead = [inputStream read:buffer maxLength:sizeof(buffer)]; + if (numberOfBytesRead > 0) { + [data appendBytes:buffer length:(NSUInteger)numberOfBytesRead]; + } else { + break; + } + } + [inputStream close]; + NSError *streamError = inputStream.streamError; + + if (streamError) { + data = nil; + } + if (outError) { + *outError = streamError; + } + return data; +} + +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + +- (void)simulateFetchForTestBlock { + // This is invoked on the same thread as the beginFetch method was. + // + // Callbacks will all occur on the callback queue. + _testBlock(self, ^(NSURLResponse *response, NSData *responseData, NSError *error) { + // Callback from test block. + if (response == nil && responseData == nil && error == nil) { + // Assume the fetcher should execute rather than be tested. + self->_testBlock = nil; + self->_isUsingTestBlock = NO; + [self->_sessionTask resume]; + return; + } + + GTMSessionFetcherBodyStreamProvider bodyStreamProvider = self.bodyStreamProvider; + if (bodyStreamProvider) { + bodyStreamProvider(^(NSInputStream *bodyStream){ + // Read from the input stream into an NSData buffer. We'll drain the stream + // explicitly on a background queue. + [self invokeOnCallbackQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) + afterUserStopped:NO + block:^{ + NSError *streamError; + NSData *streamedData = GTMDataFromInputStream(bodyStream, &streamError); + + dispatch_async(dispatch_get_main_queue(), ^{ + // Continue callbacks on the main thread, since serial behavior + // is more reliable for tests. + [self simulateDataCallbacksForTestBlockWithBodyData:streamedData + response:response + responseData:responseData + error:(error ?: streamError)]; + }); + }]; + }); + } else { + // No input stream; use the supplied data or file URL. + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSError *readError; + self->_bodyData = [NSData dataWithContentsOfURL:bodyFileURL + options:NSDataReadingMappedIfSafe + error:&readError]; + error = readError; + } + + // No stream provider. + + // In real fetches, nothing happens until the run loop spins, so apps have leeway to + // set callbacks after they call beginFetch. We'll mirror that fetcher behavior by + // delaying callbacks here at least to the next spin of the run loop. That keeps + // immediate, synchronous setting of callback blocks after beginFetch working in tests. + dispatch_async(dispatch_get_main_queue(), ^{ + [self simulateDataCallbacksForTestBlockWithBodyData:self->_bodyData + response:response + responseData:responseData + error:error]; + }); + } + }); +} + +- (void)simulateByteTransferReportWithDataLength:(int64_t)totalDataLength + block:(GTMSessionFetcherSendProgressBlock)block { + // This utility method simulates transfer progress with up to three callbacks. + // It is used to call back to any of the progress blocks. + int64_t sendReportSize = totalDataLength / 3 + 1; + int64_t totalSent = 0; + while (totalSent < totalDataLength) { + int64_t bytesRemaining = totalDataLength - totalSent; + sendReportSize = MIN(sendReportSize, bytesRemaining); + totalSent += sendReportSize; + [self invokeOnCallbackQueueUnlessStopped:^{ + block(sendReportSize, totalSent, totalDataLength); + }]; + } +} + +- (void)simulateDataCallbacksForTestBlockWithBodyData:(NSData * GTM_NULLABLE_TYPE)bodyData + response:(NSURLResponse *)response + responseData:(NSData *)suppliedData + error:(NSError *)suppliedError { + __block NSData *responseData = suppliedData; + __block NSError *responseError = suppliedError; + + // This method does the test simulation of callbacks once the upload + // and download data are known. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Get copies of ivars we'll access in async invocations. This simulation assumes + // they won't change during fetcher execution. + NSURL *destinationFileURL = _destinationFileURL; + GTMSessionFetcherWillRedirectBlock willRedirectBlock = _willRedirectBlock; + GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock = _didReceiveResponseBlock; + GTMSessionFetcherSendProgressBlock sendProgressBlock = _sendProgressBlock; + GTMSessionFetcherDownloadProgressBlock downloadProgressBlock = _downloadProgressBlock; + GTMSessionFetcherAccumulateDataBlock accumulateDataBlock = _accumulateDataBlock; + GTMSessionFetcherReceivedProgressBlock receivedProgressBlock = _receivedProgressBlock; + GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock = + _willCacheURLResponseBlock; + + // Simulate receipt of redirection. + if (willRedirectBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + willRedirectBlock((NSHTTPURLResponse *)response, self->_request, + ^(NSURLRequest *redirectRequest) { + // For simulation, we'll assume the app will just continue. + }); + }]; + } + + // If the fetcher has a challenge block, simulate a challenge. + // + // It might be nice to eventually let the user determine which testBlock + // fetches get challenged rather than always executing the supplied + // challenge block. + if (_challengeBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + if (self->_challengeBlock) { + NSURL *requestURL = self->_request.URL; + NSString *host = requestURL.host; + NSURLProtectionSpace *pspace = + [[NSURLProtectionSpace alloc] initWithHost:host + port:requestURL.port.integerValue + protocol:requestURL.scheme + realm:nil + authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; + id unusedSender = + (id)[NSNull null]; + NSURLAuthenticationChallenge *challenge = + [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:pspace + proposedCredential:nil + previousFailureCount:0 + failureResponse:nil + error:nil + sender:unusedSender]; + self->_challengeBlock(self, challenge, ^(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential){ + // We could change the responseData and responseError based on the disposition, + // but it's easier for apps to just supply the expected data and error + // directly to the test block. So this simulation ignores the disposition. + }); + } + }]; + } + + // Simulate receipt of an initial response. + if (response && didReceiveResponseBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + didReceiveResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { + // For simulation, we'll assume the disposition is to continue. + }); + }]; + } + + // Simulate reporting send progress. + if (sendProgressBlock) { + [self simulateByteTransferReportWithDataLength:(int64_t)bodyData.length + block:^(int64_t bytesSent, + int64_t totalBytesSent, + int64_t totalBytesExpectedToSend) { + // This is invoked on the callback queue unless stopped. + sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); + }]; + } + + if (destinationFileURL) { + // Simulate download to file progress. + if (downloadProgressBlock) { + [self simulateByteTransferReportWithDataLength:(int64_t)responseData.length + block:^(int64_t bytesDownloaded, + int64_t totalBytesDownloaded, + int64_t totalBytesExpectedToDownload) { + // This is invoked on the callback queue unless stopped. + downloadProgressBlock(bytesDownloaded, totalBytesDownloaded, + totalBytesExpectedToDownload); + }]; + } + + NSError *writeError; + [responseData writeToURL:destinationFileURL + options:NSDataWritingAtomic + error:&writeError]; + if (writeError) { + // Tell the test code that writing failed. + responseError = writeError; + } + } else { + // Simulate download to NSData progress. + if ((accumulateDataBlock || receivedProgressBlock) && responseData) { + [self simulateByteTransferWithData:responseData + block:^(NSData *data, + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpectedToReceive) { + // This is invoked on the callback queue unless stopped. + if (accumulateDataBlock) { + accumulateDataBlock(data); + } + + if (receivedProgressBlock) { + receivedProgressBlock(bytesReceived, totalBytesReceived); + } + }]; + } + + if (!accumulateDataBlock) { + _downloadedData = [responseData mutableCopy]; + } + + if (willCacheURLResponseBlock) { + // Simulate letting the client inspect and alter the cached response. + NSData *cachedData = responseData ?: [[NSData alloc] init]; // Always have non-nil data. + NSCachedURLResponse *cachedResponse = + [[NSCachedURLResponse alloc] initWithResponse:response + data:cachedData]; + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + willCacheURLResponseBlock(cachedResponse, ^(NSCachedURLResponse *responseToCache){ + // The app may provide an alternative response, or nil to defeat caching. + }); + }]; + } + } + _response = response; + } // @synchronized(self) + + NSOperationQueue *queue = self.sessionDelegateQueue; + [queue addOperationWithBlock:^{ + // Rather than invoke failToBeginFetchWithError: we want to simulate completion of + // a connection that started and ended, so we'll call down to finishWithError: + NSInteger status = responseError ? responseError.code : 200; + if (status >= 200 && status <= 399) { + [self finishWithError:nil shouldRetry:NO]; + } else { + [self shouldRetryNowForStatus:status + error:responseError + forceAssumeRetry:NO + response:^(BOOL shouldRetry) { + [self finishWithError:responseError shouldRetry:shouldRetry]; + }]; + } + }]; +} + +- (void)simulateByteTransferWithData:(NSData *)responseData + block:(GTMSessionFetcherSimulateByteTransferBlock)transferBlock { + // This utility method simulates transfering data to the client. It divides the data into at most + // "chunkCount" chunks and then passes each chunk along with a progress update to transferBlock. + // This function can be used with accumulateDataBlock or receivedProgressBlock. + + NSUInteger chunkCount = MAX(self.testBlockAccumulateDataChunkCount, (NSUInteger) 1); + NSUInteger totalDataLength = responseData.length; + NSUInteger sendDataSize = totalDataLength / chunkCount + 1; + NSUInteger totalSent = 0; + while (totalSent < totalDataLength) { + NSUInteger bytesRemaining = totalDataLength - totalSent; + sendDataSize = MIN(sendDataSize, bytesRemaining); + NSData *chunkData = [responseData subdataWithRange:NSMakeRange(totalSent, sendDataSize)]; + totalSent += sendDataSize; + [self invokeOnCallbackQueueUnlessStopped:^{ + transferBlock(chunkData, + (int64_t)sendDataSize, + (int64_t)totalSent, + (int64_t)totalDataLength); + }]; + } +} + +#endif // !GTM_DISABLE_FETCHER_TEST_BLOCK + +- (void)setSessionTask:(NSURLSessionTask *)sessionTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionTask != sessionTask) { + _sessionTask = sessionTask; + if (_sessionTask) { + // Request could be nil on restoring this fetcher from a background session. + if (!_request) { + _request = [_sessionTask.originalRequest mutableCopy]; + } + } + } + } // @synchronized(self) +} + +- (NSURLSessionTask * GTM_NULLABLE_TYPE)sessionTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionTask; + } // @synchronized(self) +} + ++ (NSUserDefaults *)fetcherUserDefaults { + static NSUserDefaults *gFetcherUserDefaults = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class fetcherUserDefaultsClass = NSClassFromString(@"GTMSessionFetcherUserDefaultsFactory"); + if (fetcherUserDefaultsClass) { + gFetcherUserDefaults = [fetcherUserDefaultsClass fetcherUserDefaults]; + } else { + gFetcherUserDefaults = [NSUserDefaults standardUserDefaults]; + } + }); + return gFetcherUserDefaults; +} + +- (void)addPersistedBackgroundSessionToDefaults { + NSString *sessionIdentifier = self.sessionIdentifier; + if (!sessionIdentifier) { + return; + } + NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; + if ([oldBackgroundSessions containsObject:_sessionIdentifier]) { + return; + } + NSMutableArray *newBackgroundSessions = + [NSMutableArray arrayWithArray:oldBackgroundSessions]; + [newBackgroundSessions addObject:sessionIdentifier]; + GTM_LOG_BACKGROUND_SESSION(@"Add to background sessions: %@", newBackgroundSessions); + + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + [userDefaults setObject:newBackgroundSessions + forKey:kGTMSessionFetcherPersistedDestinationKey]; + [userDefaults synchronize]; +} + +- (void)removePersistedBackgroundSessionFromDefaults { + NSString *sessionIdentifier = self.sessionIdentifier; + if (!sessionIdentifier) return; + + NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; + if (!oldBackgroundSessions) { + return; + } + NSMutableArray *newBackgroundSessions = + [NSMutableArray arrayWithArray:oldBackgroundSessions]; + NSUInteger sessionIndex = [newBackgroundSessions indexOfObject:sessionIdentifier]; + if (sessionIndex == NSNotFound) { + return; + } + [newBackgroundSessions removeObjectAtIndex:sessionIndex]; + GTM_LOG_BACKGROUND_SESSION(@"Remove from background sessions: %@", newBackgroundSessions); + + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + if (newBackgroundSessions.count == 0) { + [userDefaults removeObjectForKey:kGTMSessionFetcherPersistedDestinationKey]; + } else { + [userDefaults setObject:newBackgroundSessions + forKey:kGTMSessionFetcherPersistedDestinationKey]; + } + [userDefaults synchronize]; +} + ++ (GTM_NULLABLE NSArray *)activePersistedBackgroundSessions { + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + NSArray *oldBackgroundSessions = + [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; + if (oldBackgroundSessions.count == 0) { + return nil; + } + NSMutableArray *activeBackgroundSessions = nil; + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + for (NSString *sessionIdentifier in oldBackgroundSessions) { + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (fetcher) { + if (!activeBackgroundSessions) { + activeBackgroundSessions = [[NSMutableArray alloc] init]; + } + [activeBackgroundSessions addObject:sessionIdentifier]; + } + } + return activeBackgroundSessions; +} + ++ (NSArray *)fetchersForBackgroundSessions { + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + NSArray *backgroundSessions = + [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + NSMutableArray *fetchers = [NSMutableArray array]; + for (NSString *sessionIdentifier in backgroundSessions) { + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (!fetcher) { + fetcher = [self fetcherWithSessionIdentifier:sessionIdentifier]; + GTMSESSION_ASSERT_DEBUG(fetcher != nil, + @"Unexpected invalid session identifier: %@", sessionIdentifier); + [fetcher beginFetchWithCompletionHandler:nil]; + } + GTM_LOG_BACKGROUND_SESSION(@"%@ restoring session %@ by creating fetcher %@ %p", + [self class], sessionIdentifier, fetcher, fetcher); + if (fetcher != nil) { + [fetchers addObject:fetcher]; + } + } + return fetchers; +} + +#if TARGET_OS_IPHONE && !TARGET_OS_WATCH ++ (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler { + GTMSessionFetcher *fetcher = [self fetcherWithSessionIdentifier:identifier]; + if (fetcher != nil) { + fetcher.systemCompletionHandler = completionHandler; + } else { + GTM_LOG_BACKGROUND_SESSION(@"%@ did not create background session identifier: %@", + [self class], identifier); + } +} +#endif + +- (NSString * GTM_NULLABLE_TYPE)sessionIdentifier { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionIdentifier; + } // @synchronized(self) +} + +- (void)setSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(!_session, @"Unable to set session identifier after session created"); + _sessionIdentifier = [sessionIdentifier copy]; + _usingBackgroundSession = YES; + _canShareSession = NO; + [self restoreDefaultStateForSessionIdentifierMetadata]; + } // @synchronized(self) +} + +- (void)setSessionIdentifierInternal:(GTM_NULLABLE NSString *)sessionIdentifier { + // This internal method only does a synchronized set of the session identifier. + // It does not have side effects on the background session, shared session, or + // session identifier metadata. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _sessionIdentifier = [sessionIdentifier copy]; + } // @synchronized(self) +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionUserInfo { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionUserInfo == nil) { + // We'll return the metadata dictionary with internal keys removed. This avoids the user + // re-using the userInfo dictionary later and accidentally including the internal keys. + NSMutableDictionary *metadata = [[self sessionIdentifierMetadataUnsynchronized] mutableCopy]; + NSSet *keysToRemove = [metadata keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { + return [key hasPrefix:@"_"]; + }]; + [metadata removeObjectsForKeys:[keysToRemove allObjects]]; + if (metadata.count > 0) { + _sessionUserInfo = metadata; + } + } + return _sessionUserInfo; + } // @synchronized(self) +} + +- (void)setSessionUserInfo:(NSDictionary * GTM_NULLABLE_TYPE)dictionary { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(_sessionIdentifier == nil, @"Too late to assign userInfo"); + _sessionUserInfo = dictionary; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSDictionary *)sessionIdentifierDefaultMetadata { + GTMSessionCheckSynchronized(self); + + NSMutableDictionary *defaultUserInfo = [[NSMutableDictionary alloc] init]; + if (_destinationFileURL) { + defaultUserInfo[kGTMSessionIdentifierDestinationFileURLMetadataKey] = + [_destinationFileURL absoluteString]; + } + if (_bodyFileURL) { + defaultUserInfo[kGTMSessionIdentifierBodyFileURLMetadataKey] = [_bodyFileURL absoluteString]; + } + return (defaultUserInfo.count > 0) ? defaultUserInfo : nil; +} + +- (void)restoreDefaultStateForSessionIdentifierMetadata { + GTMSessionCheckSynchronized(self); + + NSDictionary *metadata = [self sessionIdentifierMetadataUnsynchronized]; + NSString *destinationFileURLString = metadata[kGTMSessionIdentifierDestinationFileURLMetadataKey]; + if (destinationFileURLString) { + _destinationFileURL = [NSURL URLWithString:destinationFileURLString]; + GTM_LOG_BACKGROUND_SESSION(@"Restoring destination file URL: %@", _destinationFileURL); + } + NSString *bodyFileURLString = metadata[kGTMSessionIdentifierBodyFileURLMetadataKey]; + if (bodyFileURLString) { + _bodyFileURL = [NSURL URLWithString:bodyFileURLString]; + GTM_LOG_BACKGROUND_SESSION(@"Restoring body file URL: %@", _bodyFileURL); + } +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadata { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [self sessionIdentifierMetadataUnsynchronized]; + } +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadataUnsynchronized { + GTMSessionCheckSynchronized(self); + + // Session Identifier format: "com.google.__ + if (!_sessionIdentifier) { + return nil; + } + NSScanner *metadataScanner = [NSScanner scannerWithString:_sessionIdentifier]; + [metadataScanner setCharactersToBeSkipped:nil]; + NSString *metadataString; + NSString *uuid; + if ([metadataScanner scanUpToString:@"_" intoString:NULL] && + [metadataScanner scanString:@"_" intoString:NULL] && + [metadataScanner scanUpToString:@"_" intoString:&uuid] && + [metadataScanner scanString:@"_" intoString:NULL] && + [metadataScanner scanUpToString:@"\n" intoString:&metadataString]) { + _sessionIdentifierUUID = uuid; + NSData *metadataData = [metadataString dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error; + NSDictionary *metadataDict = + [NSJSONSerialization JSONObjectWithData:metadataData + options:0 + error:&error]; + GTM_LOG_BACKGROUND_SESSION(@"User Info from session identifier: %@ %@", + metadataDict, error ? error : @""); + return metadataDict; + } + return nil; +} + +- (NSString *)createSessionIdentifierWithMetadata:(NSDictionary * GTM_NULLABLE_TYPE)metadataToInclude { + NSString *result; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Session Identifier format: "com.google.__ + GTMSESSION_ASSERT_DEBUG(!_sessionIdentifier, @"Session identifier already created"); + _sessionIdentifierUUID = [[NSUUID UUID] UUIDString]; + _sessionIdentifier = + [NSString stringWithFormat:@"%@_%@", kGTMSessionIdentifierPrefix, _sessionIdentifierUUID]; + // Start with user-supplied keys so they cannot accidentally override the fetcher's keys. + NSMutableDictionary *metadataDict = + [NSMutableDictionary dictionaryWithDictionary:(NSDictionary * GTM_NONNULL_TYPE)_sessionUserInfo]; + + if (metadataToInclude) { + [metadataDict addEntriesFromDictionary:(NSDictionary *)metadataToInclude]; + } + NSDictionary *defaultMetadataDict = [self sessionIdentifierDefaultMetadata]; + if (defaultMetadataDict) { + [metadataDict addEntriesFromDictionary:defaultMetadataDict]; + } + if (metadataDict.count > 0) { + NSData *metadataData = [NSJSONSerialization dataWithJSONObject:metadataDict + options:0 + error:NULL]; + GTMSESSION_ASSERT_DEBUG(metadataData != nil, + @"Session identifier user info failed to convert to JSON"); + if (metadataData.length > 0) { + NSString *metadataString = [[NSString alloc] initWithData:metadataData + encoding:NSUTF8StringEncoding]; + _sessionIdentifier = + [_sessionIdentifier stringByAppendingFormat:@"_%@", metadataString]; + } + } + _didCreateSessionIdentifier = YES; + result = _sessionIdentifier; + } // @synchronized(self) + return result; +} + +- (void)failToBeginFetchWithError:(NSError *)error { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _hasStoppedFetching = YES; + } + + if (error == nil) { + error = [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorDownloadFailed + userInfo:nil]; + } + + [self invokeFetchCallbacksOnCallbackQueueWithData:nil + error:error]; + [self releaseCallbacks]; + + [_service fetcherDidStop:self]; + + self.authorizer = nil; +} + ++ (GTMSessionCookieStorage *)staticCookieStorage { + static GTMSessionCookieStorage *gCookieStorage = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gCookieStorage = [[GTMSessionCookieStorage alloc] init]; + }); + return gCookieStorage; +} + +#if GTM_BACKGROUND_TASK_FETCHING + +- (void)endBackgroundTask { + // Whenever the connection stops or background execution expires, + // we need to tell UIApplication we're done. + UIBackgroundTaskIdentifier bgTaskID; + @synchronized(self) { + bgTaskID = self.backgroundTaskIdentifier; + if (bgTaskID != UIBackgroundTaskInvalid) { + self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + } + + if (bgTaskID != UIBackgroundTaskInvalid) { + id app = [[self class] fetcherUIApplication]; + [app endBackgroundTask:bgTaskID]; + } +} + +#endif // GTM_BACKGROUND_TASK_FETCHING + +- (void)authorizeRequest { + GTMSessionCheckNotSynchronized(self); + + id authorizer = self.authorizer; + SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:); + if ([authorizer respondsToSelector:asyncAuthSel]) { + SEL callbackSel = @selector(authorizer:request:finishedWithError:); + NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; + [authorizer authorizeRequest:mutableRequest + delegate:self + didFinishSelector:callbackSel]; + } else { + GTMSESSION_ASSERT_DEBUG(authorizer == nil, @"invalid authorizer for fetch"); + + // No authorizing possible, and authorizing happens only after any delay; + // just begin fetching + [self beginFetchMayDelay:NO + mayAuthorize:NO]; + } +} + +- (void)authorizer:(id)auth + request:(NSMutableURLRequest *)authorizedRequest + finishedWithError:(NSError *)error { + GTMSessionCheckNotSynchronized(self); + + if (error != nil) { + // We can't fetch without authorization + [self failToBeginFetchWithError:error]; + } else { + @synchronized(self) { + _request = authorizedRequest; + } + [self beginFetchMayDelay:NO + mayAuthorize:NO]; + } +} + + +- (BOOL)canFetchWithBackgroundSession { + // Subclasses may override. + return YES; +} + +// Returns YES if the fetcher has been started and has not yet stopped. +// +// Fetching includes waiting for authorization or for retry, waiting to be allowed by the +// service object to start the request, and actually fetching the request. +- (BOOL)isFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [self isFetchingUnsynchronized]; + } +} + +- (BOOL)isFetchingUnsynchronized { + GTMSessionCheckSynchronized(self); + + BOOL hasBegun = (_initialBeginFetchDate != nil); + return hasBegun && !_hasStoppedFetching; +} + +- (NSURLResponse * GTM_NULLABLE_TYPE)response { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + return response; + } // @synchronized(self) +} + +- (NSURLResponse * GTM_NULLABLE_TYPE)responseUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = _sessionTask.response; + if (!response) response = _response; + return response; +} + +- (NSInteger)statusCode { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSInteger statusCode = [self statusCodeUnsynchronized]; + return statusCode; + } // @synchronized(self) +} + +- (NSInteger)statusCodeUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + NSInteger statusCode; + + if ([response respondsToSelector:@selector(statusCode)]) { + statusCode = [(NSHTTPURLResponse *)response statusCode]; + } else { + // Default to zero, in hopes of hinting "Unknown" (we can't be + // sure that things are OK enough to use 200). + statusCode = 0; + } + return statusCode; +} + +- (NSDictionary * GTM_NULLABLE_TYPE)responseHeaders { + GTMSessionCheckNotSynchronized(self); + + NSURLResponse *response = self.response; + if ([response respondsToSelector:@selector(allHeaderFields)]) { + NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; + return headers; + } + return nil; +} + +- (NSDictionary * GTM_NULLABLE_TYPE)responseHeadersUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + if ([response respondsToSelector:@selector(allHeaderFields)]) { + NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; + return headers; + } + return nil; +} + +- (void)releaseCallbacks { + // Avoid releasing blocks in the sync section since objects dealloc'd by + // the blocks being released may call back into the fetcher or fetcher + // service. + dispatch_queue_t NS_VALID_UNTIL_END_OF_SCOPE holdCallbackQueue; + GTMSessionFetcherCompletionHandler NS_VALID_UNTIL_END_OF_SCOPE holdCompletionHandler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + holdCallbackQueue = _callbackQueue; + holdCompletionHandler = _completionHandler; + + _callbackQueue = nil; + _completionHandler = nil; // Setter overridden in upload. Setter assumed to be used externally. + } + + // Set local callback pointers to nil here rather than let them release at the end of the scope + // to make any problems due to the blocks being released be a bit more obvious in a stack trace. + holdCallbackQueue = nil; + holdCompletionHandler = nil; + + self.configurationBlock = nil; + self.didReceiveResponseBlock = nil; + self.challengeBlock = nil; + self.willRedirectBlock = nil; + self.sendProgressBlock = nil; + self.receivedProgressBlock = nil; + self.downloadProgressBlock = nil; + self.accumulateDataBlock = nil; + self.willCacheURLResponseBlock = nil; + self.retryBlock = nil; + self.testBlock = nil; + self.resumeDataBlock = nil; +} + +- (void)forgetSessionIdentifierForFetcher { + GTMSessionCheckSynchronized(self); + [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; +} + +- (void)forgetSessionIdentifierForFetcherWithoutSyncCheck { + // This should be called inside a @synchronized block (except during dealloc.) + if (_sessionIdentifier) { + NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; + [sessionIdentifierToFetcherMap removeObjectForKey:_sessionIdentifier]; + _sessionIdentifier = nil; + _didCreateSessionIdentifier = NO; + } +} + +// External stop method +- (void)stopFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Prevent enqueued callbacks from executing. + _userStoppedFetching = YES; + } // @synchronized(self) + [self stopFetchReleasingCallbacks:YES]; +} + +// Cancel the fetch of the URL that's currently in progress. +// +// If shouldReleaseCallbacks is NO then the fetch will be retried so the callbacks +// need to still be retained. +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { + [self removePersistedBackgroundSessionFromDefaults]; + + id service; + NSMutableURLRequest *request; + + // If the task or the retry timer is all that's retaining the fetcher, + // we want to be sure this instance survives stopping at least long enough for + // the stack to unwind. + __autoreleasing GTMSessionFetcher *holdSelf = self; + + BOOL hasCanceledTask = NO; + + [holdSelf destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _hasStoppedFetching = YES; + + service = _service; + request = _request; + + if (_sessionTask) { + // In case cancelling the task or session calls this recursively, we want + // to ensure that we'll only release the task and delegate once, + // so first set _sessionTask to nil + // + // This may be called in a callback from the task, so use autorelease to avoid + // releasing the task in its own callback. + __autoreleasing NSURLSessionTask *oldTask = _sessionTask; + if (!_isUsingTestBlock) { + _response = _sessionTask.response; + } + _sessionTask = nil; + + if ([oldTask state] != NSURLSessionTaskStateCompleted) { + // For download tasks, when the fetch is stopped, we may provide resume data that can + // be used to create a new session. + BOOL mayResume = (_resumeDataBlock + && [oldTask respondsToSelector:@selector(cancelByProducingResumeData:)]); + if (!mayResume) { + [oldTask cancel]; + // A side effect of stopping the task is that URLSession:task:didCompleteWithError: + // will be invoked asynchronously on the delegate queue. + } else { + void (^resumeBlock)(NSData *) = _resumeDataBlock; + _resumeDataBlock = nil; + + // Save callbackQueue since releaseCallbacks clears it. + dispatch_queue_t callbackQueue = _callbackQueue; + dispatch_group_enter(_callbackGroup); + [(NSURLSessionDownloadTask *)oldTask cancelByProducingResumeData:^(NSData *resumeData) { + [self invokeOnCallbackQueue:callbackQueue + afterUserStopped:YES + block:^{ + resumeBlock(resumeData); + dispatch_group_leave(self->_callbackGroup); + }]; + }]; + } + hasCanceledTask = YES; + } + } + + // If the task was canceled, wait until the URLSession:task:didCompleteWithError: to call + // finishTasksAndInvalidate, since calling it immediately tends to crash, see radar 18471901. + if (_session) { + BOOL shouldInvalidate = _shouldInvalidateSession; +#if TARGET_OS_IPHONE + // Don't invalidate if we've got a systemCompletionHandler, since + // URLSessionDidFinishEventsForBackgroundURLSession: won't be called if invalidated. + shouldInvalidate = shouldInvalidate && !self.systemCompletionHandler; +#endif + if (shouldInvalidate) { + __autoreleasing NSURLSession *oldSession = _session; + _session = nil; + + if (!hasCanceledTask) { + [oldSession finishTasksAndInvalidate]; + } else { + _sessionNeedingInvalidation = oldSession; + } + } + } + } // @synchronized(self) + + // send the stopped notification + [self sendStopNotificationIfNeeded]; + + [_authorizer stopAuthorizationForRequest:request]; + + if (shouldReleaseCallbacks) { + [self releaseCallbacks]; + + self.authorizer = nil; + } + + [service fetcherDidStop:self]; + +#if GTM_BACKGROUND_TASK_FETCHING + [self endBackgroundTask]; +#endif +} + +- (void)setStopNotificationNeeded:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _isStopNotificationNeeded = flag; + } // @synchronized(self) +} + +- (void)sendStopNotificationIfNeeded { + BOOL sendNow = NO; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_isStopNotificationNeeded) { + _isStopNotificationNeeded = NO; + sendNow = YES; + } + } // @synchronized(self) + + if (sendNow) { + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStoppedNotification + userInfo:nil + requireAsync:NO]; + } +} + +- (void)retryFetch { + [self stopFetchReleasingCallbacks:NO]; + + // A retry will need a configuration with a fresh session identifier. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionIdentifier && _didCreateSessionIdentifier) { + [self forgetSessionIdentifierForFetcher]; + _configuration = nil; + } + + if (_canShareSession) { + // Force a grab of the current session from the fetcher service in case + // the service's old one has become invalid. + _session = nil; + } + } // @synchronized(self) + + [self beginFetchForRetry]; +} + +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { + // Uncovered in upload fetcher testing, because the chunk fetcher is being waited on, and gets + // released by the upload code. The uploader just holds onto it with an ivar, and that gets + // nilled in the chunk fetcher callback. + // Used once in while loop just to avoid unused variable compiler warning. + __autoreleasing GTMSessionFetcher *holdSelf = self; + + NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + + BOOL shouldSpinRunLoop = ([NSThread isMainThread] && + (!self.callbackQueue + || self.callbackQueue == dispatch_get_main_queue())); + BOOL expired = NO; + + // Loop until the callbacks have been called and released, and until + // the connection is no longer pending, until there are no callback dispatches + // in flight, or until the timeout has expired. + int64_t delta = (int64_t)(100 * NSEC_PER_MSEC); // 100 ms + while (1) { + BOOL isTaskInProgress = (holdSelf->_sessionTask + && [_sessionTask state] != NSURLSessionTaskStateCompleted); + BOOL needsToCallCompletion = (_completionHandler != nil); + BOOL isCallbackInProgress = (_callbackGroup + && dispatch_group_wait(_callbackGroup, dispatch_time(DISPATCH_TIME_NOW, delta))); + + if (!isTaskInProgress && !needsToCallCompletion && !isCallbackInProgress) break; + + expired = ([giveUpDate timeIntervalSinceNow] < 0); + if (expired) { + GTMSESSION_LOG_DEBUG(@"GTMSessionFetcher waitForCompletionWithTimeout:%0.1f expired -- " + @"%@%@%@", timeoutInSeconds, + isTaskInProgress ? @"taskInProgress " : @"", + needsToCallCompletion ? @"needsToCallCompletion " : @"", + isCallbackInProgress ? @"isCallbackInProgress" : @""); + break; + } + + // Run the current run loop 1/1000 of a second to give the networking + // code a chance to work + const NSTimeInterval kSpinInterval = 0.001; + if (shouldSpinRunLoop) { + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + [NSThread sleepForTimeInterval:kSpinInterval]; + } + } + return !expired; +} + ++ (void)setGlobalTestBlock:(GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE)block { +#if GTM_DISABLE_FETCHER_TEST_BLOCK + GTMSESSION_ASSERT_DEBUG(block == nil, @"test blocks disabled"); +#endif + gGlobalTestBlock = [block copy]; +} + +#if GTM_BACKGROUND_TASK_FETCHING + +static GTM_NULLABLE_TYPE id gSubstituteUIApp; + ++ (void)setSubstituteUIApplication:(nullable id)app { + gSubstituteUIApp = app; +} + ++ (nullable id)substituteUIApplication { + return gSubstituteUIApp; +} + ++ (nullable id)fetcherUIApplication { + id app = gSubstituteUIApp; + if (app) return app; + + // iOS App extensions should not call [UIApplication sharedApplication], even + // if UIApplication responds to it. + + static Class applicationClass = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + BOOL isAppExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]; + if (!isAppExtension) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + }); + + if (applicationClass) { + app = (id)[applicationClass sharedApplication]; + } + return app; +} +#endif // GTM_BACKGROUND_TASK_FETCHING + +#pragma mark NSURLSession Delegate Methods + +// NSURLSession documentation indicates that redirectRequest can be passed to the handler +// but empirically redirectRequest lacks the HTTP body, so passing it will break POSTs. +// Instead, we construct a new request, a copy of the original, with overrides from the +// redirect. + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse + newRequest:(NSURLRequest *)redirectRequest + completionHandler:(void (^)(NSURLRequest * GTM_NULLABLE_TYPE))handler { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ willPerformHTTPRedirection:%@ newRequest:%@", + [self class], self, session, task, redirectResponse, redirectRequest); + + if ([self userStoppedFetching]) { + handler(nil); + return; + } + if (redirectRequest && redirectResponse) { + // Copy the original request, including the body. + NSURLRequest *originalRequest = self.request; + NSMutableURLRequest *newRequest = [originalRequest mutableCopy]; + + // The new requests's URL overrides the original's URL. + [newRequest setURL:[GTMSessionFetcher redirectURLWithOriginalRequestURL:originalRequest.URL + redirectRequestURL:redirectRequest.URL]]; + + // Any headers in the redirect override headers in the original. + NSDictionary *redirectHeaders = redirectRequest.allHTTPHeaderFields; + for (NSString *key in redirectHeaders) { + NSString *value = [redirectHeaders objectForKey:key]; + [newRequest setValue:value forHTTPHeaderField:key]; + } + + redirectRequest = newRequest; + + // Log the response we just received + [self setResponse:redirectResponse]; + [self logNowWithError:nil]; + + GTMSessionFetcherWillRedirectBlock willRedirectBlock = self.willRedirectBlock; + if (willRedirectBlock) { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + willRedirectBlock(redirectResponse, redirectRequest, ^(NSURLRequest *clientRequest) { + + // Update the request for future logging. + [self updateMutableRequest:[clientRequest mutableCopy]]; + + handler(clientRequest); + }); + }]; + } // @synchronized(self) + return; + } + // Continues here if the client did not provide a redirect block. + + // Update the request for future logging. + [self updateMutableRequest:[redirectRequest mutableCopy]]; + } + handler(redirectRequest); +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))handler { + [self setSessionTask:dataTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveResponse:%@", + [self class], self, session, dataTask, response); + void (^accumulateAndFinish)(NSURLSessionResponseDisposition) = + ^(NSURLSessionResponseDisposition dispositionValue) { + // This method is called when the server has determined that it + // has enough information to create the NSURLResponse + // it can be called multiple times, for example in the case of a + // redirect, so each time we reset the data. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL hadPreviousData = self->_downloadedLength > 0; + + [self->_downloadedData setLength:0]; + self->_downloadedLength = 0; + + if (hadPreviousData && (dispositionValue != NSURLSessionResponseCancel)) { + // Tell the accumulate block to discard prior data. + GTMSessionFetcherAccumulateDataBlock accumulateBlock = self->_accumulateDataBlock; + if (accumulateBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + accumulateBlock(nil); + }]; + } + } + } // @synchronized(self) + handler(dispositionValue); + }; + + GTMSessionFetcherDidReceiveResponseBlock receivedResponseBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + receivedResponseBlock = _didReceiveResponseBlock; + if (receivedResponseBlock) { + // We will ultimately need to call back to NSURLSession's handler with the disposition value + // for this delegate method even if the user has stopped the fetcher. + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + receivedResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { + accumulateAndFinish(desiredDisposition); + }); + }]; + } + } // @synchronized(self) + + if (receivedResponseBlock == nil) { + accumulateAndFinish(NSURLSessionResponseAllow); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didBecomeDownloadTask:%@", + [self class], self, session, dataTask, downloadTask); + [self setSessionTask:downloadTask]; +} + + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential))handler { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didReceiveChallenge:%@", + [self class], self, session, task, challenge); + + GTMSessionFetcherChallengeBlock challengeBlock = self.challengeBlock; + if (challengeBlock) { + // The fetcher user has provided custom challenge handling. + // + // We will ultimately need to call back to NSURLSession's handler with the disposition value + // for this delegate method even if the user has stopped the fetcher. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + challengeBlock(self, challenge, handler); + }]; + } + } else { + // No challenge block was provided by the client. + [self respondToChallenge:challenge + completionHandler:handler]; + } +} + +- (void)respondToChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential))handler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSInteger previousFailureCount = [challenge previousFailureCount]; + if (previousFailureCount <= 2) { + NSURLProtectionSpace *protectionSpace = [challenge protectionSpace]; + NSString *authenticationMethod = [protectionSpace authenticationMethod]; + if ([authenticationMethod isEqual:NSURLAuthenticationMethodServerTrust]) { + // SSL. + // + // Background sessions seem to require an explicit check of the server trust object + // rather than default handling. + SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; + if (serverTrust == NULL) { + // No server trust information is available. + handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } else { + // Server trust information is available. + void (^callback)(SecTrustRef, BOOL) = ^(SecTrustRef trustRef, BOOL allow){ + if (allow) { + NSURLCredential *trustCredential = [NSURLCredential credentialForTrust:trustRef]; + handler(NSURLSessionAuthChallengeUseCredential, trustCredential); + } else { + GTMSESSION_LOG_DEBUG(@"Cancelling authentication challenge for %@", self->_request.URL); + handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + }; + if (_allowInvalidServerCertificates) { + callback(serverTrust, YES); + } else { + [[self class] evaluateServerTrust:serverTrust + forRequest:_request + completionHandler:callback]; + } + } + return; + } + + NSURLCredential *credential = _credential; + + if ([[challenge protectionSpace] isProxy] && _proxyCredential != nil) { + credential = _proxyCredential; + } + + if (credential) { + handler(NSURLSessionAuthChallengeUseCredential, credential); + } else { + // The credential is still nil; tell the OS to use the default handling. This is needed + // for things that can come out of the keychain (proxies, client certificates, etc.). + // + // Note: Looking up a credential with NSURLCredentialStorage's + // defaultCredentialForProtectionSpace: is *not* the same invoking the handler with + // NSURLSessionAuthChallengePerformDefaultHandling. In the case of + // NSURLAuthenticationMethodClientCertificate, you can get nil back from + // NSURLCredentialStorage, while using this code path instead works. + handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } + + } else { + // We've failed auth 3 times. The completion handler will be called with code + // NSURLErrorCancelled. + handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + } // @synchronized(self) +} + +// Return redirect URL based on the original request URL and redirect request URL. +// +// Method disallows any scheme changes between the original request URL and redirect request URL +// aside from "http" to "https". If a change in scheme is detected the redirect URL inherits the +// scheme from the original request URL. ++ (GTM_NULLABLE NSURL *)redirectURLWithOriginalRequestURL:(GTM_NULLABLE NSURL *)originalRequestURL + redirectRequestURL:(GTM_NULLABLE NSURL *)redirectRequestURL { + // In the case of an NSURLSession redirect, neither URL should ever be nil; as a sanity check + // if either is nil return the other URL. + if (!redirectRequestURL) return originalRequestURL; + if (!originalRequestURL) return redirectRequestURL; + + NSString *originalScheme = originalRequestURL.scheme; + NSString *redirectScheme = redirectRequestURL.scheme; + BOOL insecureToSecureRedirect = + (originalScheme != nil && [originalScheme caseInsensitiveCompare:@"http"] == NSOrderedSame && + redirectScheme != nil && [redirectScheme caseInsensitiveCompare:@"https"] == NSOrderedSame); + + // Check for changes to the scheme and disallow any changes except for http to https. + if (!insecureToSecureRedirect && + (redirectScheme.length != originalScheme.length || + [redirectScheme caseInsensitiveCompare:originalScheme] != NSOrderedSame)) { + NSURLComponents *components = + [NSURLComponents componentsWithURL:(NSURL * _Nonnull)redirectRequestURL + resolvingAgainstBaseURL:NO]; + components.scheme = originalScheme; + return components.URL; + } + + return redirectRequestURL; +} + +// Validate the certificate chain. +// +// This may become a public method if it appears to be useful to users. ++ (void)evaluateServerTrust:(SecTrustRef)serverTrust + forRequest:(NSURLRequest *)request + completionHandler:(void (^)(SecTrustRef trustRef, BOOL allow))handler { + // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7. + CFRetain(serverTrust); + + // Evaluate the certificate chain. + // + // The delegate queue may be the main thread. Trust evaluation could cause some + // blocking network activity, so we must evaluate async, as documented at + // https://developer.apple.com/library/ios/technotes/tn2232/ + // + // We must also avoid multiple uses of the trust object, per docs: + // "It is not safe to call this function concurrently with any other function that uses + // the same trust management object, or to re-enter this function for the same trust + // management object." + // + // SecTrustEvaluateAsync both does sync execution of Evaluate and calls back on the + // queue passed to it, according to at sources in + // http://www.opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55050.9/lib/SecTrust.cpp + // It would require a global serial queue to ensure the evaluate happens only on a + // single thread at a time, so we'll stick with using SecTrustEvaluate on a background + // thread. + dispatch_queue_t evaluateBackgroundQueue = + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + dispatch_async(evaluateBackgroundQueue, ^{ + // It looks like the implementation of SecTrustEvaluate() on Mac grabs a global lock, + // so it may be redundant for us to also lock, but it's easy to synchronize here + // anyway. + SecTrustResultType trustEval = kSecTrustResultInvalid; + BOOL shouldAllow; + OSStatus trustError; + @synchronized([GTMSessionFetcher class]) { + GTMSessionMonitorSynchronized([GTMSessionFetcher class]); + + trustError = SecTrustEvaluate(serverTrust, &trustEval); + } + if (trustError != errSecSuccess) { + GTMSESSION_LOG_DEBUG(@"Error %d evaluating trust for %@", + (int)trustError, request); + shouldAllow = NO; + } else { + // Having a trust level "unspecified" by the user is the usual result, described at + // https://developer.apple.com/library/mac/qa/qa1360 + if (trustEval == kSecTrustResultUnspecified + || trustEval == kSecTrustResultProceed) { + shouldAllow = YES; + } else { + shouldAllow = NO; + GTMSESSION_LOG_DEBUG(@"Challenge SecTrustResultType %u for %@, properties: %@", + trustEval, request.URL.host, + CFBridgingRelease(SecTrustCopyProperties(serverTrust))); + } + } + handler(serverTrust, shouldAllow); + + CFRelease(serverTrust); + }); +} + +- (void)invokeOnCallbackQueueUnlessStopped:(void (^)(void))block { + [self invokeOnCallbackQueueAfterUserStopped:NO + block:block]; +} + +- (void)invokeOnCallbackQueueAfterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + GTMSessionCheckSynchronized(self); + + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:afterStopped + block:block]; +} + +- (void)invokeOnCallbackUnsynchronizedQueueAfterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + // testBlock simulation code may not be synchronizing when this is invoked. + [self invokeOnCallbackQueue:_callbackQueue + afterUserStopped:afterStopped + block:block]; +} + +- (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue + afterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + if (callbackQueue) { + dispatch_group_async(_callbackGroup, callbackQueue, ^{ + if (!afterStopped) { + NSDate *serviceStoppedAllDate = [self->_service stoppedAllFetchersDate]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Avoid a race between stopFetching and the callback. + if (self->_userStoppedFetching) { + return; + } + + // Also avoid calling back if the service has stopped all fetchers + // since this one was created. The fetcher may have stopped before + // stopAllFetchers was invoked, so _userStoppedFetching wasn't set, + // but the app still won't expect the callback to fire after + // the service's stopAllFetchers was invoked. + if (serviceStoppedAllDate + && [self->_initialBeginFetchDate compare:serviceStoppedAllDate] != NSOrderedDescending) { + // stopAllFetchers was called after this fetcher began. + return; + } + } // @synchronized(self) + } + block(); + }); + } +} + +- (void)invokeFetchCallbacksOnCallbackQueueWithData:(GTM_NULLABLE NSData *)data + error:(GTM_NULLABLE NSError *)error { + // Callbacks will be released in the method stopFetchReleasingCallbacks: + GTMSessionFetcherCompletionHandler handler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + handler = _completionHandler; + + if (handler) { + [self invokeOnCallbackQueueUnlessStopped:^{ + handler(data, error); + + // Post a notification, primarily to allow code to collect responses for + // testing. + // + // The observing code is not likely on the fetcher's callback + // queue, so this posts explicitly to the main queue. + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (data) { + userInfo[kGTMSessionFetcherCompletionDataKey] = data; + } + if (error) { + userInfo[kGTMSessionFetcherCompletionErrorKey] = error; + } + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherCompletionInvokedNotification + userInfo:userInfo + requireAsync:NO]; + }]; + } + } // @synchronized(self) +} + +- (void)postNotificationOnMainThreadWithName:(NSString *)noteName + userInfo:(GTM_NULLABLE NSDictionary *)userInfo + requireAsync:(BOOL)requireAsync { + dispatch_block_t postBlock = ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:noteName + object:self + userInfo:userInfo]; + }; + + if ([NSThread isMainThread] && !requireAsync) { + // Post synchronously for compatibility with older code using the fetcher. + + // Avoid calling out to other code from inside a sync block to avoid risk + // of a deadlock or of recursive sync. + GTMSessionCheckNotSynchronized(self); + + postBlock(); + } else { + dispatch_async(dispatch_get_main_queue(), postBlock); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)uploadTask + needNewBodyStream:(void (^)(NSInputStream * GTM_NULLABLE_TYPE bodyStream))completionHandler { + [self setSessionTask:uploadTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ needNewBodyStream:", + [self class], self, session, uploadTask); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSessionFetcherBodyStreamProvider provider = _bodyStreamProvider; +#if !STRIP_GTM_FETCH_LOGGING + if ([self respondsToSelector:@selector(loggedStreamProviderForStreamProvider:)]) { + provider = [self performSelector:@selector(loggedStreamProviderForStreamProvider:) + withObject:provider]; + } +#endif + if (provider) { + [self invokeOnCallbackQueueUnlessStopped:^{ + provider(completionHandler); + }]; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"NSURLSession expects a stream provider"); + + completionHandler(nil); + } + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didSendBodyData:%lld" + @" totalBytesSent:%lld totalBytesExpectedToSend:%lld", + [self class], self, session, task, bytesSent, totalBytesSent, + totalBytesExpectedToSend); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (!_sendProgressBlock) { + return; + } + // We won't hold on to send progress block; it's ok to not send it if the upload finishes. + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherSendProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = self->_sendProgressBlock; + } + if (progressBlock) { + progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); + } + }]; + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { + [self setSessionTask:dataTask]; + NSUInteger bufferLength = data.length; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveData:%p (%llu bytes)", + [self class], self, session, dataTask, data, + (unsigned long long)bufferLength); + if (bufferLength == 0) { + // Observed on completing an out-of-process upload. + return; + } + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock; + if (accumulateBlock) { + // Let the client accumulate the data. + _downloadedLength += bufferLength; + [self invokeOnCallbackQueueUnlessStopped:^{ + accumulateBlock(data); + }]; + } else if (!_userStoppedFetching) { + // Append to the mutable data buffer unless the fetch has been cancelled. + + // Resumed upload tasks may not yet have a data buffer. + if (_downloadedData == nil) { + // Using NSClassFromString for iOS 6 compatibility. + GTMSESSION_ASSERT_DEBUG( + ![dataTask isKindOfClass:NSClassFromString(@"NSURLSessionDownloadTask")], + @"Resumed download tasks should not receive data bytes"); + _downloadedData = [[NSMutableData alloc] init]; + } + + [_downloadedData appendData:data]; + _downloadedLength = (int64_t)_downloadedData.length; + + // We won't hold on to receivedProgressBlock here; it's ok to not send + // it if the transfer finishes. + if (_receivedProgressBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherReceivedProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = self->_receivedProgressBlock; + } + if (progressBlock) { + progressBlock((int64_t)bufferLength, self->_downloadedLength); + } + }]; + } + } + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ willCacheResponse:%@ %@", + [self class], self, session, dataTask, + proposedResponse, proposedResponse.response); + GTMSessionFetcherWillCacheURLResponseBlock callback; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + callback = _willCacheURLResponseBlock; + + if (callback) { + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + callback(proposedResponse, completionHandler); + }]; + } + } // @synchronized(self) + if (!callback) { + completionHandler(proposedResponse); + } +} + + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didWriteData:%lld" + @" bytesWritten:%lld totalBytesExpectedToWrite:%lld", + [self class], self, session, downloadTask, bytesWritten, + totalBytesWritten, totalBytesExpectedToWrite); + [self setSessionTask:downloadTask]; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if ((totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown) && + (totalBytesExpectedToWrite < totalBytesWritten)) { + // Have observed cases were bytesWritten == totalBytesExpectedToWrite, + // but totalBytesWritten > totalBytesExpectedToWrite, so setting to unkown in these cases. + totalBytesExpectedToWrite = NSURLSessionTransferSizeUnknown; + } + // We won't hold on to download progress block during the enqueue; + // it's ok to not send it if the upload finishes. + + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherDownloadProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = self->_downloadProgressBlock; + } + if (progressBlock) { + progressBlock(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } + }]; + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didResumeAtOffset:%lld" + @" expectedTotalBytes:%lld", + [self class], self, session, downloadTask, fileOffset, + expectedTotalBytes); + [self setSessionTask:downloadTask]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)downloadLocationURL { + // Download may have relaunched app, so update _sessionTask. + [self setSessionTask:downloadTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didFinishDownloadingToURL:%@", + [self class], self, session, downloadTask, downloadLocationURL); + NSNumber *fileSizeNum; + [downloadLocationURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:NULL]; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURL *destinationURL = _destinationFileURL; + + _downloadedLength = fileSizeNum.longLongValue; + + // Overwrite any previous file at the destination URL. + NSFileManager *fileMgr = [NSFileManager defaultManager]; + NSError *removeError; + if (![fileMgr removeItemAtURL:destinationURL error:&removeError] + && removeError.code != NSFileNoSuchFileError) { + GTMSESSION_LOG_DEBUG(@"Could not remove previous file at %@ due to %@", + downloadLocationURL.path, removeError); + } + + NSInteger statusCode = [self statusCodeUnsynchronized]; + if (statusCode < 200 || statusCode > 399) { + // In OS X 10.11, the response body is written to a file even on a server + // status error. For convenience of the fetcher client, we'll skip saving the + // downloaded body to the destination URL so that clients do not need to know + // to delete the file following fetch errors. + GTMSESSION_LOG_DEBUG(@"Abandoning download due to status %ld, file %@", + (long)statusCode, downloadLocationURL.path); + + // On error code, add the contents of the temporary file to _downloadTaskErrorData + // This way fetcher clients have access to error details possibly passed by the server. + if (_downloadedLength > 0 && _downloadedLength <= kMaximumDownloadErrorDataLength) { + _downloadTaskErrorData = [NSData dataWithContentsOfURL:downloadLocationURL]; + } else if (_downloadedLength > kMaximumDownloadErrorDataLength) { + GTMSESSION_LOG_DEBUG(@"Download error data for file %@ not passed to userInfo due to size " + @"%lld", downloadLocationURL.path, _downloadedLength); + } + } else { + NSError *moveError; + NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; + BOOL didMoveDownload = NO; + if ([fileMgr createDirectoryAtURL:destinationFolderURL + withIntermediateDirectories:YES + attributes:nil + error:&moveError]) { + didMoveDownload = [fileMgr moveItemAtURL:downloadLocationURL + toURL:destinationURL + error:&moveError]; + } + if (!didMoveDownload) { + _downloadFinishedError = moveError; + } + GTM_LOG_BACKGROUND_SESSION(@"%@ %p Moved download from \"%@\" to \"%@\" %@", + [self class], self, + downloadLocationURL.path, destinationURL.path, + error ? error : @""); + } + } // @synchronized(self) +} + +/* Sent as the last message related to a specific task. Error may be + * nil, which implies that no error occurred and this task is complete. + */ +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didCompleteWithError:%@", + [self class], self, session, task, error); + + NSInteger status = self.statusCode; + BOOL forceAssumeRetry = NO; + BOOL succeeded = NO; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + // The task is never resumed when a testBlock is used. When the session is destroyed, + // we should ignore the callback, since the testBlock support code itself invokes + // shouldRetryNowForStatus: and finishWithError:shouldRetry: + if (_isUsingTestBlock) return; +#endif + + if (error == nil) { + error = _downloadFinishedError; + } + succeeded = (error == nil && status >= 0 && status < 300); + if (succeeded) { + // Succeeded. + _bodyLength = task.countOfBytesSent; + } + } // @synchronized(self) + + if (succeeded) { + [self finishWithError:nil shouldRetry:NO]; + return; + } + // For background redirects, no delegate method is called, so we cannot restore a stripped + // Authorization header, so if a 403 ("Forbidden") was generated due to a missing OAuth 2 header, + // set the current request's URL to the redirected URL, so we in effect restore the Authorization + // header. + if ((status == 403) && self.usingBackgroundSession) { + NSURL *redirectURL = self.response.URL; + NSURLRequest *request = self.request; + if (![request.URL isEqual:redirectURL]) { + NSString *authorizationHeader = [request.allHTTPHeaderFields objectForKey:@"Authorization"]; + if (authorizationHeader != nil) { + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.URL = redirectURL; + [self updateMutableRequest:mutableRequest]; + // Avoid assuming the session is still valid. + self.session = nil; + forceAssumeRetry = YES; + } + } + } + + // If invalidating the session was deferred in stopFetchReleasingCallbacks: then do it now. + NSURLSession *oldSession = self.sessionNeedingInvalidation; + if (oldSession) { + [self setSessionNeedingInvalidation:NULL]; + [oldSession finishTasksAndInvalidate]; + } + + // Failed. + [self shouldRetryNowForStatus:status + error:error + forceAssumeRetry:forceAssumeRetry + response:^(BOOL shouldRetry) { + [self finishWithError:error shouldRetry:shouldRetry]; + }]; +} + +#if TARGET_OS_IPHONE +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSessionDidFinishEventsForBackgroundURLSession:%@", + [self class], self, session); + [self removePersistedBackgroundSessionFromDefaults]; + + GTMSessionFetcherSystemCompletionHandler handler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + handler = self.systemCompletionHandler; + self.systemCompletionHandler = nil; + } // @synchronized(self) + if (handler) { + GTM_LOG_BACKGROUND_SESSION(@"%@ %p Calling system completionHandler", [self class], self); + handler(); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLSession *oldSession = _session; + _session = nil; + if (_shouldInvalidateSession) { + [oldSession finishTasksAndInvalidate]; + } + } // @synchronized(self) + } +} +#endif + +- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(GTM_NULLABLE NSError *)error { + // This may happen repeatedly for retries. On authentication callbacks, the retry + // may begin before the prior session sends the didBecomeInvalid delegate message. + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", + [self class], self, session, error); + if (session == (NSURLSession *)self.session) { + GTM_LOG_SESSION_DELEGATE(@" Unexpected retained invalid session: %@", session); + self.session = nil; + } +} + +- (void)finishWithError:(GTM_NULLABLE NSError *)error shouldRetry:(BOOL)shouldRetry { + [self removePersistedBackgroundSessionFromDefaults]; + + BOOL shouldStopFetching = YES; + NSData *downloadedData = nil; +#if !STRIP_GTM_FETCH_LOGGING + BOOL shouldDeferLogging = NO; +#endif + BOOL shouldBeginRetryTimer = NO; + NSInteger status = [self statusCode]; + NSURL *destinationURL = self.destinationFileURL; + + BOOL fetchSucceeded = (error == nil && status >= 0 && status < 300); + +#if !STRIP_GTM_FETCH_LOGGING + if (!fetchSucceeded) { + if (!shouldDeferLogging && !self.hasLoggedError) { + [self logNowWithError:error]; + self.hasLoggedError = YES; + } + } +#endif // !STRIP_GTM_FETCH_LOGGING + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + +#if !STRIP_GTM_FETCH_LOGGING + shouldDeferLogging = _deferResponseBodyLogging; +#endif + if (fetchSucceeded) { + // Success + if ((_downloadedData.length > 0) && (destinationURL != nil)) { + // Overwrite any previous file at the destination URL. + NSFileManager *fileMgr = [NSFileManager defaultManager]; + [fileMgr removeItemAtURL:destinationURL + error:NULL]; + NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; + BOOL didMoveDownload = NO; + if ([fileMgr createDirectoryAtURL:destinationFolderURL + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + didMoveDownload = [_downloadedData writeToURL:destinationURL + options:NSDataWritingAtomic + error:&error]; + } + if (didMoveDownload) { + _downloadedData = nil; + } else { + _downloadFinishedError = error; + } + } + downloadedData = _downloadedData; + } else { + // Unsuccessful with error or status over 300. Retry or notify the delegate of failure + if (shouldRetry) { + // Retrying. + shouldBeginRetryTimer = YES; + shouldStopFetching = NO; + } else { + if (error == nil) { + // Create an error. + NSDictionary *userInfo = GTMErrorUserInfoForData( + _downloadedData.length > 0 ? _downloadedData : _downloadTaskErrorData, + [self responseHeadersUnsynchronized]); + + error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:status + userInfo:userInfo]; + } else { + // If the error had resume data, and the client supplied a resume block, pass the + // data to the client. + void (^resumeBlock)(NSData *) = _resumeDataBlock; + _resumeDataBlock = nil; + if (resumeBlock) { + NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]; + if (resumeData) { + [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ + resumeBlock(resumeData); + }]; + } + } + } + if (_downloadedData.length > 0) { + downloadedData = _downloadedData; + } + // If the error occurred after retries, report the number and duration of the + // retries. This provides a clue to a developer looking at the error description + // that the fetcher did retry before failing with this error. + if (_retryCount > 0) { + NSMutableDictionary *userInfoWithRetries = + [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)error.userInfo]; + NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; + [userInfoWithRetries setObject:@(timeSinceInitialRequest) + forKey:kGTMSessionFetcherElapsedIntervalWithRetriesKey]; + [userInfoWithRetries setObject:@(_retryCount) + forKey:kGTMSessionFetcherNumberOfRetriesDoneKey]; + error = [NSError errorWithDomain:(NSString *)error.domain + code:error.code + userInfo:userInfoWithRetries]; + } + } + } + } // @synchronized(self) + + if (shouldBeginRetryTimer) { + [self beginRetryTimer]; + } + + // We want to send the stop notification before calling the delegate's + // callback selector, since the callback selector may release all of + // the fetcher properties that the client is using to track the fetches. + // + // We'll also stop now so that, to any observers watching the notifications, + // it doesn't look like our wait for a retry (which may be long, + // 30 seconds or more) is part of the network activity. + [self sendStopNotificationIfNeeded]; + + if (shouldStopFetching) { + [self invokeFetchCallbacksOnCallbackQueueWithData:downloadedData + error:error]; + // The upload subclass doesn't want to release callbacks until upload chunks have completed. + BOOL shouldRelease = [self shouldReleaseCallbacksUponCompletion]; + [self stopFetchReleasingCallbacks:shouldRelease]; + } + +#if !STRIP_GTM_FETCH_LOGGING + // _hasLoggedError is only set by this method + if (!shouldDeferLogging && !_hasLoggedError) { + [self logNowWithError:error]; + } +#endif +} + +- (BOOL)shouldReleaseCallbacksUponCompletion { + // A subclass can override this to keep callbacks around after the + // connection has finished successfully + return YES; +} + +- (void)logNowWithError:(GTM_NULLABLE NSError *)error { + GTMSessionCheckNotSynchronized(self); + + // If the logging category is available, then log the current request, + // response, data, and error + if ([self respondsToSelector:@selector(logFetchWithError:)]) { + [self performSelector:@selector(logFetchWithError:) withObject:error]; + } +} + +#pragma mark Retries + +- (BOOL)isRetryError:(NSError *)error { + struct RetryRecord { + __unsafe_unretained NSString *const domain; + NSInteger code; + }; + + struct RetryRecord retries[] = { + { kGTMSessionFetcherStatusDomain, 408 }, // request timeout + { kGTMSessionFetcherStatusDomain, 502 }, // failure gatewaying to another server + { kGTMSessionFetcherStatusDomain, 503 }, // service unavailable + { kGTMSessionFetcherStatusDomain, 504 }, // request timeout + { NSURLErrorDomain, NSURLErrorTimedOut }, + { NSURLErrorDomain, NSURLErrorNetworkConnectionLost }, + { nil, 0 } + }; + + // NSError's isEqual always returns false for equal but distinct instances + // of NSError, so we have to compare the domain and code values explicitly + NSString *domain = error.domain; + NSInteger code = error.code; + for (int idx = 0; retries[idx].domain != nil; idx++) { + if (code == retries[idx].code && [domain isEqual:retries[idx].domain]) { + return YES; + } + } + return NO; +} + +// shouldRetryNowForStatus:error: responds with YES if the user has enabled retries +// and the status or error is one that is suitable for retrying. "Suitable" +// means either the isRetryError:'s list contains the status or error, or the +// user's retry block is present and returns YES when called, or the +// authorizer may be able to fix. +- (void)shouldRetryNowForStatus:(NSInteger)status + error:(NSError *)error + forceAssumeRetry:(BOOL)forceAssumeRetry + response:(GTMSessionFetcherRetryResponse)response { + // Determine if a refreshed authorizer may avoid an authorization error + BOOL willRetry = NO; + + // We assume _authorizer is immutable after beginFetch, and _hasAttemptedAuthRefresh is modified + // only in this method, and this method is invoked on the serial delegate queue. + // + // We want to avoid calling the authorizer from inside a sync block. + BOOL isFirstAuthError = (_authorizer != nil + && !_hasAttemptedAuthRefresh + && status == GTMSessionFetcherStatusUnauthorized); // 401 + + BOOL hasPrimed = NO; + if (isFirstAuthError) { + if ([_authorizer respondsToSelector:@selector(primeForRefresh)]) { + hasPrimed = [_authorizer primeForRefresh]; + } + } + + BOOL shouldRetryForAuthRefresh = NO; + if (hasPrimed) { + shouldRetryForAuthRefresh = YES; + _hasAttemptedAuthRefresh = YES; + [self updateRequestValue:nil forHTTPHeaderField:@"Authorization"]; + } + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL shouldDoRetry = [self isRetryEnabledUnsynchronized]; + if (shouldDoRetry && ![self hasRetryAfterInterval]) { + + // Determine if we're doing exponential backoff retries + shouldDoRetry = [self nextRetryIntervalUnsynchronized] < _maxRetryInterval; + + if (shouldDoRetry) { + // If an explicit max retry interval was set, we expect repeated backoffs to take + // up to roughly twice that for repeated fast failures. If the initial attempt is + // already more than 3 times the max retry interval, then failures have taken a long time + // (such as from network timeouts) so don't retry again to avoid the app becoming + // unexpectedly unresponsive. + if (_maxRetryInterval > 0) { + NSTimeInterval maxAllowedIntervalBeforeRetry = _maxRetryInterval * 3; + NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; + if (timeSinceInitialRequest > maxAllowedIntervalBeforeRetry) { + shouldDoRetry = NO; + } + } + } + } + BOOL canRetry = shouldRetryForAuthRefresh || forceAssumeRetry || shouldDoRetry; + if (canRetry) { + NSDictionary *userInfo = + GTMErrorUserInfoForData(_downloadedData, [self responseHeadersUnsynchronized]); + NSError *statusError = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:status + userInfo:userInfo]; + if (error == nil) { + error = statusError; + } + willRetry = shouldRetryForAuthRefresh || + forceAssumeRetry || + [self isRetryError:error] || + ((error != statusError) && [self isRetryError:statusError]); + + // If the user has installed a retry callback, consult that. + GTMSessionFetcherRetryBlock retryBlock = _retryBlock; + if (retryBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + retryBlock(willRetry, error, response); + }]; + return; + } + } + } // @synchronized(self) + response(willRetry); +} + +- (BOOL)hasRetryAfterInterval { + GTMSessionCheckSynchronized(self); + + NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; + NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; + return (retryAfterValue != nil); +} + +- (NSTimeInterval)retryAfterInterval { + GTMSessionCheckSynchronized(self); + + NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; + NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; + if (retryAfterValue == nil) { + return 0; + } + // Retry-After formatted as HTTP-date | delta-seconds + // Reference: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + NSDateFormatter *rfc1123DateFormatter = [[NSDateFormatter alloc] init]; + rfc1123DateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; + rfc1123DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; + rfc1123DateFormatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z"; + NSDate *retryAfterDate = [rfc1123DateFormatter dateFromString:retryAfterValue]; + NSTimeInterval retryAfterInterval = (retryAfterDate != nil) ? + retryAfterDate.timeIntervalSinceNow : retryAfterValue.intValue; + retryAfterInterval = MAX(0, retryAfterInterval); + return retryAfterInterval; +} + +- (void)beginRetryTimer { + if (![NSThread isMainThread]) { + // Defer creating and starting the timer until we're on the main thread to ensure it has + // a run loop. + dispatch_group_async(_callbackGroup, dispatch_get_main_queue(), ^{ + [self beginRetryTimer]; + }); + return; + } + + [self destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSTimeInterval nextInterval = [self nextRetryIntervalUnsynchronized]; + NSTimeInterval maxInterval = _maxRetryInterval; + NSTimeInterval newInterval = MIN(nextInterval, (maxInterval > 0 ? maxInterval : DBL_MAX)); + NSTimeInterval newIntervalTolerance = (newInterval / 10) > 1.0 ?: 1.0; + + _lastRetryInterval = newInterval; + + _retryTimer = [NSTimer timerWithTimeInterval:newInterval + target:self + selector:@selector(retryTimerFired:) + userInfo:nil + repeats:NO]; + _retryTimer.tolerance = newIntervalTolerance; + [[NSRunLoop mainRunLoop] addTimer:_retryTimer + forMode:NSDefaultRunLoopMode]; + } // @synchronized(self) + + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStartedNotification + userInfo:nil + requireAsync:NO]; +} + +- (void)retryTimerFired:(NSTimer *)timer { + [self destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _retryCount++; + } // @synchronized(self) + + NSOperationQueue *queue = self.sessionDelegateQueue; + [queue addOperationWithBlock:^{ + [self retryFetch]; + }]; +} + +- (void)destroyRetryTimer { + BOOL shouldNotify = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_retryTimer) { + [_retryTimer invalidate]; + _retryTimer = nil; + shouldNotify = YES; + } + } + + if (shouldNotify) { + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStoppedNotification + userInfo:nil + requireAsync:NO]; + } +} + +- (NSUInteger)retryCount { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _retryCount; + } // @synchronized(self) +} + +- (NSTimeInterval)nextRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSTimeInterval interval = [self nextRetryIntervalUnsynchronized]; + return interval; + } // @synchronized(self) +} + +- (NSTimeInterval)nextRetryIntervalUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSInteger statusCode = [self statusCodeUnsynchronized]; + if ((statusCode == 503) && [self hasRetryAfterInterval]) { + NSTimeInterval secs = [self retryAfterInterval]; + return secs; + } + // The next wait interval is the factor (2.0) times the last interval, + // but never less than the minimum interval. + NSTimeInterval secs = _lastRetryInterval * _retryFactor; + if (_maxRetryInterval > 0) { + secs = MIN(secs, _maxRetryInterval); + } + secs = MAX(secs, _minRetryInterval); + + return secs; +} + +- (NSTimer *)retryTimer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _retryTimer; + } // @synchronized(self) +} + +- (BOOL)isRetryEnabled { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isRetryEnabled; + } // @synchronized(self) +} + +- (BOOL)isRetryEnabledUnsynchronized { + GTMSessionCheckSynchronized(self); + + return _isRetryEnabled; +} + +- (void)setRetryEnabled:(BOOL)flag { + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag && !_isRetryEnabled) { + // We defer initializing these until the user calls setRetryEnabled + // to avoid using the random number generator if it's not needed. + // However, this means min and max intervals for this fetcher are reset + // as a side effect of calling setRetryEnabled. + // + // Make an initial retry interval random between 1.0 and 2.0 seconds + _minRetryInterval = InitialMinRetryInterval(); + _maxRetryInterval = kUnsetMaxRetryInterval; + _retryFactor = 2.0; + _lastRetryInterval = 0.0; + } + _isRetryEnabled = flag; + } // @synchronized(self) +}; + +- (NSTimeInterval)maxRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _maxRetryInterval; + } // @synchronized(self) +} + +- (void)setMaxRetryInterval:(NSTimeInterval)secs { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (secs > 0) { + _maxRetryInterval = secs; + } else { + _maxRetryInterval = kUnsetMaxRetryInterval; + } + } // @synchronized(self) +} + +- (double)minRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _minRetryInterval; + } // @synchronized(self) +} + +- (void)setMinRetryInterval:(NSTimeInterval)secs { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (secs > 0) { + _minRetryInterval = secs; + } else { + // Set min interval to a random value between 1.0 and 2.0 seconds + // so that if multiple clients start retrying at the same time, they'll + // repeat at different times and avoid overloading the server + _minRetryInterval = InitialMinRetryInterval(); + } + } // @synchronized(self) + +} + +#pragma mark iOS System Completion Handlers + +#if TARGET_OS_IPHONE +static NSMutableDictionary *gSystemCompletionHandlers = nil; + +- (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { + return [[self class] systemCompletionHandlerForSessionIdentifier:_sessionIdentifier]; +} + +- (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { + [[self class] setSystemCompletionHandler:systemCompletionHandler + forSessionIdentifier:_sessionIdentifier]; +} + ++ (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler + forSessionIdentifier:(NSString *)sessionIdentifier { + if (!sessionIdentifier) { + NSLog(@"%s with nil identifier", __PRETTY_FUNCTION__); + return; + } + + @synchronized([GTMSessionFetcher class]) { + if (gSystemCompletionHandlers == nil && systemCompletionHandler != nil) { + gSystemCompletionHandlers = [[NSMutableDictionary alloc] init]; + } + // Use setValue: to remove the object if completionHandler is nil. + [gSystemCompletionHandlers setValue:systemCompletionHandler + forKey:sessionIdentifier]; + } +} + ++ (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandlerForSessionIdentifier:(NSString *)sessionIdentifier { + if (!sessionIdentifier) { + return nil; + } + @synchronized([GTMSessionFetcher class]) { + return [gSystemCompletionHandlers objectForKey:sessionIdentifier]; + } +} +#endif // TARGET_OS_IPHONE + +#pragma mark Getters and Setters + +@synthesize downloadResumeData = _downloadResumeData, + configuration = _configuration, + configurationBlock = _configurationBlock, + sessionTask = _sessionTask, + wasCreatedFromBackgroundSession = _wasCreatedFromBackgroundSession, + sessionUserInfo = _sessionUserInfo, + taskDescription = _taskDescription, + taskPriority = _taskPriority, + usingBackgroundSession = _usingBackgroundSession, + canShareSession = _canShareSession, + completionHandler = _completionHandler, + credential = _credential, + proxyCredential = _proxyCredential, + bodyData = _bodyData, + bodyLength = _bodyLength, + service = _service, + serviceHost = _serviceHost, + accumulateDataBlock = _accumulateDataBlock, + receivedProgressBlock = _receivedProgressBlock, + downloadProgressBlock = _downloadProgressBlock, + resumeDataBlock = _resumeDataBlock, + didReceiveResponseBlock = _didReceiveResponseBlock, + challengeBlock = _challengeBlock, + willRedirectBlock = _willRedirectBlock, + sendProgressBlock = _sendProgressBlock, + willCacheURLResponseBlock = _willCacheURLResponseBlock, + retryBlock = _retryBlock, + retryFactor = _retryFactor, + allowedInsecureSchemes = _allowedInsecureSchemes, + allowLocalhostRequest = _allowLocalhostRequest, + allowInvalidServerCertificates = _allowInvalidServerCertificates, + cookieStorage = _cookieStorage, + callbackQueue = _callbackQueue, + initialBeginFetchDate = _initialBeginFetchDate, + testBlock = _testBlock, + testBlockAccumulateDataChunkCount = _testBlockAccumulateDataChunkCount, + comment = _comment, + log = _log; + +#if !STRIP_GTM_FETCH_LOGGING +@synthesize redirectedFromURL = _redirectedFromURL, + logRequestBody = _logRequestBody, + logResponseBody = _logResponseBody, + hasLoggedError = _hasLoggedError; +#endif + +#if GTM_BACKGROUND_TASK_FETCHING +@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier, + skipBackgroundTask = _skipBackgroundTask; +#endif + +- (GTM_NULLABLE NSURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_request copy]; + } // @synchronized(self) +} + +- (void)setRequest:(GTM_NULLABLE NSURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (![self isFetchingUnsynchronized]) { + _request = [request mutableCopy]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSMutableURLRequest *)mutableRequestForTesting { + // Allow tests only to modify the request, useful during retries. + return _request; +} + +// Internal method for updating the request property such as on redirects. +- (void)updateMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _request = request; + } // @synchronized(self) +} + +// Set a header field value on the request. Header field value changes will not +// affect a fetch after the fetch has begun. +- (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { + if (![self isFetching]) { + [self updateRequestValue:value forHTTPHeaderField:field]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); + } +} + +// Internal method for updating request headers. +- (void)updateRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_request setValue:value forHTTPHeaderField:field]; + } // @synchronized(self) +} + +- (void)setResponse:(GTM_NULLABLE NSURLResponse *)response { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _response = response; + } // @synchronized(self) +} + +- (int64_t)bodyLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_bodyLength == NSURLSessionTransferSizeUnknown) { + if (_bodyData) { + _bodyLength = (int64_t)_bodyData.length; + } else if (_bodyFileURL) { + NSNumber *fileSizeNum = nil; + NSError *fileSizeError = nil; + if ([_bodyFileURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:&fileSizeError]) { + _bodyLength = [fileSizeNum longLongValue]; + } + } + } + return _bodyLength; + } // @synchronized(self) +} + +- (BOOL)useUploadTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _useUploadTask; + } // @synchronized(self) +} + +- (void)setUseUploadTask:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag != _useUploadTask) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"useUploadTask should not change after beginFetch has been invoked"); + _useUploadTask = flag; + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURL *)bodyFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _bodyFileURL; + } // @synchronized(self) +} + +- (void)setBodyFileURL:(GTM_NULLABLE NSURL *)fileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // The comparison here is a trivial optimization and forgiveness for any client that + // repeatedly sets the property, so it just uses pointer comparison rather than isEqual:. + if (fileURL != _bodyFileURL) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"fileURL should not change after beginFetch has been invoked"); + + _bodyFileURL = fileURL; + } + } // @synchronized(self) +} + +- (GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)bodyStreamProvider { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _bodyStreamProvider; + } // @synchronized(self) +} + +- (void)setBodyStreamProvider:(GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)block { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"stream provider should not change after beginFetch has been invoked"); + + _bodyStreamProvider = [block copy]; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _authorizer; + } // @synchronized(self) +} + +- (void)setAuthorizer:(GTM_NULLABLE id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (authorizer != _authorizer) { + if ([self isFetchingUnsynchronized]) { + GTMSESSION_ASSERT_DEBUG(0, @"authorizer should not change after beginFetch has been invoked"); + } else { + _authorizer = authorizer; + } + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSData *)downloadedData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _downloadedData; + } // @synchronized(self) +} + +- (void)setDownloadedData:(GTM_NULLABLE NSData *)data { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _downloadedData = [data mutableCopy]; + } // @synchronized(self) +} + +- (int64_t)downloadedLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _downloadedLength; + } // @synchronized(self) +} + +- (void)setDownloadedLength:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _downloadedLength = length; + } // @synchronized(self) +} + +- (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _callbackQueue; + } // @synchronized(self) +} + +- (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _callbackQueue = queue ?: dispatch_get_main_queue(); + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _session; + } // @synchronized(self) +} + +- (NSInteger)servicePriority { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _servicePriority; + } // @synchronized(self) +} + +- (void)setServicePriority:(NSInteger)value { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (value != _servicePriority) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"servicePriority should not change after beginFetch has been invoked"); + + _servicePriority = value; + } + } // @synchronized(self) +} + + +- (void)setSession:(GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = session; + } // @synchronized(self) +} + +- (BOOL)canShareSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _canShareSession; + } // @synchronized(self) +} + +- (void)setCanShareSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _canShareSession = flag; + } // @synchronized(self) +} + +- (BOOL)useBackgroundSession { + // This reflects if the user requested a background session, not necessarily + // if one was created. That is tracked with _usingBackgroundSession. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userRequestedBackgroundSession; + } // @synchronized(self) +} + +- (void)setUseBackgroundSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag != _userRequestedBackgroundSession) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"useBackgroundSession should not change after beginFetch has been invoked"); + + _userRequestedBackgroundSession = flag; + } + } // @synchronized(self) +} + +- (BOOL)isUsingBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _usingBackgroundSession; + } // @synchronized(self) +} + +- (void)setUsingBackgroundSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _usingBackgroundSession = flag; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURLSession *)sessionNeedingInvalidation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionNeedingInvalidation; + } // @synchronized(self) +} + +- (void)setSessionNeedingInvalidation:(GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _sessionNeedingInvalidation = session; + } // @synchronized(self) +} + +- (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateQueue; + } // @synchronized(self) +} + +- (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (queue != _delegateQueue) { + if ([self isFetchingUnsynchronized]) { + GTMSESSION_ASSERT_DEBUG(0, @"sessionDelegateQueue should not change after fetch begins"); + } else { + _delegateQueue = queue ?: [NSOperationQueue mainQueue]; + } + } + } // @synchronized(self) +} + +- (BOOL)userStoppedFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userStoppedFetching; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)userData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userData; + } // @synchronized(self) +} + +- (void)setUserData:(GTM_NULLABLE id)theObj { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _userData = theObj; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURL *)destinationFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _destinationFileURL; + } // @synchronized(self) +} + +- (void)setDestinationFileURL:(GTM_NULLABLE NSURL *)destinationFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (((_destinationFileURL == nil) && (destinationFileURL == nil)) || + [_destinationFileURL isEqual:destinationFileURL]) { + return; + } + if (_sessionIdentifier) { + // This is something we don't expect to happen in production. + // However if it ever happen, leave a system log. + NSLog(@"%@: Destination File URL changed from (%@) to (%@) after session identifier has " + @"been created.", + [self class], _destinationFileURL, destinationFileURL); +#if DEBUG + // On both the simulator and devices, the path can change to the download file, but the name + // shouldn't change. Technically, this isn't supported in the fetcher, but the change of + // URL is expected to happen only across development runs through Xcode. + NSString *oldFilename = [_destinationFileURL lastPathComponent]; + NSString *newFilename = [destinationFileURL lastPathComponent]; + #pragma unused(oldFilename) + #pragma unused(newFilename) + GTMSESSION_ASSERT_DEBUG([oldFilename isEqualToString:newFilename], + @"Destination File URL cannot be changed after session identifier has been created"); +#endif + } + _destinationFileURL = destinationFileURL; + } // @synchronized(self) +} + +- (void)setProperties:(GTM_NULLABLE NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _properties = [dict mutableCopy]; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSDictionary *)properties { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _properties; + } // @synchronized(self) +} + +- (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_properties == nil && obj != nil) { + _properties = [[NSMutableDictionary alloc] init]; + } + [_properties setValue:obj forKey:key]; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)propertyForKey:(NSString *)key { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_properties objectForKey:key]; + } // @synchronized(self) +} + +- (void)addPropertiesFromDictionary:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_properties == nil && dict != nil) { + [self setProperties:[dict mutableCopy]]; + } else { + [_properties addEntriesFromDictionary:dict]; + } + } // @synchronized(self) +} + +- (void)setCommentWithFormat:(id)format, ... { +#if !STRIP_GTM_FETCH_LOGGING + NSString *result = format; + if (format) { + va_list argList; + va_start(argList, format); + + result = [[NSString alloc] initWithFormat:format + arguments:argList]; + va_end(argList); + } + [self setComment:result]; +#endif +} + +#if !STRIP_GTM_FETCH_LOGGING +- (NSData *)loggedStreamData { + return _loggedStreamData; +} + +- (void)appendLoggedStreamData:dataToAdd { + if (!_loggedStreamData) { + _loggedStreamData = [NSMutableData data]; + } + [_loggedStreamData appendData:dataToAdd]; +} + +- (void)clearLoggedStreamData { + _loggedStreamData = nil; +} + +- (void)setDeferResponseBodyLogging:(BOOL)deferResponseBodyLogging { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (deferResponseBodyLogging != _deferResponseBodyLogging) { + _deferResponseBodyLogging = deferResponseBodyLogging; + if (!deferResponseBodyLogging && !self.hasLoggedError) { + [_delegateQueue addOperationWithBlock:^{ + [self logNowWithError:nil]; + }]; + } + } + } // @synchronized(self) +} + +- (BOOL)deferResponseBodyLogging { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _deferResponseBodyLogging; + } // @synchronized(self) +} + +#else ++ (void)setLoggingEnabled:(BOOL)flag { +} + ++ (BOOL)isLoggingEnabled { + return NO; +} +#endif // STRIP_GTM_FETCH_LOGGING + +@end + +@implementation GTMSessionFetcher (BackwardsCompatibilityOnly) + +- (void)setCookieStorageMethod:(NSInteger)method { + // For backwards compatibility with the old fetcher, we'll support the old constants. + // + // Clients using the GTMSessionFetcher class should set the cookie storage explicitly + // themselves. + NSHTTPCookieStorage *storage = nil; + switch(method) { + case 0: // kGTMHTTPFetcherCookieStorageMethodStatic + // nil storage will use [[self class] staticCookieStorage] when the fetch begins. + break; + case 1: // kGTMHTTPFetcherCookieStorageMethodFetchHistory + // Do nothing; use whatever was set by the fetcher service. + return; + case 2: // kGTMHTTPFetcherCookieStorageMethodSystemDefault + storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; + break; + case 3: // kGTMHTTPFetcherCookieStorageMethodNone + // Create temporary storage for this fetcher only. + storage = [[GTMSessionCookieStorage alloc] init]; + break; + default: + GTMSESSION_ASSERT_DEBUG(0, @"Invalid cookie storage method: %d", (int)method); + } + self.cookieStorage = storage; +} + +@end + +@implementation GTMSessionCookieStorage { + NSMutableArray *_cookies; + NSHTTPCookieAcceptPolicy _policy; +} + +- (id)init { + self = [super init]; + if (self != nil) { + _cookies = [[NSMutableArray alloc] init]; + } + return self; +} + +- (GTM_NULLABLE NSArray *)cookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_cookies copy]; + } // @synchronized(self) +} + +- (void)setCookie:(NSHTTPCookie *)cookie { + if (!cookie) return; + if (_policy == NSHTTPCookieAcceptPolicyNever) return; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self internalSetCookie:cookie]; + } // @synchronized(self) +} + +// Note: this should only be called from inside a @synchronized(self) block. +- (void)internalSetCookie:(NSHTTPCookie *)newCookie { + GTMSessionCheckSynchronized(self); + + if (_policy == NSHTTPCookieAcceptPolicyNever) return; + + BOOL isValidCookie = (newCookie.name.length > 0 + && newCookie.domain.length > 0 + && newCookie.path.length > 0); + GTMSESSION_ASSERT_DEBUG(isValidCookie, @"invalid cookie: %@", newCookie); + + if (isValidCookie) { + // Remove the cookie if it's currently in the array. + NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie]; + if (oldCookie) { + [_cookies removeObjectIdenticalTo:oldCookie]; + } + + if (![[self class] hasCookieExpired:newCookie]) { + [_cookies addObject:newCookie]; + } + } +} + +// Add all cookies in the new cookie array to the storage, +// replacing stored cookies as appropriate. +// +// Side effect: removes expired cookies from the storage array. +- (void)setCookies:(GTM_NULLABLE NSArray *)newCookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self removeExpiredCookies]; + + for (NSHTTPCookie *newCookie in newCookies) { + [self internalSetCookie:newCookie]; + } + } // @synchronized(self) +} + +- (void)setCookies:(NSArray *)cookies forURL:(GTM_NULLABLE NSURL *)URL mainDocumentURL:(GTM_NULLABLE NSURL *)mainDocumentURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_policy == NSHTTPCookieAcceptPolicyNever) { + return; + } + + if (_policy == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) { + NSString *mainHost = mainDocumentURL.host; + NSString *associatedHost = URL.host; + if (!mainHost || ![associatedHost hasSuffix:mainHost]) { + return; + } + } + } // @synchronized(self) + [self setCookies:cookies]; +} + +- (void)deleteCookie:(NSHTTPCookie *)cookie { + if (!cookie) return; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSHTTPCookie *foundCookie = [self cookieMatchingCookie:cookie]; + if (foundCookie) { + [_cookies removeObjectIdenticalTo:foundCookie]; + } + } // @synchronized(self) +} + +// Retrieve all cookies appropriate for the given URL, considering +// domain, path, cookie name, expiration, security setting. +// Side effect: removed expired cookies from the storage array. +- (GTM_NULLABLE NSArray *)cookiesForURL:(NSURL *)theURL { + NSMutableArray *foundCookies = nil; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self removeExpiredCookies]; + + // We'll prepend "." to the desired domain, since we want the + // actual domain "nytimes.com" to still match the cookie domain + // ".nytimes.com" when we check it below with hasSuffix. + NSString *host = theURL.host.lowercaseString; + NSString *path = theURL.path; + NSString *scheme = [theURL scheme]; + + NSString *requestingDomain = nil; + BOOL isLocalhostRetrieval = NO; + + if (IsLocalhost(host)) { + isLocalhostRetrieval = YES; + } else { + if (host.length > 0) { + requestingDomain = [@"." stringByAppendingString:host]; + } + } + + for (NSHTTPCookie *storedCookie in _cookies) { + NSString *cookieDomain = storedCookie.domain.lowercaseString; + NSString *cookiePath = storedCookie.path; + BOOL cookieIsSecure = [storedCookie isSecure]; + + BOOL isDomainOK; + + if (isLocalhostRetrieval) { + // Prior to 10.5.6, the domain stored into NSHTTPCookies for localhost + // is "localhost.local" + isDomainOK = (IsLocalhost(cookieDomain) + || [cookieDomain isEqual:@"localhost.local"]); + } else { + // Ensure we're matching exact domain names. We prepended a dot to the + // requesting domain, so we can also prepend one here if needed before + // checking if the request contains the cookie domain. + if (![cookieDomain hasPrefix:@"."]) { + cookieDomain = [@"." stringByAppendingString:cookieDomain]; + } + isDomainOK = [requestingDomain hasSuffix:cookieDomain]; + } + + BOOL isPathOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath]; + BOOL isSecureOK = (!cookieIsSecure + || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame); + + if (isDomainOK && isPathOK && isSecureOK) { + if (foundCookies == nil) { + foundCookies = [NSMutableArray array]; + } + [foundCookies addObject:storedCookie]; + } + } + } // @synchronized(self) + return foundCookies; +} + +// Override methods from the NSHTTPCookieStorage (NSURLSessionTaskAdditions) category. +- (void)storeCookies:(NSArray *)cookies forTask:(NSURLSessionTask *)task { + NSURLRequest *currentRequest = task.currentRequest; + [self setCookies:cookies forURL:currentRequest.URL mainDocumentURL:nil]; +} + +- (void)getCookiesForTask:(NSURLSessionTask *)task + completionHandler:(void (^)(GTM_NSArrayOf(NSHTTPCookie *) *))completionHandler { + if (completionHandler) { + NSURLRequest *currentRequest = task.currentRequest; + NSURL *currentRequestURL = currentRequest.URL; + NSArray *cookies = [self cookiesForURL:currentRequestURL]; + completionHandler(cookies); + } +} + +// Return a cookie from the array with the same name, domain, and path as the +// given cookie, or else return nil if none found. +// +// Both the cookie being tested and all cookies in the storage array should +// be valid (non-nil name, domains, paths). +// +// Note: this should only be called from inside a @synchronized(self) block +- (GTM_NULLABLE NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie { + GTMSessionCheckSynchronized(self); + + NSString *name = cookie.name; + NSString *domain = cookie.domain; + NSString *path = cookie.path; + + GTMSESSION_ASSERT_DEBUG(name && domain && path, + @"Invalid stored cookie (name:%@ domain:%@ path:%@)", name, domain, path); + + for (NSHTTPCookie *storedCookie in _cookies) { + if ([storedCookie.name isEqual:name] + && [storedCookie.domain isEqual:domain] + && [storedCookie.path isEqual:path]) { + return storedCookie; + } + } + return nil; +} + +// Internal routine to remove any expired cookies from the array, excluding +// cookies with nil expirations. +// +// Note: this should only be called from inside a @synchronized(self) block +- (void)removeExpiredCookies { + GTMSessionCheckSynchronized(self); + + // Count backwards since we're deleting items from the array + for (NSInteger idx = (NSInteger)_cookies.count - 1; idx >= 0; idx--) { + NSHTTPCookie *storedCookie = [_cookies objectAtIndex:(NSUInteger)idx]; + if ([[self class] hasCookieExpired:storedCookie]) { + [_cookies removeObjectAtIndex:(NSUInteger)idx]; + } + } +} + ++ (BOOL)hasCookieExpired:(NSHTTPCookie *)cookie { + NSDate *expiresDate = [cookie expiresDate]; + if (expiresDate == nil) { + // Cookies seem to have a Expires property even when the expiresDate method returns nil. + id expiresVal = [[cookie properties] objectForKey:NSHTTPCookieExpires]; + if ([expiresVal isKindOfClass:[NSDate class]]) { + expiresDate = expiresVal; + } + } + BOOL hasExpired = (expiresDate != nil && [expiresDate timeIntervalSinceNow] < 0); + return hasExpired; +} + +- (void)removeAllCookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_cookies removeAllObjects]; + } // @synchronized(self) +} + +- (NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _policy; + } // @synchronized(self) +} + +- (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _policy = cookieAcceptPolicy; + } // @synchronized(self) +} + +@end + +void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...) { + // Verify that the object's selector is implemented with the proper + // number and type of arguments +#if DEBUG + va_list argList; + va_start(argList, sel); + + if (obj && sel) { + // Check that the selector is implemented + if (![obj respondsToSelector:sel]) { + NSLog(@"\"%@\" selector \"%@\" is unimplemented or misnamed", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel)); + NSCAssert(0, @"callback selector unimplemented or misnamed"); + } else { + const char *expectedArgType; + unsigned int argCount = 2; // skip self and _cmd + NSMethodSignature *sig = [obj methodSignatureForSelector:sel]; + + // Check that each expected argument is present and of the correct type + while ((expectedArgType = va_arg(argList, const char*)) != 0) { + + if ([sig numberOfArguments] > argCount) { + const char *foundArgType = [sig getArgumentTypeAtIndex:argCount]; + + if (0 != strncmp(foundArgType, expectedArgType, strlen(expectedArgType))) { + NSLog(@"\"%@\" selector \"%@\" argument %d should be type %s", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel), (argCount - 2), expectedArgType); + NSCAssert(0, @"callback selector argument type mistake"); + } + } + argCount++; + } + + // Check that the proper number of arguments are present in the selector + if (argCount != [sig numberOfArguments]) { + NSLog(@"\"%@\" selector \"%@\" should have %d arguments", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel), (argCount - 2)); + NSCAssert(0, @"callback selector arguments incorrect"); + } + } + } + + va_end(argList); +#endif +} + +NSString *GTMFetcherCleanedUserAgentString(NSString *str) { + // Reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html + // and http://www-archive.mozilla.org/build/user-agent-strings.html + + if (str == nil) return @""; + + NSMutableString *result = [NSMutableString stringWithString:str]; + + // Replace spaces and commas with underscores + [result replaceOccurrencesOfString:@" " + withString:@"_" + options:0 + range:NSMakeRange(0, result.length)]; + [result replaceOccurrencesOfString:@"," + withString:@"_" + options:0 + range:NSMakeRange(0, result.length)]; + + // Delete http token separators and remaining whitespace + static NSCharacterSet *charsToDelete = nil; + if (charsToDelete == nil) { + // Make a set of unwanted characters + NSString *const kSeparators = @"()<>@;:\\\"/[]?={}"; + + NSMutableCharacterSet *mutableChars = + [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy]; + [mutableChars addCharactersInString:kSeparators]; + charsToDelete = [mutableChars copy]; // hang on to an immutable copy + } + + while (1) { + NSRange separatorRange = [result rangeOfCharacterFromSet:charsToDelete]; + if (separatorRange.location == NSNotFound) break; + + [result deleteCharactersInRange:separatorRange]; + }; + + return result; +} + +NSString *GTMFetcherSystemVersionString(void) { + static NSString *sSavedSystemString; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // The Xcode 8 SDKs finally cleaned up this mess by providing TARGET_OS_OSX + // and TARGET_OS_IOS, but to build with older SDKs, those don't exist and + // instead one has to rely on TARGET_OS_MAC (which is true for iOS, watchOS, + // and tvOS) and TARGET_OS_IPHONE (which is true for iOS, watchOS, tvOS). So + // one has to order these carefully so you pick off the specific things + // first. + // If the code can ever assume Xcode 8 or higher (even when building for + // older OSes), then + // TARGET_OS_MAC -> TARGET_OS_OSX + // TARGET_OS_IPHONE -> TARGET_OS_IOS + // TARGET_IPHONE_SIMULATOR -> TARGET_OS_SIMULATOR +#if TARGET_OS_WATCH + // watchOS - WKInterfaceDevice + + WKInterfaceDevice *currentDevice = [WKInterfaceDevice currentDevice]; + + NSString *rawModel = [currentDevice model]; + NSString *model = GTMFetcherCleanedUserAgentString(rawModel); + + NSString *systemVersion = [currentDevice systemVersion]; + +#if TARGET_OS_SIMULATOR + NSString *hardwareModel = @"sim"; +#else + NSString *hardwareModel; + struct utsname unameRecord; + if (uname(&unameRecord) == 0) { + NSString *machineName = @(unameRecord.machine); + hardwareModel = GTMFetcherCleanedUserAgentString(machineName); + } + if (hardwareModel.length == 0) { + hardwareModel = @"unk"; + } +#endif + + sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", + model, systemVersion, hardwareModel]; + // Example: Apple_Watch/3.0 hw/Watch1_2 +#elif TARGET_OS_TV || TARGET_OS_IPHONE + // iOS and tvOS have UIDevice, use that. + UIDevice *currentDevice = [UIDevice currentDevice]; + + NSString *rawModel = [currentDevice model]; + NSString *model = GTMFetcherCleanedUserAgentString(rawModel); + + NSString *systemVersion = [currentDevice systemVersion]; + +#if TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR + NSString *hardwareModel = @"sim"; +#else + NSString *hardwareModel; + struct utsname unameRecord; + if (uname(&unameRecord) == 0) { + NSString *machineName = @(unameRecord.machine); + hardwareModel = GTMFetcherCleanedUserAgentString(machineName); + } + if (hardwareModel.length == 0) { + hardwareModel = @"unk"; + } +#endif + + sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", + model, systemVersion, hardwareModel]; + // Example: iPod_Touch/2.2 hw/iPod1_1 + // Example: Apple_TV/9.2 hw/AppleTV5,3 +#elif TARGET_OS_MAC + // Mac build + NSProcessInfo *procInfo = [NSProcessInfo processInfo]; +#if !defined(MAC_OS_X_VERSION_10_10) + BOOL hasOperatingSystemVersion = NO; +#elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10 + BOOL hasOperatingSystemVersion = + [procInfo respondsToSelector:@selector(operatingSystemVersion)]; +#else + BOOL hasOperatingSystemVersion = YES; +#endif + NSString *versString; + if (hasOperatingSystemVersion) { +#if defined(MAC_OS_X_VERSION_10_10) + // A reference to NSOperatingSystemVersion requires the 10.10 SDK. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +// Disable unguarded availability warning as we can't use the @availability macro until we require +// all clients to build with Xcode 9 or above. + NSOperatingSystemVersion version = procInfo.operatingSystemVersion; +#pragma clang diagnostic pop + versString = [NSString stringWithFormat:@"%ld.%ld.%ld", + (long)version.majorVersion, (long)version.minorVersion, + (long)version.patchVersion]; +#else +#pragma unused(procInfo) +#endif + } else { + // With Gestalt inexplicably deprecated in 10.8, we're reduced to reading + // the system plist file. + NSString *const kPath = @"/System/Library/CoreServices/SystemVersion.plist"; + NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:kPath]; + versString = [plist objectForKey:@"ProductVersion"]; + if (versString.length == 0) { + versString = @"10.?.?"; + } + } + + sSavedSystemString = [[NSString alloc] initWithFormat:@"MacOSX/%@", versString]; +#elif defined(_SYS_UTSNAME_H) + // Foundation-only build + struct utsname unameRecord; + uname(&unameRecord); + + sSavedSystemString = [NSString stringWithFormat:@"%s/%s", + unameRecord.sysname, unameRecord.release]; // "Darwin/8.11.1" +#else +#error No branch taken for a default user agent +#endif + }); + return sSavedSystemString; +} + +NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle) { + NSString *result = [NSString stringWithFormat:@"%@ %@", + GTMFetcherApplicationIdentifier(bundle), + GTMFetcherSystemVersionString()]; + return result; +} + +NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle) { + @synchronized([GTMSessionFetcher class]) { + static NSMutableDictionary *sAppIDMap = nil; + + // If there's a bundle ID, use that; otherwise, use the process name + if (bundle == nil) { + bundle = [NSBundle mainBundle]; + } + NSString *bundleID = [bundle bundleIdentifier]; + if (bundleID == nil) { + bundleID = @""; + } + + NSString *identifier = [sAppIDMap objectForKey:bundleID]; + if (identifier) return identifier; + + // Apps may add a string to the info.plist to uniquely identify different builds. + identifier = [bundle objectForInfoDictionaryKey:@"GTMUserAgentID"]; + if (identifier.length == 0) { + if (bundleID.length > 0) { + identifier = bundleID; + } else { + // Fall back on the procname, prefixed by "proc" to flag that it's + // autogenerated and perhaps unreliable + NSString *procName = [[NSProcessInfo processInfo] processName]; + identifier = [NSString stringWithFormat:@"proc_%@", procName]; + } + } + + // Clean up whitespace and special characters + identifier = GTMFetcherCleanedUserAgentString(identifier); + + // If there's a version number, append that + NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + if (version.length == 0) { + version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; + } + + // Clean up whitespace and special characters + version = GTMFetcherCleanedUserAgentString(version); + + // Glue the two together (cleanup done above or else cleanup would strip the + // slash) + if (version.length > 0) { + identifier = [identifier stringByAppendingFormat:@"/%@", version]; + } + + if (sAppIDMap == nil) { + sAppIDMap = [[NSMutableDictionary alloc] init]; + } + [sAppIDMap setObject:identifier forKey:bundleID]; + return identifier; + } +} + +#if DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG) +@implementation GTMSessionSyncMonitorInternal { + NSValue *_objectKey; // The synchronize target object. + const char *_functionName; // The function containing the monitored sync block. +} + +- (instancetype)initWithSynchronizationObject:(id)object + allowRecursive:(BOOL)allowRecursive + functionName:(const char *)functionName { + self = [super init]; + if (self) { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + _objectKey = [NSValue valueWithNonretainedObject:object]; + _functionName = functionName; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + if (counters == nil) { + counters = [NSMutableDictionary dictionary]; + threadDict[(id)threadKey] = counters; + } + NSCountedSet *functionNamesCounter = counters[_objectKey]; + NSUInteger numberOfSyncingFunctions = functionNamesCounter.count; + + if (!allowRecursive) { + BOOL isTopLevelSyncScope = (numberOfSyncingFunctions == 0); + NSArray *stack = [NSThread callStackSymbols]; + GTMSESSION_ASSERT_DEBUG(isTopLevelSyncScope, + @"*** Recursive sync on %@ at %s; previous sync at %@\n%@", + [object class], functionName, functionNamesCounter.allObjects, + [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); + } + + if (!functionNamesCounter) { + functionNamesCounter = [NSCountedSet set]; + counters[_objectKey] = functionNamesCounter; + } + [functionNamesCounter addObject:(id _Nonnull)@(functionName)]; + } + return self; +} + +- (void)dealloc { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + NSCountedSet *functionNamesCounter = counters[_objectKey]; + NSString *functionNameStr = @(_functionName); + NSUInteger numberOfSyncsByThisFunction = [functionNamesCounter countForObject:functionNameStr]; + NSArray *stack = [NSThread callStackSymbols]; + GTMSESSION_ASSERT_DEBUG(numberOfSyncsByThisFunction > 0, @"Sync not found on %@ at %s\n%@", + [_objectKey.nonretainedObjectValue class], _functionName, + [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); + [functionNamesCounter removeObject:functionNameStr]; + if (functionNamesCounter.count == 0) { + [counters removeObjectForKey:_objectKey]; + } +} + ++ (NSArray *)functionsHoldingSynchronizationOnObject:(id)object { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + NSValue *localObjectKey = [NSValue valueWithNonretainedObject:object]; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + NSCountedSet *functionNamesCounter = counters[localObjectKey]; + return functionNamesCounter.count > 0 ? functionNamesCounter.allObjects : nil; +} +@end +#endif // DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG) +GTM_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h new file mode 100644 index 0000000..5ccea78 --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h @@ -0,0 +1,112 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "GTMSessionFetcher.h" + +// GTM HTTP Logging +// +// All traffic using GTMSessionFetcher can be easily logged. Call +// +// [GTMSessionFetcher setLoggingEnabled:YES]; +// +// to begin generating log files. +// +// Unless explicitly set by the application using +setLoggingDirectory:, +// logs are put into a default directory, located at: +// * macOS: ~/Desktop/GTMHTTPDebugLogs +// * iOS simulator: ~/GTMHTTPDebugLogs (in application sandbox) +// * iOS device: ~/Documents/GTMHTTPDebugLogs (in application sandbox) +// +// Tip: use the Finder's "Sort By Date" to find the most recent logs. +// +// Each run of an application gets a separate set of log files. An html +// file is generated to simplify browsing the run's http transactions. +// The html file includes javascript links for inline viewing of uploaded +// and downloaded data. +// +// A symlink is created in the logs folder to simplify finding the html file +// for the latest run of the application; the symlink is called +// +// AppName_http_log_newest.html +// +// For better viewing of XML logs, use Camino or Firefox rather than Safari. +// +// Each fetcher may be given a comment to be inserted as a label in the logs, +// such as +// [fetcher setCommentWithFormat:@"retrieve item %@", itemName]; +// +// Projects may define STRIP_GTM_FETCH_LOGGING to remove logging code. + +#if !STRIP_GTM_FETCH_LOGGING + +@interface GTMSessionFetcher (GTMSessionFetcherLogging) + +// Note: on macOS the default logs directory is ~/Desktop/GTMHTTPDebugLogs; on +// iOS simulators it will be the ~/GTMHTTPDebugLogs (in the app sandbox); on +// iOS devices it will be in ~/Documents/GTMHTTPDebugLogs (in the app sandbox). +// These directories will be created as needed, and are excluded from backups +// to iCloud and iTunes. +// +// If a custom directory is set, the directory should already exist. It is +// the application's responsibility to exclude any custom directory from +// backups, if desired. ++ (void)setLoggingDirectory:(NSString *)path; ++ (NSString *)loggingDirectory; + +// client apps can turn logging on and off ++ (void)setLoggingEnabled:(BOOL)isLoggingEnabled; ++ (BOOL)isLoggingEnabled; + +// client apps can turn off logging to a file if they want to only check +// the fetcher's log property ++ (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled; ++ (BOOL)isLoggingToFileEnabled; + +// client apps can optionally specify process name and date string used in +// log file names ++ (void)setLoggingProcessName:(NSString *)processName; ++ (NSString *)loggingProcessName; + ++ (void)setLoggingDateStamp:(NSString *)dateStamp; ++ (NSString *)loggingDateStamp; + +// client apps can specify the directory for the log for this specific run, +// typically to match the directory used by another fetcher class, like: +// +// [GTMSessionFetcher setLogDirectoryForCurrentRun:[GTMHTTPFetcher logDirectoryForCurrentRun]]; +// +// Setting this overrides the logging directory, process name, and date stamp when writing +// the log file. ++ (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun; ++ (NSString *)logDirectoryForCurrentRun; + +// Prunes old log directories that have not been modified since the provided date. +// This will not delete the current run's log directory. ++ (void)deleteLogDirectoriesOlderThanDate:(NSDate *)date; + +// internal; called by fetcher +- (void)logFetchWithError:(NSError *)error; +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider; + +// internal; accessors useful for viewing logs ++ (NSString *)processNameLogPrefix; ++ (NSString *)symlinkNameSuffix; ++ (NSString *)htmlFileName; + +@end + +#endif // !STRIP_GTM_FETCH_LOGGING diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m new file mode 100644 index 0000000..cdf5c17 --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m @@ -0,0 +1,982 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#include +#include + +#import "GTMSessionFetcherLogging.h" + +#ifndef STRIP_GTM_FETCH_LOGGING + #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. +#endif + +#if !STRIP_GTM_FETCH_LOGGING + +// Sensitive credential strings are replaced in logs with _snip_ +// +// Apps that must see the contents of sensitive tokens can set this to 1 +#ifndef SKIP_GTM_FETCH_LOGGING_SNIPPING +#define SKIP_GTM_FETCH_LOGGING_SNIPPING 0 +#endif + +// If GTMReadMonitorInputStream is available, it can be used for +// capturing uploaded streams of data +// +// We locally declare methods of GTMReadMonitorInputStream so we +// do not need to import the header, as some projects may not have it available +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMReadMonitorInputStream : NSInputStream + ++ (instancetype)inputStreamWithStream:(NSInputStream *)input; + +@property (assign) id readDelegate; +@property (assign) SEL readSelector; + +@end +#else +@class GTMReadMonitorInputStream; +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionFetcher (GTMHTTPFetcherLoggingUtilities) + ++ (NSString *)headersStringForDictionary:(NSDictionary *)dict; ++ (NSString *)snipSubstringOfString:(NSString *)originalStr + betweenStartString:(NSString *)startStr + endString:(NSString *)endStr; +- (void)inputStream:(GTMReadMonitorInputStream *)stream + readIntoBuffer:(void *)buffer + length:(int64_t)length; + +@end + +@implementation GTMSessionFetcher (GTMSessionFetcherLogging) + +// fetchers come and fetchers go, but statics are forever +static BOOL gIsLoggingEnabled = NO; +static BOOL gIsLoggingToFile = YES; +static NSString *gLoggingDirectoryPath = nil; +static NSString *gLogDirectoryForCurrentRun = nil; +static NSString *gLoggingDateStamp = nil; +static NSString *gLoggingProcessName = nil; + ++ (void)setLoggingDirectory:(NSString *)path { + gLoggingDirectoryPath = [path copy]; +} + ++ (NSString *)loggingDirectory { + if (!gLoggingDirectoryPath) { + NSArray *paths = nil; +#if TARGET_IPHONE_SIMULATOR + // default to a directory called GTMHTTPDebugLogs into a sandbox-safe + // directory that a developer can find easily, the application home + paths = @[ NSHomeDirectory() ]; +#elif TARGET_OS_IPHONE + // Neither ~/Desktop nor ~/Home is writable on an actual iOS, watchOS, or tvOS device. + // Put it in ~/Documents. + paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); +#else + // default to a directory called GTMHTTPDebugLogs in the desktop folder + paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); +#endif + + NSString *desktopPath = paths.firstObject; + if (desktopPath) { + NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs"; + NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName]; + + NSFileManager *fileMgr = [NSFileManager defaultManager]; + BOOL isDir; + BOOL doesFolderExist = [fileMgr fileExistsAtPath:logsFolderPath isDirectory:&isDir]; + if (!doesFolderExist) { + // make the directory + doesFolderExist = [fileMgr createDirectoryAtPath:logsFolderPath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + if (doesFolderExist) { + // The directory has been created. Exclude it from backups. + NSURL *pathURL = [NSURL fileURLWithPath:logsFolderPath isDirectory:YES]; + [pathURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:NULL]; + } + } + + if (doesFolderExist) { + // it's there; store it in the global + gLoggingDirectoryPath = [logsFolderPath copy]; + } + } + } + return gLoggingDirectoryPath; +} + ++ (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun { + // Set the path for this run's logs. + gLogDirectoryForCurrentRun = [logDirectoryForCurrentRun copy]; +} + ++ (NSString *)logDirectoryForCurrentRun { + // make a directory for this run's logs, like SyncProto_logs_10-16_01-56-58PM + if (gLogDirectoryForCurrentRun) return gLogDirectoryForCurrentRun; + + NSString *parentDir = [self loggingDirectory]; + NSString *logNamePrefix = [self processNameLogPrefix]; + NSString *dateStamp = [self loggingDateStamp]; + NSString *dirName = [NSString stringWithFormat:@"%@%@", logNamePrefix, dateStamp]; + NSString *logDirectory = [parentDir stringByAppendingPathComponent:dirName]; + + if (gIsLoggingToFile) { + NSFileManager *fileMgr = [NSFileManager defaultManager]; + // Be sure that the first time this app runs, it's not writing to a preexisting folder + static BOOL gShouldReuseFolder = NO; + if (!gShouldReuseFolder) { + gShouldReuseFolder = YES; + NSString *origLogDir = logDirectory; + for (int ctr = 2; ctr < 20; ++ctr) { + if (![fileMgr fileExistsAtPath:logDirectory]) break; + + // append a digit + logDirectory = [origLogDir stringByAppendingFormat:@"_%d", ctr]; + } + } + if (![fileMgr createDirectoryAtPath:logDirectory + withIntermediateDirectories:YES + attributes:nil + error:NULL]) return nil; + } + gLogDirectoryForCurrentRun = logDirectory; + + return gLogDirectoryForCurrentRun; +} + ++ (void)setLoggingEnabled:(BOOL)isLoggingEnabled { + gIsLoggingEnabled = isLoggingEnabled; +} + ++ (BOOL)isLoggingEnabled { + return gIsLoggingEnabled; +} + ++ (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled { + gIsLoggingToFile = isLoggingToFileEnabled; +} + ++ (BOOL)isLoggingToFileEnabled { + return gIsLoggingToFile; +} + ++ (void)setLoggingProcessName:(NSString *)processName { + gLoggingProcessName = [processName copy]; +} + ++ (NSString *)loggingProcessName { + // get the process name (once per run) replacing spaces with underscores + if (!gLoggingProcessName) { + NSString *procName = [[NSProcessInfo processInfo] processName]; + gLoggingProcessName = [procName stringByReplacingOccurrencesOfString:@" " withString:@"_"]; + } + return gLoggingProcessName; +} + ++ (void)setLoggingDateStamp:(NSString *)dateStamp { + gLoggingDateStamp = [dateStamp copy]; +} + ++ (NSString *)loggingDateStamp { + // We'll pick one date stamp per run, so a run that starts at a later second + // will get a unique results html file + if (!gLoggingDateStamp) { + // produce a string like 08-21_01-41-23PM + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setFormatterBehavior:NSDateFormatterBehavior10_4]; + [formatter setDateFormat:@"M-dd_hh-mm-ssa"]; + + gLoggingDateStamp = [formatter stringFromDate:[NSDate date]]; + } + return gLoggingDateStamp; +} + ++ (NSString *)processNameLogPrefix { + static NSString *gPrefix = nil; + if (!gPrefix) { + NSString *processName = [self loggingProcessName]; + gPrefix = [[NSString alloc] initWithFormat:@"%@_log_", processName]; + } + return gPrefix; +} + ++ (NSString *)symlinkNameSuffix { + return @"_log_newest.html"; +} + ++ (NSString *)htmlFileName { + return @"aperçu_http_log.html"; +} + ++ (void)deleteLogDirectoriesOlderThanDate:(NSDate *)cutoffDate { + NSFileManager *fileMgr = [NSFileManager defaultManager]; + NSURL *parentDir = [NSURL fileURLWithPath:[[self class] loggingDirectory]]; + NSURL *logDirectoryForCurrentRun = + [NSURL fileURLWithPath:[[self class] logDirectoryForCurrentRun]]; + NSError *error; + NSArray *contents = [fileMgr contentsOfDirectoryAtURL:parentDir + includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] + options:0 + error:&error]; + for (NSURL *itemURL in contents) { + if ([itemURL isEqual:logDirectoryForCurrentRun]) continue; + + NSDate *modDate; + if ([itemURL getResourceValue:&modDate + forKey:NSURLContentModificationDateKey + error:&error]) { + if ([modDate compare:cutoffDate] == NSOrderedAscending) { + if (![fileMgr removeItemAtURL:itemURL error:&error]) { + NSLog(@"deleteLogDirectoriesOlderThanDate failed to delete %@: %@", + itemURL.path, error); + } + } + } else { + NSLog(@"deleteLogDirectoriesOlderThanDate failed to get mod date of %@: %@", + itemURL.path, error); + } + } +} + +// formattedStringFromData returns a prettyprinted string for XML or JSON input, +// and a plain string for other input data +- (NSString *)formattedStringFromData:(NSData *)inputData + contentType:(NSString *)contentType + JSON:(NSDictionary **)outJSON { + if (!inputData) return nil; + + // if the content type is JSON and we have the parsing class available, use that + if ([contentType hasPrefix:@"application/json"] && inputData.length > 5) { + // convert from JSON string to NSObjects and back to a formatted string + NSMutableDictionary *obj = [NSJSONSerialization JSONObjectWithData:inputData + options:NSJSONReadingMutableContainers + error:NULL]; + if (obj) { + if (outJSON) *outJSON = obj; + if ([obj isKindOfClass:[NSMutableDictionary class]]) { + // for security and privacy, omit OAuth 2 response access and refresh tokens + if ([obj valueForKey:@"refresh_token"] != nil) { + [obj setObject:@"_snip_" forKey:@"refresh_token"]; + } + if ([obj valueForKey:@"access_token"] != nil) { + [obj setObject:@"_snip_" forKey:@"access_token"]; + } + } + NSData *data = [NSJSONSerialization dataWithJSONObject:obj + options:NSJSONWritingPrettyPrinted + error:NULL]; + if (data) { + NSString *jsonStr = [[NSString alloc] initWithData:data + encoding:NSUTF8StringEncoding]; + return jsonStr; + } + } + } + +#if !TARGET_OS_IPHONE && !GTM_SKIP_LOG_XMLFORMAT + // verify that this data starts with the bytes indicating XML + + NSString *const kXMLLintPath = @"/usr/bin/xmllint"; + static BOOL gHasCheckedAvailability = NO; + static BOOL gIsXMLLintAvailable = NO; + + if (!gHasCheckedAvailability) { + gIsXMLLintAvailable = [[NSFileManager defaultManager] fileExistsAtPath:kXMLLintPath]; + gHasCheckedAvailability = YES; + } + if (gIsXMLLintAvailable + && inputData.length > 5 + && strncmp(inputData.bytes, " 0) { + // success + inputData = formattedData; + } + } +#else + // we can't call external tasks on the iPhone; leave the XML unformatted +#endif + + NSString *dataStr = [[NSString alloc] initWithData:inputData + encoding:NSUTF8StringEncoding]; + return dataStr; +} + +// stringFromStreamData creates a string given the supplied data +// +// If NSString can create a UTF-8 string from the data, then that is returned. +// +// Otherwise, this routine tries to find a MIME boundary at the beginning of the data block, and +// uses that to break up the data into parts. Each part will be used to try to make a UTF-8 string. +// For parts that fail, a replacement string showing the part header and <> is supplied +// in place of the binary data. + +- (NSString *)stringFromStreamData:(NSData *)data + contentType:(NSString *)contentType { + + if (!data) return nil; + + // optimistically, see if the whole data block is UTF-8 + NSString *streamDataStr = [self formattedStringFromData:data + contentType:contentType + JSON:NULL]; + if (streamDataStr) return streamDataStr; + + // Munge a buffer by replacing non-ASCII bytes with underscores, and turn that munged buffer an + // NSString. That gives us a string we can use with NSScanner. + NSMutableData *mutableData = [NSMutableData dataWithData:data]; + unsigned char *bytes = (unsigned char *)mutableData.mutableBytes; + + for (unsigned int idx = 0; idx < mutableData.length; ++idx) { + if (bytes[idx] > 0x7F || bytes[idx] == 0) { + bytes[idx] = '_'; + } + } + + NSString *mungedStr = [[NSString alloc] initWithData:mutableData + encoding:NSUTF8StringEncoding]; + if (mungedStr) { + + // scan for the boundary string + NSString *boundary = nil; + NSScanner *scanner = [NSScanner scannerWithString:mungedStr]; + + if ([scanner scanUpToString:@"\r\n" intoString:&boundary] + && [boundary hasPrefix:@"--"]) { + + // we found a boundary string; use it to divide the string into parts + NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary]; + + // look at each munged part in the original string, and try to convert those into UTF-8 + NSMutableArray *origParts = [NSMutableArray array]; + NSUInteger offset = 0; + for (NSString *mungedPart in mungedParts) { + NSUInteger partSize = mungedPart.length; + NSData *origPartData = [data subdataWithRange:NSMakeRange(offset, partSize)]; + NSString *origPartStr = [[NSString alloc] initWithData:origPartData + encoding:NSUTF8StringEncoding]; + if (origPartStr) { + // we could make this original part into UTF-8; use the string + [origParts addObject:origPartStr]; + } else { + // this part can't be made into UTF-8; scan the header, if we can + NSString *header = nil; + NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart]; + if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) { + // we couldn't find a header + header = @""; + } + // make a part string with the header and <> + NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%lu bytes>>\r", + header, (long)(partSize - header.length)]; + [origParts addObject:binStr]; + } + offset += partSize + boundary.length; + } + // rejoin the original parts + streamDataStr = [origParts componentsJoinedByString:boundary]; + } + } + if (!streamDataStr) { + // give up; just make a string showing the uploaded bytes + streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", (unsigned int)data.length]; + } + return streamDataStr; +} + +// logFetchWithError is called following a successful or failed fetch attempt +// +// This method does all the work for appending to and creating log files + +- (void)logFetchWithError:(NSError *)error { + if (![[self class] isLoggingEnabled]) return; + NSString *logDirectory = [[self class] logDirectoryForCurrentRun]; + if (!logDirectory) return; + NSString *processName = [[self class] loggingProcessName]; + + // TODO: add Javascript to display response data formatted in hex + + // each response's NSData goes into its own xml or txt file, though all responses for this run of + // the app share a main html file. This counter tracks all fetch responses for this app run. + // + // we'll use a local variable since this routine may be reentered while waiting for XML formatting + // to be completed by an external task + static int gResponseCounter = 0; + int responseCounter = ++gResponseCounter; + + NSURLResponse *response = [self response]; + NSDictionary *responseHeaders = [self responseHeaders]; + NSString *responseDataStr = nil; + NSDictionary *responseJSON = nil; + + // if there's response data, decide what kind of file to put it in based on the first bytes of the + // file or on the mime type supplied by the server + NSString *responseMIMEType = [response MIMEType]; + BOOL isResponseImage = NO; + + // file name for an image data file + NSString *responseDataFileName = nil; + + int64_t responseDataLength = self.downloadedLength; + if (responseDataLength > 0) { + NSData *downloadedData = self.downloadedData; + if (downloadedData == nil + && responseDataLength > 0 + && responseDataLength < 20000 + && self.destinationFileURL) { + // There's a download file that's not too big, so get the data to display from the downloaded + // file. + NSURL *destinationURL = self.destinationFileURL; + downloadedData = [NSData dataWithContentsOfURL:destinationURL]; + } + NSString *responseType = [responseHeaders valueForKey:@"Content-Type"]; + responseDataStr = [self formattedStringFromData:downloadedData + contentType:responseType + JSON:&responseJSON]; + NSString *responseDataExtn = nil; + NSData *dataToWrite = nil; + if (responseDataStr) { + // we were able to make a UTF-8 string from the response data + if ([responseMIMEType isEqual:@"application/atom+xml"] + || [responseMIMEType hasSuffix:@"/xml"]) { + responseDataExtn = @"xml"; + dataToWrite = [responseDataStr dataUsingEncoding:NSUTF8StringEncoding]; + } + } else if ([responseMIMEType isEqual:@"image/jpeg"]) { + responseDataExtn = @"jpg"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else if ([responseMIMEType isEqual:@"image/gif"]) { + responseDataExtn = @"gif"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else if ([responseMIMEType isEqual:@"image/png"]) { + responseDataExtn = @"png"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else { + // add more non-text types here + } + // if we have an extension, save the raw data in a file with that extension + if (responseDataExtn && dataToWrite) { + // generate a response file base name like + NSString *responseBaseName = [NSString stringWithFormat:@"fetch_%d_response", responseCounter]; + responseDataFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn]; + NSString *responseDataFilePath = [logDirectory stringByAppendingPathComponent:responseDataFileName]; + + NSError *downloadedError = nil; + if (gIsLoggingToFile && ![dataToWrite writeToFile:responseDataFilePath + options:0 + error:&downloadedError]) { + NSLog(@"%@ logging write error:%@ (%@)", [self class], downloadedError, responseDataFileName); + } + } + } + // we'll have one main html file per run of the app + NSString *htmlName = [[self class] htmlFileName]; + NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName]; + + // if the html file exists (from logging previous fetches) we don't need + // to re-write the header or the scripts + NSFileManager *fileMgr = [NSFileManager defaultManager]; + BOOL didFileExist = [fileMgr fileExistsAtPath:htmlPath]; + + NSMutableString* outputHTML = [NSMutableString string]; + + // we need a header to say we'll have UTF-8 text + if (!didFileExist) { + [outputHTML appendFormat:@"%@ HTTP fetch log %@", + processName, [[self class] loggingDateStamp]]; + } + // now write the visible html elements + NSString *copyableFileName = [NSString stringWithFormat:@"fetch_%d.txt", responseCounter]; + + NSDate *now = [NSDate date]; + // write the date & time, the comment, and the link to the plain-text (copyable) log + [outputHTML appendFormat:@"%@      ", now]; + + NSString *comment = [self comment]; + if (comment.length > 0) { + [outputHTML appendFormat:@"%@      ", comment]; + } + [outputHTML appendFormat:@"request/response log
", copyableFileName]; + NSTimeInterval elapsed = -self.initialBeginFetchDate.timeIntervalSinceNow; + [outputHTML appendFormat:@"elapsed: %5.3fsec
", elapsed]; + + // write the request URL + NSURLRequest *request = self.request; + NSString *requestMethod = request.HTTPMethod; + NSURL *requestURL = request.URL; + + // Save the request URL for next time in case this redirects. + NSString *redirectedFromURLString = [self.redirectedFromURL absoluteString]; + self.redirectedFromURL = [requestURL copy]; + if (redirectedFromURLString) { + [outputHTML appendFormat:@"redirected from %@
", + redirectedFromURLString]; + } + [outputHTML appendFormat:@"request: %@ %@
\n", requestMethod, requestURL]; + + // write the request headers + NSDictionary *requestHeaders = request.allHTTPHeaderFields; + NSUInteger numberOfRequestHeaders = requestHeaders.count; + if (numberOfRequestHeaders > 0) { + // Indicate if the request is authorized; warn if the request is authorized but non-SSL + NSString *auth = [requestHeaders objectForKey:@"Authorization"]; + NSString *headerDetails = @""; + if (auth) { + BOOL isInsecure = [[requestURL scheme] isEqual:@"http"]; + if (isInsecure) { + // 26A0 = ⚠ + headerDetails = + @"   authorized, non-SSL "; + } else { + headerDetails = @"   authorized"; + } + } + NSString *cookiesHdr = [requestHeaders objectForKey:@"Cookie"]; + if (cookiesHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   cookies"]; + } + NSString *matchHdr = [requestHeaders objectForKey:@"If-Match"]; + if (matchHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   if-match"]; + } + matchHdr = [requestHeaders objectForKey:@"If-None-Match"]; + if (matchHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   if-none-match"]; + } + [outputHTML appendFormat:@"   headers: %d %@
", + (int)numberOfRequestHeaders, headerDetails]; + } else { + [outputHTML appendFormat:@"   headers: none
"]; + } + // write the request post data + NSData *bodyData = nil; + NSData *loggedStreamData = self.loggedStreamData; + if (loggedStreamData) { + bodyData = loggedStreamData; + } else { + bodyData = self.bodyData; + if (bodyData == nil) { + bodyData = self.request.HTTPBody; + } + } + uint64_t bodyDataLength = bodyData.length; + + if (bodyData.length == 0) { + // If the data is in a body upload file URL, read that in if it's not huge. + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSNumber *fileSizeNum = nil; + NSError *fileSizeError = nil; + if ([bodyFileURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:&fileSizeError]) { + bodyDataLength = [fileSizeNum unsignedLongLongValue]; + if (bodyDataLength > 0 && bodyDataLength < 50000) { + bodyData = [NSData dataWithContentsOfURL:bodyFileURL + options:NSDataReadingUncached + error:&fileSizeError]; + } + } + } + } + NSString *bodyDataStr = nil; + NSString *postType = [requestHeaders valueForKey:@"Content-Type"]; + + if (bodyDataLength > 0) { + [outputHTML appendFormat:@"   data: %llu bytes, %@
\n", + bodyDataLength, postType ? postType : @"(no type)"]; + NSString *logRequestBody = self.logRequestBody; + if (logRequestBody) { + bodyDataStr = [logRequestBody copy]; + self.logRequestBody = nil; + } else { + bodyDataStr = [self stringFromStreamData:bodyData + contentType:postType]; + if (bodyDataStr) { + // remove OAuth 2 client secret and refresh token + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"client_secret=" + endString:@"&"]; + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"refresh_token=" + endString:@"&"]; + // remove ClientLogin password + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"&Passwd=" + endString:@"&"]; + } + } + } else { + // no post data + } + // write the response status, MIME type, URL + NSInteger status = [self statusCode]; + if (response) { + NSString *statusString = @""; + if (status != 0) { + if (status == 200 || status == 201) { + statusString = [NSString stringWithFormat:@"%ld", (long)status]; + + // report any JSON-RPC error + if ([responseJSON isKindOfClass:[NSDictionary class]]) { + NSDictionary *jsonError = [responseJSON objectForKey:@"error"]; + if ([jsonError isKindOfClass:[NSDictionary class]]) { + NSString *jsonCode = [[jsonError valueForKey:@"code"] description]; + NSString *jsonMessage = [jsonError valueForKey:@"message"]; + if (jsonCode || jsonMessage) { + // 2691 = ⚑ + NSString *const jsonErrFmt = + @"   JSON error: %@ %@  ⚑"; + statusString = [statusString stringByAppendingFormat:jsonErrFmt, + jsonCode ? jsonCode : @"", + jsonMessage ? jsonMessage : @""]; + } + } + } + } else { + // purple for anything other than 200 or 201 + NSString *flag = status >= 400 ? @" ⚑" : @""; // 2691 = ⚑ + NSString *explanation = [NSHTTPURLResponse localizedStringForStatusCode:status]; + NSString *const statusFormat = @"%ld %@ %@"; + statusString = [NSString stringWithFormat:statusFormat, (long)status, explanation, flag]; + } + } + // show the response URL only if it's different from the request URL + NSString *responseURLStr = @""; + NSURL *responseURL = response.URL; + + if (responseURL && ![responseURL isEqual:request.URL]) { + NSString *const responseURLFormat = + @"response URL: %@
\n"; + responseURLStr = [NSString stringWithFormat:responseURLFormat, [responseURL absoluteString]]; + } + [outputHTML appendFormat:@"response:  status %@
\n%@", + statusString, responseURLStr]; + // Write the response headers + NSUInteger numberOfResponseHeaders = responseHeaders.count; + if (numberOfResponseHeaders > 0) { + // Indicate if the server is setting cookies + NSString *cookiesSet = [responseHeaders valueForKey:@"Set-Cookie"]; + NSString *cookiesStr = + cookiesSet ? @"  sets cookies" : @""; + // Indicate if the server is redirecting + NSString *location = [responseHeaders valueForKey:@"Location"]; + BOOL isRedirect = status >= 300 && status <= 399 && location != nil; + NSString *redirectsStr = + isRedirect ? @"  redirects" : @""; + [outputHTML appendFormat:@"   headers: %d %@ %@
\n", + (int)numberOfResponseHeaders, cookiesStr, redirectsStr]; + } else { + [outputHTML appendString:@"   headers: none
\n"]; + } + } + // error + if (error) { + [outputHTML appendFormat:@"Error: %@
\n", error.description]; + } + // Write the response data + if (responseDataFileName) { + if (isResponseImage) { + // Make a small inline image that links to the full image file + [outputHTML appendFormat:@"   data: %lld bytes, %@
", + responseDataLength, responseMIMEType]; + NSString *const fmt = + @"image\n"; + [outputHTML appendFormat:fmt, responseDataFileName, responseDataFileName]; + } else { + // The response data was XML; link to the xml file + NSString *const fmt = + @"   data: %lld bytes, %@   %@\n"; + [outputHTML appendFormat:fmt, responseDataLength, responseMIMEType, + responseDataFileName, [responseDataFileName pathExtension]]; + } + } else { + // The response data was not an image; just show the length and MIME type + [outputHTML appendFormat:@"   data: %lld bytes, %@\n", + responseDataLength, responseMIMEType ? responseMIMEType : @"(no response type)"]; + } + // Make a single string of the request and response, suitable for copying + // to the clipboard and pasting into a bug report + NSMutableString *copyable = [NSMutableString string]; + if (comment) { + [copyable appendFormat:@"%@\n\n", comment]; + } + [copyable appendFormat:@"%@ elapsed: %5.3fsec\n", now, elapsed]; + if (redirectedFromURLString) { + [copyable appendFormat:@"Redirected from %@\n", redirectedFromURLString]; + } + [copyable appendFormat:@"Request: %@ %@\n", requestMethod, requestURL]; + if (requestHeaders.count > 0) { + [copyable appendFormat:@"Request headers:\n%@\n", + [[self class] headersStringForDictionary:requestHeaders]]; + } + if (bodyDataLength > 0) { + [copyable appendFormat:@"Request body: (%llu bytes)\n", bodyDataLength]; + if (bodyDataStr) { + [copyable appendFormat:@"%@\n", bodyDataStr]; + } + [copyable appendString:@"\n"]; + } + if (response) { + [copyable appendFormat:@"Response: status %d\n", (int) status]; + [copyable appendFormat:@"Response headers:\n%@\n", + [[self class] headersStringForDictionary:responseHeaders]]; + [copyable appendFormat:@"Response body: (%lld bytes)\n", responseDataLength]; + if (responseDataLength > 0) { + NSString *logResponseBody = self.logResponseBody; + if (logResponseBody) { + // The user has provided the response body text. + responseDataStr = [logResponseBody copy]; + self.logResponseBody = nil; + } + if (responseDataStr != nil) { + [copyable appendFormat:@"%@\n", responseDataStr]; + } else { + // Even though it's redundant, we'll put in text to indicate that all the bytes are binary. + if (self.destinationFileURL) { + [copyable appendFormat:@"<<%lld bytes>> to file %@\n", + responseDataLength, self.destinationFileURL.path]; + } else { + [copyable appendFormat:@"<<%lld bytes>>\n", responseDataLength]; + } + } + } + } + if (error) { + [copyable appendFormat:@"Error: %@\n", error]; + } + // Save to log property before adding the separator + self.log = copyable; + + [copyable appendString:@"-----------------------------------------------------------\n"]; + + // Write the copyable version to another file (linked to at the top of the html file, above) + // + // Ideally, something to just copy this to the clipboard like + // Copy here." + // would work everywhere, but it only works in Safari as of 8/2010 + if (gIsLoggingToFile) { + NSString *parentDir = [[self class] loggingDirectory]; + NSString *copyablePath = [logDirectory stringByAppendingPathComponent:copyableFileName]; + NSError *copyableError = nil; + if (![copyable writeToFile:copyablePath + atomically:NO + encoding:NSUTF8StringEncoding + error:©ableError]) { + // Error writing to file + NSLog(@"%@ logging write error:%@ (%@)", [self class], copyableError, copyablePath); + } + [outputHTML appendString:@"

"]; + + // Append the HTML to the main output file + const char* htmlBytes = outputHTML.UTF8String; + NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath + append:YES]; + [stream open]; + [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)]; + [stream close]; + + // Make a symlink to the latest html + NSString *const symlinkNameSuffix = [[self class] symlinkNameSuffix]; + NSString *symlinkName = [processName stringByAppendingString:symlinkNameSuffix]; + NSString *symlinkPath = [parentDir stringByAppendingPathComponent:symlinkName]; + + [fileMgr removeItemAtPath:symlinkPath error:NULL]; + [fileMgr createSymbolicLinkAtPath:symlinkPath + withDestinationPath:htmlPath + error:NULL]; +#if TARGET_OS_IPHONE + static BOOL gReportedLoggingPath = NO; + if (!gReportedLoggingPath) { + gReportedLoggingPath = YES; + NSLog(@"GTMSessionFetcher logging to \"%@\"", parentDir); + } +#endif + } +} + +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream { + if (!inputStream) return nil; + if (![GTMSessionFetcher isLoggingEnabled]) return inputStream; + + [self clearLoggedStreamData]; // Clear any previous data. + Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); + if (!monitorClass) { + NSString const *str = @"<>"; + NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; + [self appendLoggedStreamData:stringData]; + return inputStream; + } + inputStream = [monitorClass inputStreamWithStream:inputStream]; + + GTMReadMonitorInputStream *readMonitorInputStream = (GTMReadMonitorInputStream *)inputStream; + [readMonitorInputStream setReadDelegate:self]; + SEL readSel = @selector(inputStream:readIntoBuffer:length:); + [readMonitorInputStream setReadSelector:readSel]; + + return inputStream; +} + +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider { + if (!streamProvider) return nil; + if (![GTMSessionFetcher isLoggingEnabled]) return streamProvider; + + [self clearLoggedStreamData]; // Clear any previous data. + Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); + if (!monitorClass) { + NSString const *str = @"<>"; + NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; + [self appendLoggedStreamData:stringData]; + return streamProvider; + } + GTMSessionFetcherBodyStreamProvider loggedStreamProvider = + ^(GTMSessionFetcherBodyStreamProviderResponse response) { + streamProvider(^(NSInputStream *bodyStream) { + bodyStream = [self loggedInputStreamForInputStream:bodyStream]; + response(bodyStream); + }); + }; + return loggedStreamProvider; +} + +@end + +@implementation GTMSessionFetcher (GTMSessionFetcherLoggingUtilities) + +- (void)inputStream:(GTMReadMonitorInputStream *)stream + readIntoBuffer:(void *)buffer + length:(int64_t)length { + // append the captured data + NSData *data = [NSData dataWithBytesNoCopy:buffer + length:(NSUInteger)length + freeWhenDone:NO]; + [self appendLoggedStreamData:data]; +} + +#pragma mark Fomatting Utilities + ++ (NSString *)snipSubstringOfString:(NSString *)originalStr + betweenStartString:(NSString *)startStr + endString:(NSString *)endStr { +#if SKIP_GTM_FETCH_LOGGING_SNIPPING + return originalStr; +#else + if (!originalStr) return nil; + + // Find the start string, and replace everything between it + // and the end string (or the end of the original string) with "_snip_" + NSRange startRange = [originalStr rangeOfString:startStr]; + if (startRange.location == NSNotFound) return originalStr; + + // We found the start string + NSUInteger originalLength = originalStr.length; + NSUInteger startOfTarget = NSMaxRange(startRange); + NSRange targetAndRest = NSMakeRange(startOfTarget, originalLength - startOfTarget); + NSRange endRange = [originalStr rangeOfString:endStr + options:0 + range:targetAndRest]; + NSRange replaceRange; + if (endRange.location == NSNotFound) { + // Found no end marker so replace to end of string + replaceRange = targetAndRest; + } else { + // Replace up to the endStr + replaceRange = NSMakeRange(startOfTarget, endRange.location - startOfTarget); + } + NSString *result = [originalStr stringByReplacingCharactersInRange:replaceRange + withString:@"_snip_"]; + return result; +#endif // SKIP_GTM_FETCH_LOGGING_SNIPPING +} + ++ (NSString *)headersStringForDictionary:(NSDictionary *)dict { + // Format the dictionary in http header style, like + // Accept: application/json + // Cache-Control: no-cache + // Content-Type: application/json; charset=utf-8 + // + // Pad the key names, but not beyond 16 chars, since long custom header + // keys just create too much whitespace + NSArray *keys = [dict.allKeys sortedArrayUsingSelector:@selector(compare:)]; + + NSMutableString *str = [NSMutableString string]; + for (NSString *key in keys) { + NSString *value = [dict valueForKey:key]; + if ([key isEqual:@"Authorization"]) { + // Remove OAuth 1 token + value = [[self class] snipSubstringOfString:value + betweenStartString:@"oauth_token=\"" + endString:@"\""]; + + // Remove OAuth 2 bearer token (draft 16, and older form) + value = [[self class] snipSubstringOfString:value + betweenStartString:@"Bearer " + endString:@"\n"]; + value = [[self class] snipSubstringOfString:value + betweenStartString:@"OAuth " + endString:@"\n"]; + + // Remove Google ClientLogin + value = [[self class] snipSubstringOfString:value + betweenStartString:@"GoogleLogin auth=" + endString:@"\n"]; + } + [str appendFormat:@" %@: %@\n", key, value]; + } + return str; +} + +@end + +#endif // !STRIP_GTM_FETCH_LOGGING diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h new file mode 100644 index 0000000..fb743ca --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h @@ -0,0 +1,193 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// For best performance and convenient usage, fetchers should be generated by a common +// GTMSessionFetcherService instance, like +// +// _fetcherService = [[GTMSessionFetcherService alloc] init]; +// GTMSessionFetcher* myFirstFetcher = [_fetcherService fetcherWithRequest:request1]; +// GTMSessionFetcher* mySecondFetcher = [_fetcherService fetcherWithRequest:request2]; + +#import "GTMSessionFetcher.h" + +GTM_ASSUME_NONNULL_BEGIN + +// Notifications. + +// This notification indicates a reusable session has become invalid. It is intended mainly for the +// service's unit tests. +// +// The notification object is the fetcher service. +// The invalid session is provided via the userInfo kGTMSessionFetcherServiceSessionKey key. +extern NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification; +extern NSString *const kGTMSessionFetcherServiceSessionKey; + +@interface GTMSessionFetcherService : NSObject + +// Queues of delayed and running fetchers. Each dictionary contains arrays +// of GTMSessionFetcher *fetchers, keyed by NSString *host +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *delayedFetchersByHost; +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *runningFetchersByHost; + +// A max value of 0 means no fetchers should be delayed. +// The default limit is 10 simultaneous fetchers targeting each host. +// This does not apply to fetchers whose useBackgroundSession property is YES. Since services are +// not resurrected on an app relaunch, delayed fetchers would effectively be abandoned. +@property(atomic, assign) NSUInteger maxRunningFetchersPerHost; + +// Properties to be applied to each fetcher; see GTMSessionFetcher.h for descriptions +@property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; +@property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; +@property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; +@property(atomic, strong) NSURLCredential *proxyCredential; +@property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; +@property(atomic, assign) BOOL allowLocalhostRequest; +@property(atomic, assign) BOOL allowInvalidServerCertificates; +@property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; +@property(atomic, assign) NSTimeInterval maxRetryInterval; +@property(atomic, assign) NSTimeInterval minRetryInterval; +@property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; + +#if GTM_BACKGROUND_TASK_FETCHING +@property(atomic, assign) BOOL skipBackgroundTask; +#endif + +// A default useragent of GTMFetcherStandardUserAgentString(nil) will be given to each fetcher +// created by this service unless the request already has a user-agent header set. +// This default will be added starting with builds with the SDKs for OS X 10.11 and iOS 9. +// +// To use the configuration's default user agent, set this property to nil. +@property(atomic, copy, GTM_NULLABLE) NSString *userAgent; + +// The authorizer to attach to the created fetchers. If a specific fetcher should +// not authorize its requests, the fetcher's authorizer property may be set to nil +// before the fetch begins. +@property(atomic, strong, GTM_NULLABLE) id authorizer; + +// Delegate queue used by the session when calling back to the fetcher. The default +// is the main queue. Changing this does not affect the queue used to call back to the +// application; that is specified by the callbackQueue property above. +@property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; + +// When enabled, indicates the same session should be used by subsequent fetchers. +// +// This is enabled by default. +@property(atomic, assign) BOOL reuseSession; + +// Sets the delay until an unused session is invalidated. +// The default interval is 60 seconds. +// +// If the interval is set to 0, then any reused session is not invalidated except by +// explicitly invoking -resetSession. Be aware that setting the interval to 0 thus +// causes the session's delegate to be retained until the session is explicitly reset. +@property(atomic, assign) NSTimeInterval unusedSessionTimeout; + +// If shouldReuseSession is enabled, this will force creation of a new session when future +// fetchers begin. +- (void)resetSession; + +// Create a fetcher +// +// These methods will return a fetcher. If successfully created, the connection +// will hold a strong reference to it for the life of the connection as well. +// So the caller doesn't have to hold onto the fetcher explicitly unless they +// want to be able to monitor or cancel it. +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; +- (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL; +- (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString; + +// Common method for fetcher creation. +// +// -fetcherWithRequest:fetcherClass: may be overridden to customize creation of +// fetchers. This is the ONLY method in the GTMSessionFetcher library intended to +// be overridden. +- (id)fetcherWithRequest:(NSURLRequest *)request + fetcherClass:(Class)fetcherClass; + +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; + +- (NSUInteger)numberOfFetchers; // running + delayed fetchers +- (NSUInteger)numberOfRunningFetchers; +- (NSUInteger)numberOfDelayedFetchers; + +// Return a list of all running or delayed fetchers. This includes fetchers created +// by the service which have been started and have not yet stopped. +// +// Returns an array of fetcher objects, or nil if none. +- (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchers; + +// Search for running or delayed fetchers with the specified URL. +// +// Returns an array of fetcher objects found, or nil if none found. +- (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchersWithRequestURL:(NSURL *)requestURL; + +- (void)stopAllFetchers; + +// Methods for use by the fetcher class only. +- (GTM_NULLABLE NSURLSession *)session; +- (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; +- (GTM_NULLABLE id)sessionDelegate; +- (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; + +// The testBlock can inspect its fetcher parameter's request property to +// determine which fetcher is being faked. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; + +@end + +@interface GTMSessionFetcherService (TestingSupport) + +// Convenience methods to create a fetcher service for testing. +// +// Fetchers generated by this mock fetcher service will not perform any +// network operation, but will invoke callbacks and provide the supplied data +// or error to the completion handler. +// +// You can make more customized mocks by setting the test block property of the service +// or fetcher; the test block can inspect the fetcher's request or other properties. +// +// See the description of the testBlock property below. ++ (instancetype)mockFetcherServiceWithFakedData:(GTM_NULLABLE NSData *)fakedDataOrNil + fakedError:(GTM_NULLABLE NSError *)fakedErrorOrNil; ++ (instancetype)mockFetcherServiceWithFakedData:(GTM_NULLABLE NSData *)fakedDataOrNil + fakedResponse:(NSHTTPURLResponse *)fakedResponse + fakedError:(GTM_NULLABLE NSError *)fakedErrorOrNil; + +// Spin the run loop and discard events (or, if not on the main thread, just sleep the thread) +// until all running and delayed fetchers have completed. +// +// This is only for use in testing or in tools without a user interface. +// +// Synchronous fetches should never be done by shipping apps; they are +// sufficient reason for rejection from the app store. +// +// Returns NO if timed out. +- (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds; + +@end + +@interface GTMSessionFetcherService (BackwardsCompatibilityOnly) + +// Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. +// This method is just for compatibility with the old fetcher. +@property(atomic, assign) NSInteger cookieStorageMethod; + +@end + +GTM_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m new file mode 100644 index 0000000..ad0c4bd --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m @@ -0,0 +1,1365 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionFetcherService.h" + +NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification + = @"kGTMSessionFetcherServiceSessionBecameInvalidNotification"; +NSString *const kGTMSessionFetcherServiceSessionKey + = @"kGTMSessionFetcherServiceSessionKey"; + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (ServiceMethods) +- (BOOL)beginFetchMayDelay:(BOOL)mayDelay + mayAuthorize:(BOOL)mayAuthorize; +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionFetcherService () + +@property(atomic, strong, readwrite) NSDictionary *delayedFetchersByHost; +@property(atomic, strong, readwrite) NSDictionary *runningFetchersByHost; + +@end + +// Since NSURLSession doesn't support a separate delegate per task (!), instances of this +// class serve as a session delegate trampoline. +// +// This class maps a session's tasks to fetchers, and resends delegate messages to the task's +// fetcher. +@interface GTMSessionFetcherSessionDelegateDispatcher : NSObject + +// The session for the tasks in this dispatcher's task-to-fetcher map. +@property(atomic) NSURLSession *session; + +// The timer interval for invalidating a session that has no active tasks. +@property(atomic) NSTimeInterval discardInterval; + +// The current discard timer. +@property(atomic, readonly) NSTimer *discardTimer; + + +- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService + sessionDiscardInterval:(NSTimeInterval)discardInterval; + +- (void)setFetcher:(GTMSessionFetcher *)fetcher + forTask:(NSURLSessionTask *)task; +- (void)removeFetcher:(GTMSessionFetcher *)fetcher; + +// Before using a session, tells the delegate dispatcher to stop the discard timer. +- (void)startSessionUsage; + +// When abandoning a delegate dispatcher, we want to avoid the session retaining +// the delegate after tasks complete. +- (void)abandon; + +@end + + +@implementation GTMSessionFetcherService { + NSMutableDictionary *_delayedFetchersByHost; + NSMutableDictionary *_runningFetchersByHost; + NSUInteger _maxRunningFetchersPerHost; + + // When this ivar is nil, the service will not reuse sessions. + GTMSessionFetcherSessionDelegateDispatcher *_delegateDispatcher; + + // Fetchers will wait on this if another fetcher is creating the shared NSURLSession. + dispatch_semaphore_t _sessionCreationSemaphore; + + dispatch_queue_t _callbackQueue; + NSOperationQueue *_delegateQueue; + NSHTTPCookieStorage *_cookieStorage; + NSString *_userAgent; + NSTimeInterval _timeout; + + NSURLCredential *_credential; // Username & password. + NSURLCredential *_proxyCredential; // Credential supplied to proxy servers. + + NSInteger _cookieStorageMethod; + + id _authorizer; + + // For waitForCompletionOfAllFetchersWithTimeout: we need to wait on stopped fetchers since + // they've not yet finished invoking their queued callbacks. This array is nil except when + // waiting on fetchers. + NSMutableArray *_stoppedFetchersToWaitFor; + + // For fetchers that enqueued their callbacks before stopAllFetchers was called on the service, + // set a barrier so the callbacks know to bail out. + NSDate *_stoppedAllFetchersDate; +} + +@synthesize maxRunningFetchersPerHost = _maxRunningFetchersPerHost, + configuration = _configuration, + configurationBlock = _configurationBlock, + cookieStorage = _cookieStorage, + userAgent = _userAgent, + challengeBlock = _challengeBlock, + credential = _credential, + proxyCredential = _proxyCredential, + allowedInsecureSchemes = _allowedInsecureSchemes, + allowLocalhostRequest = _allowLocalhostRequest, + allowInvalidServerCertificates = _allowInvalidServerCertificates, + retryEnabled = _retryEnabled, + retryBlock = _retryBlock, + maxRetryInterval = _maxRetryInterval, + minRetryInterval = _minRetryInterval, + properties = _properties, + unusedSessionTimeout = _unusedSessionTimeout, + testBlock = _testBlock; + +#if GTM_BACKGROUND_TASK_FETCHING +@synthesize skipBackgroundTask = _skipBackgroundTask; +#endif + +- (instancetype)init { + self = [super init]; + if (self) { + _delayedFetchersByHost = [[NSMutableDictionary alloc] init]; + _runningFetchersByHost = [[NSMutableDictionary alloc] init]; + _maxRunningFetchersPerHost = 10; + _cookieStorageMethod = -1; + _unusedSessionTimeout = 60.0; + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + _callbackQueue = dispatch_get_main_queue(); + + _delegateQueue = [[NSOperationQueue alloc] init]; + _delegateQueue.maxConcurrentOperationCount = 1; + _delegateQueue.name = @"com.google.GTMSessionFetcher.NSURLSessionDelegateQueue"; + + _sessionCreationSemaphore = dispatch_semaphore_create(1); + + // Starting with the SDKs for OS X 10.11/iOS 9, the service has a default useragent. + // Apps can remove this and get the default system "CFNetwork" useragent by setting the + // fetcher service's userAgent property to nil. +#if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) + _userAgent = GTMFetcherStandardUserAgentString(nil); +#endif + } + return self; +} + +- (void)dealloc { + [self detachAuthorizer]; + [_delegateDispatcher abandon]; +} + +#pragma mark Generate a new fetcher + +// Clients may override this method. Clients should not override any other library methods. +- (id)fetcherWithRequest:(NSURLRequest *)request + fetcherClass:(Class)fetcherClass { + GTMSessionFetcher *fetcher = [[fetcherClass alloc] initWithRequest:request + configuration:self.configuration]; + fetcher.callbackQueue = self.callbackQueue; + fetcher.sessionDelegateQueue = self.sessionDelegateQueue; + fetcher.challengeBlock = self.challengeBlock; + fetcher.credential = self.credential; + fetcher.proxyCredential = self.proxyCredential; + fetcher.authorizer = self.authorizer; + fetcher.cookieStorage = self.cookieStorage; + fetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; + fetcher.allowLocalhostRequest = self.allowLocalhostRequest; + fetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; + fetcher.configurationBlock = self.configurationBlock; + fetcher.retryEnabled = self.retryEnabled; + fetcher.retryBlock = self.retryBlock; + fetcher.maxRetryInterval = self.maxRetryInterval; + fetcher.minRetryInterval = self.minRetryInterval; + fetcher.properties = self.properties; + fetcher.service = self; + if (self.cookieStorageMethod >= 0) { + [fetcher setCookieStorageMethod:self.cookieStorageMethod]; + } + +#if GTM_BACKGROUND_TASK_FETCHING + fetcher.skipBackgroundTask = self.skipBackgroundTask; +#endif + + NSString *userAgent = self.userAgent; + if (userAgent.length > 0 + && [request valueForHTTPHeaderField:@"User-Agent"] == nil) { + [fetcher setRequestValue:userAgent + forHTTPHeaderField:@"User-Agent"]; + } + fetcher.testBlock = self.testBlock; + + return fetcher; +} + +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request { + return [self fetcherWithRequest:request + fetcherClass:[GTMSessionFetcher class]]; +} + +- (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL { + return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; +} + +- (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString { + NSURL *url = [NSURL URLWithString:requestURLString]; + return [self fetcherWithURL:url]; +} + +// Returns a session for the fetcher's host, or nil. +- (NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLSession *session = _delegateDispatcher.session; + return session; + } +} + +// Returns a session for the fetcher's host, or nil. For shared sessions, this +// waits on a semaphore, blocking other fetchers while the caller creates the +// session if needed. +- (NSURLSession *)sessionForFetcherCreation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + if (!_delegateDispatcher) { + // This fetcher is creating a non-shared session, so skip the semaphore usage. + return nil; + } + } + + // Wait if another fetcher is currently creating a session; avoid waiting + // inside the @synchronized block, as that can deadlock. + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Before getting the NSURLSession for task creation, it is + // important to invalidate and nil out the session discard timer; otherwise + // the session can be invalidated between when it is returned to the + // fetcher, and when the fetcher attempts to create its NSURLSessionTask. + [_delegateDispatcher startSessionUsage]; + + NSURLSession *session = _delegateDispatcher.session; + if (session) { + // The calling fetcher will receive a preexisting session, so + // we can allow other fetchers to create a session. + dispatch_semaphore_signal(_sessionCreationSemaphore); + } else { + // No existing session was obtained, so the calling fetcher will create the session; + // it *must* invoke fetcherDidCreateSession: to signal the dispatcher's semaphore after + // the session has been created (or fails to be created) to avoid a hang. + } + return session; + } +} + +- (id)sessionDelegate { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateDispatcher; + } +} + +#pragma mark Queue Management + +- (void)addRunningFetcher:(GTMSessionFetcher *)fetcher + forHost:(NSString *)host { + // Add to the array of running fetchers for this host, creating the array if needed. + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + if (runningForHost == nil) { + runningForHost = [NSMutableArray arrayWithObject:fetcher]; + [_runningFetchersByHost setObject:runningForHost forKey:host]; + } else { + [runningForHost addObject:fetcher]; + } +} + +- (void)addDelayedFetcher:(GTMSessionFetcher *)fetcher + forHost:(NSString *)host { + // Add to the array of delayed fetchers for this host, creating the array if needed. + NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + if (delayedForHost == nil) { + delayedForHost = [NSMutableArray arrayWithObject:fetcher]; + [_delayedFetchersByHost setObject:delayedForHost forKey:host]; + } else { + [delayedForHost addObject:fetcher]; + } +} + +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSString *host = fetcher.request.URL.host; + if (host == nil) { + return NO; + } + NSArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + NSUInteger idx = [delayedForHost indexOfObjectIdenticalTo:fetcher]; + BOOL isDelayed = (delayedForHost != nil) && (idx != NSNotFound); + return isDelayed; + } +} + +- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher { + // Entry point from the fetcher + NSURL *requestURL = fetcher.request.URL; + NSString *host = requestURL.host; + + // Addresses "file:///path" case where localhost is the implicit host. + if (host.length == 0 && [requestURL isFileURL]) { + host = @"localhost"; + } + + if (host.length == 0) { + // Data URIs legitimately have no host, reject other hostless URLs. + GTMSESSION_ASSERT_DEBUG([[requestURL scheme] isEqual:@"data"], @"%@ lacks host", fetcher); + return YES; + } + + BOOL shouldBeginResult; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + if (runningForHost != nil + && [runningForHost indexOfObjectIdenticalTo:fetcher] != NSNotFound) { + GTMSESSION_ASSERT_DEBUG(NO, @"%@ was already running", fetcher); + return YES; + } + + BOOL shouldRunNow = (fetcher.usingBackgroundSession + || _maxRunningFetchersPerHost == 0 + || _maxRunningFetchersPerHost > + [[self class] numberOfNonBackgroundSessionFetchers:runningForHost]); + if (shouldRunNow) { + [self addRunningFetcher:fetcher forHost:host]; + shouldBeginResult = YES; + } else { + [self addDelayedFetcher:fetcher forHost:host]; + shouldBeginResult = NO; + } + } // @synchronized(self) + + // We'll save the host that serves as the key for this fetcher's array + // to avoid any chance of the underlying request changing, stranding + // the fetcher in the wrong array + fetcher.serviceHost = host; + + return shouldBeginResult; +} + +- (void)startFetcher:(GTMSessionFetcher *)fetcher { + [fetcher beginFetchMayDelay:NO + mayAuthorize:YES]; +} + +// Internal utility. Returns a fetcher's delegate if it's a dispatcher, or nil if the fetcher +// is its own delegate and has no dispatcher. +- (GTMSessionFetcherSessionDelegateDispatcher *)delegateDispatcherForFetcher:(GTMSessionFetcher *)fetcher { + GTMSessionCheckNotSynchronized(self); + + NSURLSession *fetcherSession = fetcher.session; + if (fetcherSession) { + id fetcherDelegate = fetcherSession.delegate; + BOOL hasDispatcher = (fetcherDelegate != nil && fetcherDelegate != fetcher); + if (hasDispatcher) { + GTMSESSION_ASSERT_DEBUG([fetcherDelegate isKindOfClass:[GTMSessionFetcherSessionDelegateDispatcher class]], + @"Fetcher delegate class: %@", [fetcherDelegate class]); + return (GTMSessionFetcherSessionDelegateDispatcher *)fetcherDelegate; + } + } + return nil; +} + +- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher { + if (fetcher.canShareSession) { + NSURLSession *fetcherSession = fetcher.session; + GTMSESSION_ASSERT_DEBUG(fetcherSession != nil, @"Fetcher missing its session: %@", fetcher); + + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + if (delegateDispatcher) { + GTMSESSION_ASSERT_DEBUG(delegateDispatcher.session == nil, + @"Fetcher made an extra session: %@", fetcher); + + // Save this fetcher's session. + delegateDispatcher.session = fetcherSession; + + // Allow other fetchers to request this session now. + dispatch_semaphore_signal(_sessionCreationSemaphore); + } + } +} + +- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher { + // If this fetcher has a separate delegate with a shared session, then + // this fetcher should be added to the delegate's map of tasks to fetchers. + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + if (delegateDispatcher) { + GTMSESSION_ASSERT_DEBUG(fetcher.canShareSession, + @"Inappropriate shared session: %@", fetcher); + + // There should already be a session, from this or a previous fetcher. + // + // Sanity check that the fetcher's session is the delegate's shared session. + NSURLSession *sharedSession = delegateDispatcher.session; + NSURLSession *fetcherSession = fetcher.session; + GTMSESSION_ASSERT_DEBUG(sharedSession != nil, @"Missing delegate session: %@", fetcher); + GTMSESSION_ASSERT_DEBUG(fetcherSession == sharedSession, + @"Inconsistent session: %@ %@ (shared: %@)", + fetcher, fetcherSession, sharedSession); + + if (sharedSession != nil && fetcherSession == sharedSession) { + NSURLSessionTask *task = fetcher.sessionTask; + GTMSESSION_ASSERT_DEBUG(task != nil, @"Missing session task: %@", fetcher); + + if (task) { + [delegateDispatcher setFetcher:fetcher + forTask:task]; + } + } + } +} + +- (void)stopFetcher:(GTMSessionFetcher *)fetcher { + [fetcher stopFetching]; +} + +- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher { + // Entry point from the fetcher + NSString *host = fetcher.serviceHost; + if (!host) { + // fetcher has been stopped previously + return; + } + + // This removeFetcher: invocation is a fallback; typically, fetchers are removed from the task + // map when the task completes. + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + [delegateDispatcher removeFetcher:fetcher]; + + NSMutableArray *fetchersToStart; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // If a test is waiting for all fetchers to stop, it needs to wait for this one + // to invoke its callbacks on the callback queue. + [_stoppedFetchersToWaitFor addObject:fetcher]; + + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + [runningForHost removeObject:fetcher]; + + NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + [delayedForHost removeObject:fetcher]; + + while (delayedForHost.count > 0 + && [[self class] numberOfNonBackgroundSessionFetchers:runningForHost] + < _maxRunningFetchersPerHost) { + // Start another delayed fetcher running, scanning for the minimum + // priority value, defaulting to FIFO for equal priorities + GTMSessionFetcher *nextFetcher = nil; + for (GTMSessionFetcher *delayedFetcher in delayedForHost) { + if (nextFetcher == nil + || delayedFetcher.servicePriority < nextFetcher.servicePriority) { + nextFetcher = delayedFetcher; + } + } + + if (nextFetcher) { + [self addRunningFetcher:nextFetcher forHost:host]; + runningForHost = [_runningFetchersByHost objectForKey:host]; + + [delayedForHost removeObjectIdenticalTo:nextFetcher]; + + if (!fetchersToStart) { + fetchersToStart = [NSMutableArray array]; + } + [fetchersToStart addObject:nextFetcher]; + } + } + + if (runningForHost.count == 0) { + // None left; remove the empty array + [_runningFetchersByHost removeObjectForKey:host]; + } + + if (delayedForHost.count == 0) { + [_delayedFetchersByHost removeObjectForKey:host]; + } + } // @synchronized(self) + + // Start fetchers outside of the synchronized block to avoid a deadlock. + for (GTMSessionFetcher *nextFetcher in fetchersToStart) { + [self startFetcher:nextFetcher]; + } + + // The fetcher is no longer in the running or the delayed array, + // so remove its host and thread properties + fetcher.serviceHost = nil; +} + +- (NSUInteger)numberOfFetchers { + NSUInteger running = [self numberOfRunningFetchers]; + NSUInteger delayed = [self numberOfDelayedFetchers]; + return running + delayed; +} + +- (NSUInteger)numberOfRunningFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger sum = 0; + for (NSString *host in _runningFetchersByHost) { + NSArray *fetchers = [_runningFetchersByHost objectForKey:host]; + sum += fetchers.count; + } + return sum; + } +} + +- (NSUInteger)numberOfDelayedFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger sum = 0; + for (NSString *host in _delayedFetchersByHost) { + NSArray *fetchers = [_delayedFetchersByHost objectForKey:host]; + sum += fetchers.count; + } + return sum; + } +} + +- (NSArray *)issuedFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSMutableArray *allFetchers = [NSMutableArray array]; + void (^accumulateFetchers)(id, id, BOOL *) = ^(NSString *host, + NSArray *fetchersForHost, + BOOL *stop) { + [allFetchers addObjectsFromArray:fetchersForHost]; + }; + [_runningFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; + [_delayedFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; + + GTMSESSION_ASSERT_DEBUG(allFetchers.count == [NSSet setWithArray:allFetchers].count, + @"Fetcher appears multiple times\n running: %@\n delayed: %@", + _runningFetchersByHost, _delayedFetchersByHost); + + return allFetchers.count > 0 ? allFetchers : nil; + } +} + +- (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL { + NSString *host = requestURL.host; + if (host.length == 0) return nil; + + NSURL *targetURL = [requestURL absoluteURL]; + + NSArray *allFetchers = [self issuedFetchers]; + NSIndexSet *indexes = [allFetchers indexesOfObjectsPassingTest:^BOOL(GTMSessionFetcher *fetcher, + NSUInteger idx, + BOOL *stop) { + NSURL *fetcherURL = [fetcher.request.URL absoluteURL]; + return [fetcherURL isEqual:targetURL]; + }]; + + NSArray *result = nil; + if (indexes.count > 0) { + result = [allFetchers objectsAtIndexes:indexes]; + } + return result; +} + +- (void)stopAllFetchers { + NSArray *delayedFetchersByHost; + NSArray *runningFetchersByHost; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Set the time barrier so fetchers know not to call back even if + // the stop calls below occur after the fetchers naturally + // stopped and so were removed from _runningFetchersByHost, + // but while the callbacks were already enqueued before stopAllFetchers + // was invoked. + _stoppedAllFetchersDate = [[NSDate alloc] init]; + + // Remove fetchers from the delayed list to avoid fetcherDidStop: from + // starting more fetchers running as a side effect of stopping one + delayedFetchersByHost = _delayedFetchersByHost.allValues; + [_delayedFetchersByHost removeAllObjects]; + + runningFetchersByHost = _runningFetchersByHost.allValues; + [_runningFetchersByHost removeAllObjects]; + } + + for (NSArray *delayedForHost in delayedFetchersByHost) { + for (GTMSessionFetcher *fetcher in delayedForHost) { + [self stopFetcher:fetcher]; + } + } + + for (NSArray *runningForHost in runningFetchersByHost) { + for (GTMSessionFetcher *fetcher in runningForHost) { + [self stopFetcher:fetcher]; + } + } +} + +- (NSDate *)stoppedAllFetchersDate { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _stoppedAllFetchersDate; + } +} + +#pragma mark Accessors + +- (BOOL)reuseSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateDispatcher != nil; + } +} + +- (void)setReuseSession:(BOOL)shouldReuse { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL wasReusing = (_delegateDispatcher != nil); + if (shouldReuse != wasReusing) { + [self abandonDispatcher]; + if (shouldReuse) { + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + } else { + _delegateDispatcher = nil; + } + } + } +} + +- (void)resetSession { + GTMSessionCheckNotSynchronized(self); + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + [self resetSessionInternal]; + } + + dispatch_semaphore_signal(_sessionCreationSemaphore); +} + +- (void)resetSessionInternal { + GTMSessionCheckSynchronized(self); + + // The old dispatchers may be retained as delegates of any ongoing sessions by those sessions. + if (_delegateDispatcher) { + [self abandonDispatcher]; + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + } +} + +- (void)resetSessionForDispatcherDiscardTimer:(NSTimer *)timer { + GTMSessionCheckNotSynchronized(self); + + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_delegateDispatcher.discardTimer == timer) { + // If the delegate dispatcher's current discardTimer is the same object as the timer + // that fired, no fetcher has recently attempted to start using the session by calling + // startSessionUsage, which invalidates and nils out the timer. + [self resetSessionInternal]; + } else { + // A fetcher has invalidated the timer between its triggering and now, potentially + // meaning a fetcher has requested access to the NSURLSession, and may be in the process + // of starting a new task. The dispatcher should not be abandoned, as this can lead + // to a race condition between calling -finishTasksAndInvalidate on the NSURLSession + // and the fetcher attempting to create a new task. + } + } + + dispatch_semaphore_signal(_sessionCreationSemaphore); +} + +- (NSTimeInterval)unusedSessionTimeout { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _unusedSessionTimeout; + } +} + +- (void)setUnusedSessionTimeout:(NSTimeInterval)timeout { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _unusedSessionTimeout = timeout; + _delegateDispatcher.discardInterval = timeout; + } +} + +// This method should be called inside of @synchronized(self) +- (void)abandonDispatcher { + GTMSessionCheckSynchronized(self); + [_delegateDispatcher abandon]; +} + +- (NSDictionary *)runningFetchersByHost { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_runningFetchersByHost copy]; + } +} + +- (void)setRunningFetchersByHost:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _runningFetchersByHost = [dict mutableCopy]; + } +} + +- (NSDictionary *)delayedFetchersByHost { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_delayedFetchersByHost copy]; + } +} + +- (void)setDelayedFetchersByHost:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delayedFetchersByHost = [dict mutableCopy]; + } +} + +- (id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _authorizer; + } +} + +- (void)setAuthorizer:(id)obj { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (obj != _authorizer) { + [self detachAuthorizer]; + } + + _authorizer = obj; + } + + // Use the fetcher service for the authorization fetches if the auth + // object supports fetcher services + if ([obj respondsToSelector:@selector(setFetcherService:)]) { +#if GTM_USE_SESSION_FETCHER + [obj setFetcherService:self]; +#else + [obj setFetcherService:(id)self]; +#endif + } +} + +// This should be called inside a @synchronized(self) block except during dealloc. +- (void)detachAuthorizer { + // This method is called by the fetcher service's dealloc and setAuthorizer: + // methods; do not override. + // + // The fetcher service retains the authorizer, and the authorizer has a + // weak pointer to the fetcher service (a non-zeroing pointer for + // compatibility with iOS 4 and Mac OS X 10.5/10.6.) + // + // When this fetcher service no longer uses the authorizer, we want to remove + // the authorizer's dependence on the fetcher service. Authorizers can still + // function without a fetcher service. + if ([_authorizer respondsToSelector:@selector(fetcherService)]) { + id authFetcherService = [_authorizer fetcherService]; + if (authFetcherService == self) { + [_authorizer setFetcherService:nil]; + } + } +} + +- (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _callbackQueue; + } // @synchronized(self) +} + +- (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _callbackQueue = queue ?: dispatch_get_main_queue(); + } // @synchronized(self) +} + +- (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateQueue; + } // @synchronized(self) +} + +- (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateQueue = queue ?: [NSOperationQueue mainQueue]; + } // @synchronized(self) +} + +- (NSOperationQueue *)delegateQueue { + // Provided for compatibility with the old fetcher service. The gtm-oauth2 code respects + // any custom delegate queue for calling the app. + return nil; +} + ++ (NSUInteger)numberOfNonBackgroundSessionFetchers:(NSArray *)fetchers { + NSUInteger sum = 0; + for (GTMSessionFetcher *fetcher in fetchers) { + if (!fetcher.usingBackgroundSession) { + ++sum; + } + } + return sum; +} + +@end + +@implementation GTMSessionFetcherService (TestingSupport) + ++ (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil + fakedError:(NSError *)fakedErrorOrNil { +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + NSURL *url = [NSURL URLWithString:@"http://example.invalid"]; + NSHTTPURLResponse *fakedResponse = + [[NSHTTPURLResponse alloc] initWithURL:url + statusCode:(fakedErrorOrNil ? 500 : 200) + HTTPVersion:@"HTTP/1.1" + headerFields:nil]; + return [self mockFetcherServiceWithFakedData:fakedDataOrNil + fakedResponse:fakedResponse + fakedError:fakedErrorOrNil]; +#else + GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled"); + return nil; +#endif // GTM_DISABLE_FETCHER_TEST_BLOCK +} + ++ (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil + fakedResponse:(NSHTTPURLResponse *)fakedResponse + fakedError:(NSError *)fakedErrorOrNil { +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + GTMSessionFetcherService *service = [[self alloc] init]; + service.allowedInsecureSchemes = @[ @"http" ]; + service.testBlock = ^(GTMSessionFetcher *fetcherToTest, + GTMSessionFetcherTestResponse testResponse) { + testResponse(fakedResponse, fakedDataOrNil, fakedErrorOrNil); + }; + return service; +#else + GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled"); + return nil; +#endif // GTM_DISABLE_FETCHER_TEST_BLOCK +} + +#pragma mark Synchronous Wait for Unit Testing + +- (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds { + NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + _stoppedFetchersToWaitFor = [NSMutableArray array]; + + BOOL shouldSpinRunLoop = [NSThread isMainThread]; + const NSTimeInterval kSpinInterval = 0.001; + BOOL didTimeOut = NO; + while (([self numberOfFetchers] > 0 || _stoppedFetchersToWaitFor.count > 0)) { + didTimeOut = [giveUpDate timeIntervalSinceNow] < 0; + if (didTimeOut) break; + + GTMSessionFetcher *stoppedFetcher = _stoppedFetchersToWaitFor.firstObject; + if (stoppedFetcher) { + [_stoppedFetchersToWaitFor removeObject:stoppedFetcher]; + [stoppedFetcher waitForCompletionWithTimeout:10.0 * kSpinInterval]; + } + + if (shouldSpinRunLoop) { + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + [NSThread sleepForTimeInterval:kSpinInterval]; + } + } + _stoppedFetchersToWaitFor = nil; + + return !didTimeOut; +} + +@end + +@implementation GTMSessionFetcherService (BackwardsCompatibilityOnly) + +- (NSInteger)cookieStorageMethod { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _cookieStorageMethod; + } +} + +- (void)setCookieStorageMethod:(NSInteger)cookieStorageMethod { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _cookieStorageMethod = cookieStorageMethod; + } +} + +@end + +@implementation GTMSessionFetcherSessionDelegateDispatcher { + __weak GTMSessionFetcherService *_parentService; + NSURLSession *_session; + + // The task map maps NSURLSessionTasks to GTMSessionFetchers + NSMutableDictionary *_taskToFetcherMap; + // The discard timer will invalidate sessions after the session's last task completes. + NSTimer *_discardTimer; + NSTimeInterval _discardInterval; +} + +@synthesize discardInterval = _discardInterval, + session = _session; + +- (instancetype)init { + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService + sessionDiscardInterval:(NSTimeInterval)discardInterval { + self = [super init]; + if (self) { + _discardInterval = discardInterval; + _parentService = parentService; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p %@ %@", + [self class], self, + _session ?: @"", + _taskToFetcherMap.count > 0 ? _taskToFetcherMap : @""]; +} + +- (NSTimer *)discardTimer { + GTMSessionCheckNotSynchronized(self); + @synchronized(self) { + return _discardTimer; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)startDiscardTimer { + GTMSessionCheckSynchronized(self); + [_discardTimer invalidate]; + _discardTimer = nil; + if (_discardInterval > 0) { + _discardTimer = [NSTimer timerWithTimeInterval:_discardInterval + target:self + selector:@selector(discardTimerFired:) + userInfo:nil + repeats:NO]; + [_discardTimer setTolerance:(_discardInterval / 10)]; + [[NSRunLoop mainRunLoop] addTimer:_discardTimer forMode:NSRunLoopCommonModes]; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)destroyDiscardTimer { + GTMSessionCheckSynchronized(self); + [_discardTimer invalidate]; + _discardTimer = nil; +} + +- (void)discardTimerFired:(NSTimer *)timer { + GTMSessionFetcherService *service; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger numberOfTasks = _taskToFetcherMap.count; + if (numberOfTasks == 0) { + service = _parentService; + } + } + + // Inform the service that the discard timer has fired, and should check whether the + // service can abandon us. -resetSession cannot be called directly, as there is a + // race condition that must be guarded against with the NSURLSession being returned + // from sessionForFetcherCreation outside other locks. The service can take steps + // to prevent resetting the session if that has occurred. + // + // The service must be called from outside the @synchronized block. + [service resetSessionForDispatcherDiscardTimer:timer]; +} + +- (void)abandon { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self destroySessionAndTimer]; + } +} + +- (void)startSessionUsage { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self destroyDiscardTimer]; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)destroySessionAndTimer { + GTMSessionCheckSynchronized(self); + [self destroyDiscardTimer]; + + // Break any retain cycle from the session holding the delegate. + [_session finishTasksAndInvalidate]; + + // Immediately clear the session so no new task may be issued with it. + // + // The _taskToFetcherMap needs to stay valid until the outstanding tasks finish. + _session = nil; +} + +- (void)setFetcher:(GTMSessionFetcher *)fetcher forTask:(NSURLSessionTask *)task { + GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"missing fetcher"); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_taskToFetcherMap == nil) { + _taskToFetcherMap = [[NSMutableDictionary alloc] init]; + } + + if (fetcher) { + [_taskToFetcherMap setObject:fetcher forKey:task]; + [self destroyDiscardTimer]; + } + } +} + +- (void)removeFetcher:(GTMSessionFetcher *)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Typically, a fetcher should be removed when its task invokes + // URLSession:task:didCompleteWithError:. + // + // When fetching with a testBlock, though, the task completed delegate + // method may not be invoked, requiring cleanup here. + NSArray *tasks = [_taskToFetcherMap allKeysForObject:fetcher]; + GTMSESSION_ASSERT_DEBUG(tasks.count <= 1, @"fetcher task not unmapped: %@", tasks); + [_taskToFetcherMap removeObjectsForKeys:tasks]; + + if (_taskToFetcherMap.count == 0) { + [self startDiscardTimer]; + } + } +} + +// This helper method provides synchronized access to the task map for the delegate +// methods below. +- (id)fetcherForTask:(NSURLSessionTask *)task { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_taskToFetcherMap objectForKey:task]; + } +} + +- (void)removeTaskFromMap:(NSURLSessionTask *)task { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_taskToFetcherMap removeObjectForKey:task]; + } +} + +- (void)setSession:(NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = session; + } +} + +- (NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _session; + } +} + +- (NSTimeInterval)discardInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _discardInterval; + } +} + +- (void)setDiscardInterval:(NSTimeInterval)interval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _discardInterval = interval; + } +} + +// NSURLSessionDelegate protocol methods. + +// - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session; +// +// TODO(seh): How do we route this to an appropriate fetcher? + + +- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", + [self class], self, session, error); + NSDictionary *localTaskToFetcherMap; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = nil; + + localTaskToFetcherMap = [_taskToFetcherMap copy]; + } + + // Any "suspended" tasks may not have received callbacks from NSURLSession when the session + // completes; we'll call them now. + [localTaskToFetcherMap enumerateKeysAndObjectsUsingBlock:^(NSURLSessionTask *task, + GTMSessionFetcher *fetcher, + BOOL *stop) { + if (fetcher.session == session) { + // Our delegate method URLSession:task:didCompleteWithError: will rely on + // _taskToFetcherMap so that should still contain this fetcher. + NSError *canceledError = [NSError errorWithDomain:NSURLErrorDomain + code:NSURLErrorCancelled + userInfo:nil]; + [self URLSession:session task:task didCompleteWithError:canceledError]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"Unexpected session in fetcher: %@ has %@ (expected %@)", + fetcher, fetcher.session, session); + } + }]; + + // Our tests rely on this notification to know the session discard timer fired. + NSDictionary *userInfo = @{ kGTMSessionFetcherServiceSessionKey : session }; + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc postNotificationName:kGTMSessionFetcherServiceSessionBecameInvalidNotification + object:_parentService + userInfo:userInfo]; +} + + +#pragma mark - NSURLSessionTaskDelegate + +// NSURLSessionTaskDelegate protocol methods. +// +// We won't test here if the fetcher responds to these since we only want this +// class to implement the same delegate methods the fetcher does (so NSURLSession's +// tests for respondsToSelector: will have the same result whether the session +// delegate is the fetcher or this dispatcher.) + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task +willPerformHTTPRedirection:response + newRequest:request + completionHandler:completionHandler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))handler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + didReceiveChallenge:challenge + completionHandler:handler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))handler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + needNewBodyStream:handler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + didSendBodyData:bytesSent + totalBytesSent:totalBytesSent +totalBytesExpectedToSend:totalBytesExpectedToSend]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error { + id fetcher = [self fetcherForTask:task]; + + // This is the usual way tasks are removed from the task map. + [self removeTaskFromMap:task]; + + [fetcher URLSession:session + task:task + didCompleteWithError:error]; +} + +// NSURLSessionDataDelegate protocol methods. + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))handler { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + didReceiveResponse:response + completionHandler:handler]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { + id fetcher = [self fetcherForTask:dataTask]; + GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"Missing fetcher for %@", dataTask); + [self removeTaskFromMap:dataTask]; + if (fetcher) { + GTMSESSION_ASSERT_DEBUG([fetcher isKindOfClass:[GTMSessionFetcher class]], + @"Expecting GTMSessionFetcher"); + [self setFetcher:(GTMSessionFetcher *)fetcher forTask:downloadTask]; + } + + [fetcher URLSession:session + dataTask:dataTask +didBecomeDownloadTask:downloadTask]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + didReceiveData:data]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *))handler { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + willCacheResponse:proposedResponse + completionHandler:handler]; +} + +// NSURLSessionDownloadDelegate protocol methods. + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask +didFinishDownloadingToURL:location]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalWritten +totalBytesExpectedToWrite:(int64_t)totalExpected { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask + didWriteData:bytesWritten + totalBytesWritten:totalWritten +totalBytesExpectedToWrite:totalExpected]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask + didResumeAtOffset:fileOffset + expectedTotalBytes:expectedTotalBytes]; +} + +@end diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h new file mode 100644 index 0000000..a098ce9 --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h @@ -0,0 +1,166 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// GTMSessionUploadFetcher implements Google's resumable upload protocol. + +// +// This subclass of GTMSessionFetcher simulates the series of fetches +// needed for chunked upload as a single fetch operation. +// +// Protocol document: TBD +// +// To the client, the only fetcher that exists is this class; the subsidiary +// fetchers needed for uploading chunks are not visible (though the most recent +// chunk fetcher may be accessed via the -activeFetcher or -chunkFetcher methods, and +// -responseHeaders and -statusCode reflect results from the most recent chunk +// fetcher.) +// +// Chunk fetchers are discarded as soon as they have completed. +// +// The protocol also allows for a cancellation notification request to be sent to the +// server to allow discarding of the currently uploaded data and this will be sent +// automatically upon calling stopFetching if the upload has already started. +// +// Note: Unlike the fetcher superclass, the methods of GTMSessionUploadFetcher should +// only be used from the main thread until further work is done to make this subclass +// thread-safe. + +#import "GTMSessionFetcher.h" +#import "GTMSessionFetcherService.h" + +GTM_ASSUME_NONNULL_BEGIN + +// The value to use for file size parameters when the file size is not yet known. +extern int64_t const kGTMSessionUploadFetcherUnknownFileSize; + +// Unless an application knows it needs a smaller chunk size, it should use the standard +// chunk size, which sends the entire file as a single chunk to minimize upload overhead. +// Setting an explicit chunk size that comfortably fits in memory is advisable for large +// uploads. +extern int64_t const kGTMSessionUploadFetcherStandardChunkSize; + +// When uploading requires data buffer allocations (such as uploading from an NSData or +// an NSFileHandle) this is the maximum buffer size that will be created by the fetcher. +extern int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize; + +// Notification that the upload location URL was provided by the server. +extern NSString *const kGTMSessionFetcherUploadLocationObtainedNotification; + +// Block to provide data during uploads. +// +// Response data may be allocated with dataWithBytesNoCopy:length:freeWhenDone: for efficiency, +// and released after the response block returns. +// +// If the length of the file being uploaded is unknown or already set, send +// kGTMSessionUploadFetcherUnknownFileSize for |fullUploadLength|. Otherwise, set |fullUploadLength| +// to its proper value. +// +// Pass nil as the data (and optionally an NSError) for a failure. +typedef void (^GTMSessionUploadFetcherDataProviderResponse)(NSData * GTM_NULLABLE_TYPE data, + int64_t fullUploadLength, + NSError * GTM_NULLABLE_TYPE error); +// Do not call the response with an NSData object with less data than the requested length unless +// you are passing the fullUploadLength to the fetcher for the first time and it is the last chunk +// of data in the file being uploaded. +typedef void (^GTMSessionUploadFetcherDataProvider)(int64_t offset, int64_t length, + GTMSessionUploadFetcherDataProviderResponse response); + +// Block to be notified about the final status of the cancellation request started in stopFetching. +// +// |fetcher| will be the cancel request that was sent to the server, or nil if stopFetching is not +// going to send a cancel request. If |fetcher| is provided, the other parameters correspond to the +// completion handler of the cancellation request fetcher. +typedef void (^GTMSessionUploadFetcherCancellationHandler)( + GTMSessionFetcher * GTM_NULLABLE_TYPE fetcher, + NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); + +@interface GTMSessionUploadFetcher : GTMSessionFetcher + +// Create an upload fetcher specifying either the request or the resume location URL, +// then set an upload data source using one of these: +// +// setUploadFileURL: +// setUploadDataLength:provider: +// setUploadFileHandle: +// setUploadData: + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; + ++ (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; + +// Allows dataProviders for files of unknown length. Pass kGTMSessionUploadFetcherUnknownFileSize as +// |fullLength| if the length is unknown. +- (void)setUploadDataLength:(int64_t)fullLength + provider:(GTM_NULLABLE GTMSessionUploadFetcherDataProvider)block; + ++ (NSArray *)uploadFetchersForBackgroundSessions; ++ (GTM_NULLABLE instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier; + +- (void)pauseFetching; +- (void)resumeFetching; +- (BOOL)isPaused; + +@property(atomic, strong, GTM_NULLABLE) NSURL *uploadLocationURL; +@property(atomic, strong, GTM_NULLABLE) NSData *uploadData; +@property(atomic, strong, GTM_NULLABLE) NSURL *uploadFileURL; +@property(atomic, strong, GTM_NULLABLE) NSFileHandle *uploadFileHandle; +@property(atomic, copy, readonly, GTM_NULLABLE) GTMSessionUploadFetcherDataProvider uploadDataProvider; +@property(atomic, copy) NSString *uploadMIMEType; +@property(atomic, assign) int64_t chunkSize; +@property(atomic, readonly, assign) int64_t currentOffset; + +// The fetcher for the current data chunk, if any +@property(atomic, strong, GTM_NULLABLE) GTMSessionFetcher *chunkFetcher; + +// The active fetcher is the current chunk fetcher, or the upload fetcher itself +// if no chunk fetcher has yet been created. +@property(atomic, readonly) GTMSessionFetcher *activeFetcher; + +// The last request made by an active fetcher. Useful for testing. +@property(atomic, readonly, GTM_NULLABLE) NSURLRequest *lastChunkRequest; + +// The status code from the most recently-completed fetch. +@property(atomic, assign) NSInteger statusCode; + +// Invoked as part of the stop fetching process. Invoked immediately if there is no upload in +// progress, otherwise invoked with the results of the attempt to notify the server that the +// upload will not continue. +// +// Unlike other callbacks, since this is related specifically to the stopFetching flow it is not +// cleared by stopFetching. It will instead clear itself after it is invoked or if the completion +// has occured before stopFetching is called. +@property(atomic, copy, GTM_NULLABLE) GTMSessionUploadFetcherCancellationHandler + cancellationHandler; + +// Exposed for testing only. +@property(atomic, readonly, GTM_NULLABLE) dispatch_queue_t delegateCallbackQueue; +@property(atomic, readonly, GTM_NULLABLE) GTMSessionFetcherCompletionHandler delegateCompletionHandler; + +@end + +@interface GTMSessionFetcher (GTMSessionUploadFetcherMethods) + +@property(readonly, GTM_NULLABLE) GTMSessionUploadFetcher *parentUploadFetcher; + +@end + +GTM_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m new file mode 100644 index 0000000..9ac51ba --- /dev/null +++ b/My Mind/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m @@ -0,0 +1,1954 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionUploadFetcher.h" + +static NSString *const kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey = @"_upChunk"; +static NSString *const kGTMSessionIdentifierUploadFileURLMetadataKey = @"_upFileURL"; +static NSString *const kGTMSessionIdentifierUploadFileLengthMetadataKey = @"_upFileLen"; +static NSString *const kGTMSessionIdentifierUploadLocationURLMetadataKey = @"_upLocURL"; +static NSString *const kGTMSessionIdentifierUploadMIMETypeMetadataKey = @"_uploadMIME"; +static NSString *const kGTMSessionIdentifierUploadChunkSizeMetadataKey = @"_upChSize"; +static NSString *const kGTMSessionIdentifierUploadCurrentOffsetMetadataKey = @"_upOffset"; + +static NSString *const kGTMSessionHeaderXGoogUploadChunkGranularity = @"X-Goog-Upload-Chunk-Granularity"; +static NSString *const kGTMSessionHeaderXGoogUploadCommand = @"X-Goog-Upload-Command"; +static NSString *const kGTMSessionHeaderXGoogUploadContentLength = @"X-Goog-Upload-Content-Length"; +static NSString *const kGTMSessionHeaderXGoogUploadContentType = @"X-Goog-Upload-Content-Type"; +static NSString *const kGTMSessionHeaderXGoogUploadOffset = @"X-Goog-Upload-Offset"; +static NSString *const kGTMSessionHeaderXGoogUploadProtocol = @"X-Goog-Upload-Protocol"; +static NSString *const kGTMSessionXGoogUploadProtocolResumable = @"resumable"; +static NSString *const kGTMSessionHeaderXGoogUploadSizeReceived = @"X-Goog-Upload-Size-Received"; +static NSString *const kGTMSessionHeaderXGoogUploadStatus = @"X-Goog-Upload-Status"; +static NSString *const kGTMSessionHeaderXGoogUploadURL = @"X-Goog-Upload-URL"; + +// Property of chunk fetchers identifying the parent upload fetcher. Non-retained NSValue. +static NSString *const kGTMSessionUploadFetcherChunkParentKey = @"_uploadFetcherChunkParent"; + +int64_t const kGTMSessionUploadFetcherUnknownFileSize = -1; + +int64_t const kGTMSessionUploadFetcherStandardChunkSize = (int64_t)LLONG_MAX; + +#if TARGET_OS_IPHONE +int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 10 * 1024 * 1024; // 10 MB for iOS, watchOS, tvOS +#else +int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 100 * 1024 * 1024; // 100 MB for macOS +#endif + +typedef NS_ENUM(NSUInteger, GTMSessionUploadFetcherStatus) { + kStatusUnknown, + kStatusActive, + kStatusFinal, + kStatusCancelled, +}; + +NSString *const kGTMSessionFetcherUploadLocationObtainedNotification = + @"kGTMSessionFetcherUploadLocationObtainedNotification"; + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (ProtectedMethods) + +// Access to non-public method on the parent fetcher class. +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks; +- (void)createSessionIdentifierWithMetadata:(NSDictionary *)metadata; +- (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(id)target + didFinishSelector:(SEL)finishedSelector; +- (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue + afterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block; +- (NSTimer *)retryTimer; +- (void)beginFetchForRetry; + +@property(readwrite, strong) NSData *downloadedData; +- (void)releaseCallbacks; + +- (NSInteger)statusCodeUnsynchronized; + +- (BOOL)userStoppedFetching; + +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionUploadFetcher () + +// Changing readonly to readwrite. +@property(atomic, strong, readwrite) NSURLRequest *lastChunkRequest; +@property(atomic, readwrite, assign) int64_t currentOffset; + +// Internal properties. +@property(strong, atomic, GTM_NULLABLE) GTMSessionFetcher *fetcherInFlight; // Synchronized on self. + +@property(assign, atomic, getter=isSubdataGenerating) BOOL subdataGenerating; +@property(assign, atomic) BOOL shouldInitiateOffsetQuery; +@property(assign, atomic) int64_t uploadGranularity; + +@end + +@implementation GTMSessionUploadFetcher { + GTMSessionFetcher *_chunkFetcher; + + // We'll call through to the delegate's completion handler. + GTMSessionFetcherCompletionHandler _delegateCompletionHandler; + dispatch_queue_t _delegateCallbackQueue; + + // The initial fetch's body length and bytes actually sent are + // needed for calculating progress during subsequent chunk uploads + int64_t _initialBodyLength; + int64_t _initialBodySent; + + // The upload server address for the chunks of this upload session. + NSURL *_uploadLocationURL; + + // _uploadData, _uploadDataProvider, or _uploadFileHandle may be set, but only one. + NSData *_uploadData; + NSFileHandle *_uploadFileHandle; + GTMSessionUploadFetcherDataProvider _uploadDataProvider; + NSURL *_uploadFileURL; + int64_t _uploadFileLength; + NSString *_uploadMIMEType; + int64_t _chunkSize; + int64_t _uploadGranularity; + BOOL _isPaused; + BOOL _isRestartedUpload; + BOOL _shouldInitiateOffsetQuery; + + // Tied to useBackgroundSession property, since this property is applicable to chunk fetchers. + BOOL _useBackgroundSessionOnChunkFetchers; + + // We keep the latest offset into the upload data just for progress reporting. + int64_t _currentOffset; + + NSDictionary *_recentChunkReponseHeaders; + NSInteger _recentChunkStatusCode; + + // For waiting, we need to know the fetcher in flight, if any, and if subdata generation + // is in progress. + GTMSessionFetcher *_fetcherInFlight; + BOOL _isSubdataGenerating; + BOOL _isCancelInFlight; + + GTMSessionUploadFetcherCancellationHandler _cancellationHandler; +} + ++ (void)load { + [self uploadFetchersForBackgroundSessions]; +} + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTMSessionFetcherService *)fetcherService { + GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:request + fetcherService:fetcherService]; + [fetcher setLocationURL:nil + uploadMIMEType:uploadMIMEType + chunkSize:chunkSize]; + return fetcher; +} + ++ (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTMSessionFetcherService *)fetcherService { + GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:nil + fetcherService:fetcherService]; + [fetcher setLocationURL:uploadLocationURL + uploadMIMEType:uploadMIMEType + chunkSize:chunkSize]; + return fetcher; +} + ++ (instancetype)uploadFetcherForSessionIdentifierMetadata:(NSDictionary *)metadata { + GTMSESSION_ASSERT_DEBUG( + [metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue], + @"Session identifier metadata is not for an upload fetcher: %@", metadata); + + NSNumber *uploadFileLengthNum = metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey]; + GTMSESSION_ASSERT_DEBUG(uploadFileLengthNum != nil, + @"Session metadata missing an UploadFileSize"); + if (uploadFileLengthNum == nil) return nil; + + int64_t uploadFileLength = [uploadFileLengthNum longLongValue]; + GTMSESSION_ASSERT_DEBUG(uploadFileLength >= 0, @"Session metadata UploadFileSize is unknown"); + + NSString *uploadFileURLString = metadata[kGTMSessionIdentifierUploadFileURLMetadataKey]; + GTMSESSION_ASSERT_DEBUG(uploadFileURLString, @"Session metadata missing an UploadFileURL"); + if (uploadFileURLString == nil) return nil; + + NSURL *uploadFileURL = [NSURL URLWithString:uploadFileURLString]; + // There used to be a call here to NSURL checkResourceIsReachableAndReturnError: to check for the + // existence of the file (also tried NSFileManager fileExistsAtPath:). We've determined + // empirically that the check can fail at startup even when the upload file does in fact exist. + // For now, we'll go ahead and restore the background upload fetcher. If the file doesn't exist, + // it will fail later. + + NSString *uploadLocationURLString = metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey]; + NSURL *uploadLocationURL = + uploadLocationURLString ? [NSURL URLWithString:uploadLocationURLString] : nil; + + NSString *uploadMIMEType = + metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey]; + int64_t uploadChunkSize = + [metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] longLongValue]; + if (uploadChunkSize <= 0) { + uploadChunkSize = kGTMSessionUploadFetcherStandardChunkSize; + } + int64_t currentOffset = + [metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] longLongValue]; + GTMSESSION_ASSERT_DEBUG(currentOffset <= uploadFileLength, + @"CurrentOffset (%lld) exceeds UploadFileSize (%lld)", + currentOffset, uploadFileLength); + if (currentOffset > uploadFileLength) return nil; + + GTMSessionUploadFetcher *uploadFetcher = [self uploadFetcherWithLocation:uploadLocationURL + uploadMIMEType:uploadMIMEType + chunkSize:uploadChunkSize + fetcherService:nil]; + // Set the upload file length before setting the upload file URL tries to determine the length. + [uploadFetcher setUploadFileLength:uploadFileLength]; + + uploadFetcher.uploadFileURL = uploadFileURL; + uploadFetcher.sessionUserInfo = metadata; + uploadFetcher.useBackgroundSession = YES; + uploadFetcher.currentOffset = currentOffset; + uploadFetcher.delegateCallbackQueue = uploadFetcher.callbackQueue; + uploadFetcher.allowedInsecureSchemes = @[ @"http" ]; // Allowed on restored upload fetcher. + return uploadFetcher; +} + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + fetcherService:(GTMSessionFetcherService *)fetcherService { + // Internal utility method for instantiating fetchers + GTMSessionUploadFetcher *fetcher; + if ([fetcherService isKindOfClass:[GTMSessionFetcherService class]]) { + fetcher = [fetcherService fetcherWithRequest:request + fetcherClass:self]; + } else { + fetcher = [self fetcherWithRequest:request]; + } + fetcher.useBackgroundSession = YES; + return fetcher; +} + ++ (NSPointerArray *)uploadFetcherPointerArrayForBackgroundSessions { + static NSPointerArray *gUploadFetcherPointerArrayForBackgroundSessions = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gUploadFetcherPointerArrayForBackgroundSessions = [NSPointerArray weakObjectsPointerArray]; + }); + return gUploadFetcherPointerArrayForBackgroundSessions; +} + ++ (instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + NSArray *uploadFetchersForBackgroundSessions = [self uploadFetchersForBackgroundSessions]; + for (GTMSessionUploadFetcher *uploadFetcher in uploadFetchersForBackgroundSessions) { + if ([uploadFetcher.chunkFetcher.sessionIdentifier isEqual:sessionIdentifier]) { + return uploadFetcher; + } + } + return nil; +} + ++ (NSArray *)uploadFetchersForBackgroundSessions { + // Collect the background session upload fetchers that are still in memory. + NSPointerArray *uploadFetcherPointerArray = [self uploadFetcherPointerArrayForBackgroundSessions]; + [uploadFetcherPointerArray compact]; + NSMutableSet *restoredSessionIdentifiers = [[NSMutableSet alloc] init]; + NSMutableArray *uploadFetchers = [[NSMutableArray alloc] init]; + for (GTMSessionUploadFetcher *uploadFetcher in uploadFetcherPointerArray) { + NSString *sessionIdentifier = uploadFetcher.chunkFetcher.sessionIdentifier; + if (sessionIdentifier) { + [restoredSessionIdentifiers addObject:sessionIdentifier]; + [uploadFetchers addObject:uploadFetcher]; + } + } + + // The system may have other ongoing background upload sessions. Restore upload fetchers for those + // too. + NSArray *fetchers = [GTMSessionFetcher fetchersForBackgroundSessions]; + for (GTMSessionFetcher *fetcher in fetchers) { + NSString *sessionIdentifier = fetcher.sessionIdentifier; + if (!sessionIdentifier || [restoredSessionIdentifiers containsObject:sessionIdentifier]) { + continue; + } + NSDictionary *sessionIdentifierMetadata = [fetcher sessionIdentifierMetadata]; + if (sessionIdentifierMetadata == nil) { + continue; + } + if (![sessionIdentifierMetadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue]) { + continue; + } + GTMSessionUploadFetcher *uploadFetcher = + [self uploadFetcherForSessionIdentifierMetadata:sessionIdentifierMetadata]; + if (uploadFetcher == nil) { + // Something went wrong with this upload fetcher, so kill the restored chunk fetcher. + [fetcher stopFetching]; + continue; + } + [uploadFetchers addObject:uploadFetcher]; + uploadFetcher->_chunkFetcher = fetcher; + uploadFetcher->_fetcherInFlight = fetcher; + [uploadFetcher attachSendProgressBlockToChunkFetcher:fetcher]; + fetcher.completionHandler = + [fetcher completionHandlerWithTarget:uploadFetcher + didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; + + GTMSESSION_LOG_DEBUG(@"%@ restoring upload fetcher %@ for chunk fetcher %@", + [self class], uploadFetcher, fetcher); + } + return uploadFetchers; +} + +- (void)setUploadData:(NSData *)data { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadData != data) { + _uploadData = data; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSData *)uploadData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadData; + } +} + +- (void)setUploadFileHandle:(NSFileHandle *)fh { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadFileHandle != fh) { + _uploadFileHandle = fh; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSFileHandle *)uploadFileHandle { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadFileHandle; + } +} + +- (void)setUploadFileURL:(NSURL *)uploadURL { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadFileURL != uploadURL) { + _uploadFileURL = uploadURL; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSURL *)uploadFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadFileURL; + } +} + +- (void)setUploadFileLength:(int64_t)fullLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadFileLength == kGTMSessionUploadFetcherUnknownFileSize && + fullLength != kGTMSessionUploadFetcherUnknownFileSize) { + _uploadFileLength = fullLength; + } + } +} + +- (void)setUploadDataLength:(int64_t)fullLength + provider:(GTMSessionUploadFetcherDataProvider)block { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadDataProvider = [block copy]; + _uploadFileLength = fullLength; + } + [self setupRequestHeaders]; +} + +- (GTMSessionUploadFetcherDataProvider)uploadDataProvider { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadDataProvider; + } +} + + +- (void)setUploadMIMEType:(NSString *)uploadMIMEType { + GTMSESSION_ASSERT_DEBUG(0, @"TODO: disallow setUploadMIMEType by making declaration readonly"); + // (and uploadMIMEType, chunksize, currentOffset) + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadMIMEType = uploadMIMEType; + } +} + +- (NSString *)uploadMIMEType { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadMIMEType; + } +} + +- (void)setChunkSize:(int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _chunkSize = chunkSize; + } +} + +- (int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _chunkSize; + } +} + +- (void)setupRequestHeaders { + GTMSessionCheckNotSynchronized(self); + +#if DEBUG + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + int hasData = (_uploadData != nil) ? 1 : 0; + int hasFileHandle = (_uploadFileHandle != nil) ? 1 : 0; + int hasFileURL = (_uploadFileURL != nil) ? 1 : 0; + int hasUploadDataProvider = (_uploadDataProvider != nil) ? 1 : 0; + int numberOfSources = hasData + hasFileHandle + hasFileURL + hasUploadDataProvider; + #pragma unused(numberOfSources) + GTMSESSION_ASSERT_DEBUG(numberOfSources == 1, + @"Need just one upload source (%d)", numberOfSources); + } // @synchronized(self) +#endif + + // Add our custom headers to the initial request indicating the data + // type and total size to be delivered later in the chunk requests. + NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; + + GTMSESSION_ASSERT_DEBUG((mutableRequest == nil) != (_uploadLocationURL == nil), + @"Request and location are mutually exclusive"); + if (!mutableRequest) return; + + [mutableRequest setValue:kGTMSessionXGoogUploadProtocolResumable + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol]; + [mutableRequest setValue:@"start" + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + [mutableRequest setValue:_uploadMIMEType + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentType]; + [mutableRequest setValue:@([self fullUploadLength]).stringValue + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength]; + + NSString *method = mutableRequest.HTTPMethod; + if (method == nil || [method caseInsensitiveCompare:@"GET"] == NSOrderedSame) { + [mutableRequest setHTTPMethod:@"POST"]; + } + + // Ensure the user agent header identifies this to the upload server as a + // GTMSessionUploadFetcher client. The /1 can be incremented in the unlikely circumstance + // we need to make a bug fix in the client that the server can recognize. + NSString *const kUserAgentStub = @"(GTMSUF/1)"; + NSString *userAgent = [mutableRequest valueForHTTPHeaderField:@"User-Agent"]; + if (userAgent == nil + || [userAgent rangeOfString:kUserAgentStub].location == NSNotFound) { + if (userAgent.length == 0) { + userAgent = GTMFetcherStandardUserAgentString(nil); + } + userAgent = [userAgent stringByAppendingFormat:@" %@", kUserAgentStub]; + [mutableRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + [self setRequest:mutableRequest]; +} + +- (void)setLocationURL:(NSURL * GTM_NULLABLE_TYPE)location + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(chunkSize > 0, @"chunk size is zero"); + + // When resuming an upload, set the known upload target URL. + _uploadLocationURL = location; + + _uploadMIMEType = uploadMIMEType; + _chunkSize = chunkSize; + + // Indicate that we've not yet determined the file handle's length + _uploadFileLength = kGTMSessionUploadFetcherUnknownFileSize; + + // Indicate that we've not yet determined the upload fetcher status + _recentChunkStatusCode = -1; + + // If this is restarting an upload begun by another fetcher, + // the location is specified but the request is nil + _isRestartedUpload = (location != nil); + } // @synchronized(self) +} + +- (int64_t)fullUploadLength { + int64_t result; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadData) { + result = (int64_t)_uploadData.length; + } else { + if (_uploadFileLength == kGTMSessionUploadFetcherUnknownFileSize) { + if (_uploadFileHandle) { + // First time through, seek to end to determine file length + _uploadFileLength = (int64_t)[_uploadFileHandle seekToEndOfFile]; + } else if (_uploadDataProvider) { + // _uploadFileLength is set when the _uploadDataProvider is set. + GTMSESSION_ASSERT_DEBUG(_uploadFileLength >= 0, @"No uploadDataProvider length set"); + } else { + NSNumber *filesizeNum; + NSError *valueError; + if ([_uploadFileURL getResourceValue:&filesizeNum + forKey:NSURLFileSizeKey + error:&valueError]) { + _uploadFileLength = filesizeNum.longLongValue; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Cannot get file size: %@\n %@", + valueError, _uploadFileURL.path); + _uploadFileLength = 0; + } + } + } + result = _uploadFileLength; + } + } // @synchronized(self) + return result; +} + +// Make a subdata of the upload data. +- (void)generateChunkSubdataWithOffset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + GTMSessionUploadFetcherDataProvider uploadDataProvider = self.uploadDataProvider; + if (uploadDataProvider) { + uploadDataProvider(offset, length, response); + return; + } + + NSData *uploadData = self.uploadData; + if (uploadData) { + // NSData provided. + NSData *resultData; + if (offset == 0 && length == (int64_t)uploadData.length) { + resultData = uploadData; + } else { + int64_t dataLength = (int64_t)uploadData.length; + // Ensure our range is valid. b/18007814 + if (offset + length > dataLength) { + NSString *errorMessage = [NSString stringWithFormat: + @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld", + offset, length, dataLength]; + GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage); + response(nil, + kGTMSessionUploadFetcherUnknownFileSize, + [self uploadChunkUnavailableErrorWithDescription:errorMessage]); + return; + } + NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); + + @try { + resultData = [uploadData subdataWithRange:range]; + } + @catch (NSException *exception) { + NSString *errorMessage = exception.description; + GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage); + response(nil, + kGTMSessionUploadFetcherUnknownFileSize, + [self uploadChunkUnavailableErrorWithDescription:errorMessage]); + return; + } + } + response(resultData, kGTMSessionUploadFetcherUnknownFileSize, nil); + return; + } + NSURL *uploadFileURL = self.uploadFileURL; + if (uploadFileURL) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self generateChunkSubdataFromFileURL:uploadFileURL + offset:offset + length:length + response:response]; + }); + return; + } + GTMSESSION_ASSERT_DEBUG(_uploadFileHandle, @"Unexpectedly missing upload data package"); + NSFileHandle *uploadFileHandle = self.uploadFileHandle; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self generateChunkSubdataFromFileHandle:uploadFileHandle + offset:offset + length:length + response:response]; + }); +} + +- (void)generateChunkSubdataFromFileHandle:(NSFileHandle *)fileHandle + offset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + NSData *resultData; + NSError *error; + @try { + [fileHandle seekToFileOffset:(unsigned long long)offset]; + resultData = [fileHandle readDataOfLength:(NSUInteger)length]; + } + @catch (NSException *exception) { + GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileHandle failed to read, %@", exception); + error = [self uploadChunkUnavailableErrorWithDescription:exception.description]; + } + // The response always re-dispatches to the main thread, so we skip doing that here. + response(resultData, kGTMSessionUploadFetcherUnknownFileSize, error); +} + +- (void)generateChunkSubdataFromFileURL:(NSURL *)fileURL + offset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + GTMSessionCheckNotSynchronized(self); + + NSData *resultData; + NSError *error; + int64_t fullUploadLength = [self fullUploadLength]; + NSData *mappedData = + [NSData dataWithContentsOfURL:fileURL + options:NSDataReadingMappedAlways + NSDataReadingUncached + error:&error]; + if (!mappedData) { + // We could not create an NSData by memory-mapping the file. +#if TARGET_IPHONE_SIMULATOR + // NSTemporaryDirectory() can differ in the simulator between app restarts, + // yet the contents for the new path remains unchanged, so try the latest temp path. + if ([error.domain isEqual:NSCocoaErrorDomain] && (error.code == NSFileReadNoSuchFileError)) { + NSString *filename = [fileURL lastPathComponent]; + NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename]; + NSURL *newFileURL = [NSURL fileURLWithPath:filePath]; + if (![newFileURL isEqual:fileURL]) { + [self generateChunkSubdataFromFileURL:newFileURL + offset:offset + length:length + response:response]; + return; + } + } +#endif + + // If the file is just too large to create an NSData for, or if for some other reason we can't + // map it, create an NSFileHandle instead to read a subset into an NSData. +#if DEBUG + NSNumber *fileSizeNum; + BOOL hasFileSize = [fileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:NULL]; + GTMSESSION_LOG_DEBUG(@"Note: uploadFileURL is falling back to creating upload chunks by reading" + @" an NSFileHandle since uploadFileURL failed to map the upload file," + @" file size %@, %@", + hasFileSize ? fileSizeNum : @"unknown", error); +#endif + + NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:fileURL + error:&error]; + if (fileHandle != nil) { + [self generateChunkSubdataFromFileHandle:fileHandle + offset:offset + length:length + response:response]; + return; + } + GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileURL failed to read, %@", error); + // Fall through with the error. + } else { + // Successfully created an NSData by memory-mapping the file. + if ((NSUInteger)(offset + length) > mappedData.length) { + NSString *errorMessage = [NSString stringWithFormat: + @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld\texpected UploadLength: %lld", + offset, length, (long long)mappedData.length, fullUploadLength]; + GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage); + response(nil, + kGTMSessionUploadFetcherUnknownFileSize, + [self uploadChunkUnavailableErrorWithDescription:errorMessage]); + return; + } + if (offset > 0 || length < fullUploadLength) { + NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); + resultData = [mappedData subdataWithRange:range]; + } else { + resultData = mappedData; + } + } + // The response always re-dispatches to the main thread, so we skip re-dispatching here. + response(resultData, kGTMSessionUploadFetcherUnknownFileSize, error); +} + +- (NSError *)uploadChunkUnavailableErrorWithDescription:(NSString *)description { + // The description in the userInfo is intended as a clue to programmers, not + // for client code to examine or rely on. + NSDictionary *userInfo = @{ @"description" : description }; + return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorUploadChunkUnavailable + userInfo:userInfo]; +} + +- (NSError *)prematureFailureErrorWithUserInfo:(NSDictionary *)userInfo { + // An error for if we get an unexpected status from the upload server or + // otherwise cannot continue. This is an issue beyond the upload protocol; + // there's no way the client can do anything useful except give up. + NSError *error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:501 // Not implemented + userInfo:userInfo]; + return error; +} + ++ (GTMSessionUploadFetcherStatus)uploadStatusFromResponseHeaders:(NSDictionary *)responseHeaders { + NSString *statusString = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus]; + if ([statusString isEqual:@"active"]) { + return kStatusActive; + } + if ([statusString isEqual:@"final"]) { + return kStatusFinal; + } + if ([statusString isEqual:@"cancelled"]) { + return kStatusCancelled; + } + return kStatusUnknown; +} + +#pragma mark Method overrides affecting the initial fetch only + +- (void)setCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCompletionHandler = handler; + } +} + +- (void)setDelegateCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCallbackQueue = queue; + } +} + +- (dispatch_queue_t GTM_NULLABLE_TYPE)delegateCallbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateCallbackQueue; + } +} + +- (BOOL)isRestartedUpload { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isRestartedUpload; + } +} + +- (GTMSessionFetcher * GTM_NULLABLE_TYPE)chunkFetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _chunkFetcher; + } +} + +- (void)setChunkFetcher:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _chunkFetcher = fetcher; + } +} + +- (void)setFetcherInFlight:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _fetcherInFlight = fetcher; + } +} + +- (GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcherInFlight { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _fetcherInFlight; + } +} + +- (void)setCancellationHandler:(GTMSessionUploadFetcherCancellationHandler GTM_NULLABLE_TYPE) + cancellationHandler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _cancellationHandler = cancellationHandler; + } +} + +- (GTMSessionUploadFetcherCancellationHandler GTM_NULLABLE_TYPE)cancellationHandler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _cancellationHandler; + } +} + +- (void)beginFetchForRetry { + GTMSessionCheckNotSynchronized(self); + + // Override the superclass to reset the initial body length and fetcher-in-flight, + // then call the superclass implementation. + [self setInitialBodyLength:[self bodyLength]]; + + GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@", + self.fetcherInFlight); + self.fetcherInFlight = self; + [super beginFetchForRetry]; +} + +- (void)beginFetchWithCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { + GTMSessionCheckNotSynchronized(self); + + [self setInitialBodyLength:[self bodyLength]]; + + // We'll hold onto the superclass's callback queue so we can invoke the handler + // even after the superclass has released the queue and its callback handler, as + // happens during auth failure. + [self setDelegateCallbackQueue:self.callbackQueue]; + self.completionHandler = handler; + + if ([self isRestartedUpload]) { + // When restarting an upload, we know the destination location for chunk fetches, + // but we need to query to find the initial offset. + if (![self isPaused]) { + [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; + } + return; + } + // We don't want to call into the client's completion block immediately + // after the finish of the initial connection (the delegate is called only + // when uploading finishes), so we substitute our own completion block to be + // called when the initial connection finishes + GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@", + self.fetcherInFlight); + + self.fetcherInFlight = self; + [super beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + self.fetcherInFlight = nil; + // callback + + BOOL hasTestBlock = (self.testBlock != nil); + if (![self isRestartedUpload] && !hasTestBlock) { + if (error == nil) { + [self beginChunkFetches]; + } else { + if ([self retryTimer] == nil) { + [self invokeFinalCallbackWithData:nil + error:error + shouldInvalidateLocation:YES]; + } + } + } else { + // If there was no initial request, then this fetch is resuming some + // other uploadFetcher's initial request, and the superclass's connection + // is never used, so at this point we call the user's actual completion + // block. + if (!hasTestBlock) { + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + } else { + // There was a test block, so we won't do chunk fetches, but we simulate obtaining + // the data to be uploaded from the upload data provider block or the file handle, + // and then call back. + [self generateChunkSubdataWithOffset:0 + length:[self fullUploadLength] + response:^(NSData *generateData, int64_t fullUploadLength, NSError *generateError) { + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + }]; + } + } + }]; +} + +- (void)beginChunkFetches { + GTMSessionCheckNotSynchronized(self); + +#if DEBUG + // The initial response of the resumable upload protocol should have an + // empty body + // + // This assert typically happens because the upload create/edit link URL was + // not supplied with the request, and the server is thus expecting a non- + // resumable request/response. + if (self.downloadedData.length > 0) { + NSData *downloadedData = self.downloadedData; + NSString *str = [[NSString alloc] initWithData:downloadedData + encoding:NSUTF8StringEncoding]; + #pragma unused(str) + GTMSESSION_ASSERT_DEBUG(NO, @"unexpected response data (uploading to the wrong URL?)\n%@", str); + } +#endif + + // We need to get the upload URL from the location header to continue. + NSDictionary *responseHeaders = [self responseHeaders]; + + [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; + + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown, + @"beginChunkFetches has unexpected upload status for headers %@", responseHeaders); + + BOOL isPrematureStop = (uploadStatus == kStatusFinal) || (uploadStatus == kStatusCancelled); + + NSString *uploadLocationURLStr = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadURL]; + BOOL hasUploadLocation = (uploadLocationURLStr.length > 0); + + if (isPrematureStop || !hasUploadLocation) { + GTMSESSION_ASSERT_DEBUG(NO, @"Premature failure: upload-status:\"%@\" location:%@", + [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], uploadLocationURLStr); + // We cannot continue since we do not know the location to use + // as our upload destination. + NSDictionary *userInfo = nil; + NSData *downloadedData = self.downloadedData; + if (downloadedData.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : downloadedData }; + } + NSError *failureError = [self prematureFailureErrorWithUserInfo:userInfo]; + [self invokeFinalCallbackWithData:nil + error:failureError + shouldInvalidateLocation:YES]; + return; + } + + self.uploadLocationURL = [NSURL URLWithString:uploadLocationURLStr]; + + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc postNotificationName:kGTMSessionFetcherUploadLocationObtainedNotification + object:self]; + + // we've now sent all of the initial post body data, so we need to include + // its size in future progress indicator callbacks + [self setInitialBodySent:[self initialBodyLength]]; + + // just in case the user paused us during the initial fetch... + if (![self isPaused]) { + [self uploadNextChunkWithOffset:0]; + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent + totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + // Overrides the superclass. + [self invokeDelegateWithDidSendBytes:bytesSent + totalBytesSent:totalBytesSent + totalBytesExpectedToSend:totalBytesExpectedToSend + [self fullUploadLength]]; +} + +- (BOOL)shouldReleaseCallbacksUponCompletion { + // Overrides the superclass. + + // We don't want the superclass to release the delegate and callback + // blocks once the initial fetch has finished + // + // This is invoked for only successful completion of the connection; + // an error always will invoke and release the callbacks + return NO; +} + +- (void)invokeFinalCallbackWithData:(NSData *)data + error:(NSError *)error + shouldInvalidateLocation:(BOOL)shouldInvalidateLocation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (shouldInvalidateLocation) { + _uploadLocationURL = nil; + } + + dispatch_queue_t queue = _delegateCallbackQueue; + GTMSessionFetcherCompletionHandler handler = _delegateCompletionHandler; + if (queue && handler) { + [self invokeOnCallbackQueue:queue + afterUserStopped:NO + block:^{ + handler(data, error); + }]; + } + } // @synchronized(self) + + [self releaseUploadAndBaseCallbacks:!self.userStoppedFetching]; +} + +- (void)releaseUploadAndBaseCallbacks:(BOOL)shouldReleaseCancellation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCallbackQueue = nil; + _delegateCompletionHandler = nil; + _uploadDataProvider = nil; + if (shouldReleaseCancellation) { + _cancellationHandler = nil; + } + } + + // Release the base class's callbacks, too, if needed. + [self releaseCallbacks]; +} + +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { + GTMSessionCheckNotSynchronized(self); + + // Clear _fetcherInFlight when stopped. Moved from stopFetching, since that's a public method, + // where this method does the work. Fixes issue clearing value when retryBlock included. + GTMSessionFetcher *fetcherInFlight = self.fetcherInFlight; + if (fetcherInFlight == self) { + self.fetcherInFlight = nil; + } + + [super stopFetchReleasingCallbacks:shouldReleaseCallbacks]; + + if (shouldReleaseCallbacks) { + [self releaseUploadAndBaseCallbacks:NO]; + } +} + +#pragma mark Chunk fetching methods + +- (void)uploadNextChunkWithOffset:(int64_t)offset { + // use the properties in each chunk fetcher + NSDictionary *props = [self properties]; + + [self uploadNextChunkWithOffset:offset + fetcherProperties:props]; +} + +- (void)sendQueryForUploadOffsetWithFetcherProperties:(NSDictionary *)props { + GTMSessionFetcher *queryFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:YES]; + queryFetcher.bodyData = [NSData data]; + + NSString *originalComment = self.comment; + [queryFetcher setCommentWithFormat:@"%@ (query offset)", + originalComment ? originalComment : @"upload"]; + + [queryFetcher setRequestValue:@"query" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + + self.fetcherInFlight = queryFetcher; + [queryFetcher beginFetchWithDelegate:self + didFinishSelector:@selector(queryFetcher:finishedWithData:error:)]; +} + +- (void)queryFetcher:(GTMSessionFetcher *)queryFetcher + finishedWithData:(NSData *)data + error:(NSError *)error { + self.fetcherInFlight = nil; + + NSDictionary *responseHeaders = [queryFetcher responseHeaders]; + NSString *sizeReceivedHeader; + + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown || error != nil, + @"query fetcher completion has unexpected upload status for headers %@", responseHeaders); + + if (error == nil) { + sizeReceivedHeader = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadSizeReceived]; + + if (uploadStatus == kStatusCancelled || + (uploadStatus == kStatusActive && sizeReceivedHeader == nil)) { + NSDictionary *userInfo = nil; + if (data.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; + } + error = [self prematureFailureErrorWithUserInfo:userInfo]; + } + } + + if (error == nil) { + int64_t offset = [sizeReceivedHeader longLongValue]; + int64_t fullUploadLength = [self fullUploadLength]; + if (uploadStatus == kStatusFinal || + (offset >= fullUploadLength && + fullUploadLength != kGTMSessionUploadFetcherUnknownFileSize)) { + // Handle we're done + [self chunkFetcher:queryFetcher finishedWithData:data error:nil]; + } else { + [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; + [self uploadNextChunkWithOffset:offset]; + } + } else { + // Handle query error + [self chunkFetcher:queryFetcher finishedWithData:data error:error]; + } +} + +- (void)sendCancelUploadWithFetcherProperties:(NSDictionary *)props { + @synchronized(self) { + _isCancelInFlight = YES; + } + GTMSessionFetcher *cancelFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:YES]; + cancelFetcher.bodyData = [NSData data]; + + NSString *originalComment = self.comment; + [cancelFetcher setCommentWithFormat:@"%@ (cancel)", + originalComment ? originalComment : @"upload"]; + + [cancelFetcher setRequestValue:@"cancel" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + + self.fetcherInFlight = cancelFetcher; + [cancelFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + self.fetcherInFlight = nil; + if (![self triggerCancellationHandlerForFetch:cancelFetcher data:data error:error]) { + if (error) { + GTMSESSION_LOG_DEBUG(@"cancelFetcher %@", error); + } + } + @synchronized(self) { + self->_isCancelInFlight = NO; + } + }]; +} + +- (void)uploadNextChunkWithOffset:(int64_t)offset + fetcherProperties:(NSDictionary *)props { + GTMSessionCheckNotSynchronized(self); + + // Example chunk headers: + // X-Goog-Upload-Command: upload, finalize + // X-Goog-Upload-Offset: 0 + // Content-Length: 2000000 + // Content-Type: image/jpeg + // + // {bytes 0-1999999} + + // The chunk upload URL requires no authentication header. + GTMSessionFetcher *chunkFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:NO]; + [self attachSendProgressBlockToChunkFetcher:chunkFetcher]; + int64_t chunkSize = [self updateChunkFetcher:chunkFetcher + forChunkAtOffset:offset]; + BOOL isUploadingFileURL = (self.uploadFileURL != nil); + int64_t fullUploadLength = [self fullUploadLength]; + + // The chunk size may have changed, so determine again if we're uploading the full file. + BOOL isUploadingFullFile = (offset == 0 && + fullUploadLength != kGTMSessionUploadFetcherUnknownFileSize && + chunkSize >= fullUploadLength); + if (isUploadingFullFile && isUploadingFileURL) { + // The data is the full upload file URL. + chunkFetcher.bodyFileURL = self.uploadFileURL; + [self beginChunkFetcher:chunkFetcher + offset:offset]; + } else { + // Make an NSData for the subset for this upload chunk. + self.subdataGenerating = YES; + [self generateChunkSubdataWithOffset:offset + length:chunkSize + response:^(NSData *chunkData, int64_t uploadFileLength, NSError *chunkError) { + // The subdata methods may leave us on a background thread. + dispatch_async(dispatch_get_main_queue(), ^{ + self.subdataGenerating = NO; + + // dont allow the updating of fileLength for uploads not using a data provider as they + // should know the file length before the upload starts. + if (self->_uploadDataProvider != nil && uploadFileLength > 0) { + [self setUploadFileLength:uploadFileLength]; + // Update the command and content-length headers if this is the last chunk to be sent. + if (offset + chunkSize >= uploadFileLength) { + int64_t updatedChunkSize = [self updateChunkFetcher:chunkFetcher + forChunkAtOffset:offset]; + if (updatedChunkSize == 0) { + // Calling beginChunkFetcher early when there is no more data to send allows us to + // properly handle nil chunkData below without having to account for the case where + // we are just finalizing the file. + chunkFetcher.bodyData = [[NSData alloc] init]; + [self beginChunkFetcher:chunkFetcher + offset:offset]; + return; + } + } + } + + if (chunkData == nil) { + NSError *responseError = chunkError; + if (!responseError) { + responseError = [self uploadChunkUnavailableErrorWithDescription:@"chunkData is nil"]; + } + [self invokeFinalCallbackWithData:nil + error:responseError + shouldInvalidateLocation:YES]; + return; + } + + BOOL didWriteFile = NO; + if (isUploadingFileURL) { + // Make a temporary file with the data subset. + NSString *tempName = + [NSString stringWithFormat:@"GTMUpload_temp_%@", [[NSUUID UUID] UUIDString]]; + NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName]; + NSError *writeError; + didWriteFile = [chunkData writeToFile:tempPath + options:NSDataWritingAtomic + error:&writeError]; + if (didWriteFile) { + chunkFetcher.bodyFileURL = [NSURL fileURLWithPath:tempPath]; + } else { + GTMSESSION_LOG_DEBUG(@"writeToFile failed: %@\n%@", writeError, tempPath); + } + } + if (!didWriteFile) { + chunkFetcher.bodyData = [chunkData copy]; + } + [self beginChunkFetcher:chunkFetcher + offset:offset]; + }); + }]; + } +} + +- (void)beginChunkFetcher:(GTMSessionFetcher *)chunkFetcher + offset:(int64_t)offset { + + // Track the current offset for progress reporting + self.currentOffset = offset; + + // Hang on to the fetcher in case we need to cancel it. We set these before beginning the + // chunk fetch so the observers notified of chunk fetches can inspect the upload fetcher to + // match to the chunk. + self.chunkFetcher = chunkFetcher; + self.fetcherInFlight = chunkFetcher; + + // Update the last chunk request, including any request headers. + self.lastChunkRequest = chunkFetcher.request; + + [chunkFetcher beginFetchWithDelegate:self + didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; +} + +- (void)attachSendProgressBlockToChunkFetcher:(GTMSessionFetcher *)chunkFetcher { + chunkFetcher.sendProgressBlock = ^(int64_t bytesSent, int64_t totalBytesSent, + int64_t totalBytesExpectedToSend) { + // The total bytes expected include the initial body and the full chunked + // data, independent of how big this fetcher's chunk is. + int64_t initialBodySent = [self bodyLength]; // TODO(grobbins) use [self initialBodySent] + int64_t totalSent = initialBodySent + self.currentOffset + totalBytesSent; + int64_t totalExpected = initialBodySent + [self fullUploadLength]; + + [self invokeDelegateWithDidSendBytes:bytesSent + totalBytesSent:totalSent + totalBytesExpectedToSend:totalExpected]; + }; +} + +- (NSDictionary *)uploadSessionIdentifierMetadata { + NSMutableDictionary *metadata = [NSMutableDictionary dictionary]; + metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] = @YES; + GTMSESSION_ASSERT_DEBUG(self.uploadFileURL, + @"Invalid upload fetcher to create session identifier for metadata"); + metadata[kGTMSessionIdentifierUploadFileURLMetadataKey] = [self.uploadFileURL absoluteString]; + metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey] = @([self fullUploadLength]); + + if (self.uploadLocationURL) { + metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey] = + [self.uploadLocationURL absoluteString]; + } + if (self.uploadMIMEType) { + metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey] = self.uploadMIMEType; + } + metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] = @(self.chunkSize); + metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] = @(self.currentOffset); + return metadata; +} + +- (GTMSessionFetcher *)uploadFetcherWithProperties:(NSDictionary *)properties + isQueryFetch:(BOOL)isQueryFetch { + GTMSessionCheckNotSynchronized(self); + + // Common code to make a request for a query command or for a chunk upload. + NSURL *uploadLocationURL = self.uploadLocationURL; + NSMutableURLRequest *chunkRequest = [NSMutableURLRequest requestWithURL:uploadLocationURL]; + [chunkRequest setHTTPMethod:@"PUT"]; + + // copy the user-agent from the original connection + // n.b. that self.request is nil for upload fetchers created with an existing upload location + // URL. + NSURLRequest *origRequest = self.request; + NSString *userAgent = [origRequest valueForHTTPHeaderField:@"User-Agent"]; + if (userAgent.length > 0) { + [chunkRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + [chunkRequest setValue:kGTMSessionXGoogUploadProtocolResumable + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol]; + + // To avoid timeouts when debugging, copy the timeout of the initial fetcher. + NSTimeInterval origTimeout = [origRequest timeoutInterval]; + [chunkRequest setTimeoutInterval:origTimeout]; + + // + // Make a new chunk fetcher. + // + GTMSessionFetcher *chunkFetcher = [GTMSessionFetcher fetcherWithRequest:chunkRequest]; + chunkFetcher.callbackQueue = self.callbackQueue; + chunkFetcher.sessionUserInfo = self.sessionUserInfo; + chunkFetcher.configurationBlock = self.configurationBlock; + chunkFetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; + chunkFetcher.allowLocalhostRequest = self.allowLocalhostRequest; + chunkFetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; + chunkFetcher.useUploadTask = !isQueryFetch; + + if (self.uploadFileURL && !isQueryFetch && self.useBackgroundSession) { + [chunkFetcher createSessionIdentifierWithMetadata:[self uploadSessionIdentifierMetadata]]; + } + + // Give the chunk fetcher the same properties as the previous chunk fetcher + chunkFetcher.properties = [properties mutableCopy]; + [chunkFetcher setProperty:[NSValue valueWithNonretainedObject:self] + forKey:kGTMSessionUploadFetcherChunkParentKey]; + + // copy other fetcher settings to the new fetcher + chunkFetcher.retryEnabled = self.retryEnabled; + chunkFetcher.maxRetryInterval = self.maxRetryInterval; + + if ([self isRetryEnabled]) { + // We interpose our own retry method both so we can change the request to ask the server to + // tell us where to resume the chunk. + chunkFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *chunkError, + GTMSessionFetcherRetryResponse response) { + void (^finish)(BOOL) = ^(BOOL shouldRetry){ + // We'll retry by sending an offset query. + if (shouldRetry) { + self.shouldInitiateOffsetQuery = !isQueryFetch; + + // We don't know what our actual offset is anymore, but the server will tell us. + self.currentOffset = 0; + } + // We don't actually want to retry this specific fetcher. + response(NO); + }; + + GTMSessionFetcherRetryBlock retryBlock = self.retryBlock; + if (retryBlock) { + // Ask the client, then call the finish block above. + retryBlock(suggestedWillRetry, chunkError, finish); + } else { + finish(suggestedWillRetry); + } + }; + } + + return chunkFetcher; +} + +- (void)chunkFetcher:(GTMSessionFetcher *)chunkFetcher + finishedWithData:(NSData *)data + error:(NSError *)error { + BOOL hasDestroyedOldChunkFetcher = NO; + self.fetcherInFlight = nil; + + NSDictionary *responseHeaders = [chunkFetcher responseHeaders]; + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown + || error != nil + || self.wasCreatedFromBackgroundSession, + @"chunk fetcher completion has kStatusUnknown upload status for headers %@ fetcher %@", + responseHeaders, self); + BOOL isUploadStatusStopped = (uploadStatus == kStatusFinal || uploadStatus == kStatusCancelled); + + // Check if the fetcher was actually querying. If it failed, do not retry, + // as it would enter an infinite retry loop. + NSString *uploadCommand = + chunkFetcher.request.allHTTPHeaderFields[kGTMSessionHeaderXGoogUploadCommand]; + BOOL isQueryFetch = [uploadCommand isEqual:@"query"]; + + // TODO + // Maybe here we can check to see if the request had x goog content length set. (the file length one). + int64_t previousContentLength = + [[chunkFetcher.request valueForHTTPHeaderField:@"Content-Length"] longLongValue]; + // The Content-Length header may not be present if the chunk fetcher was recreated from + // a background session. + BOOL hasKnownChunkSize = (previousContentLength > 0); + BOOL needsQuery = (!hasKnownChunkSize && !isUploadStatusStopped); + + if (error || (needsQuery && !isQueryFetch)) { + NSInteger status = error.code; + + // Status 4xx indicates a bad offset in the Google upload protocol. However, do not retry status + // 404 per spec, nor if the upload size appears to have been zero (since the server will just + // keep asking us to retry.) + if (self.shouldInitiateOffsetQuery || + (needsQuery && !isQueryFetch) || + ([error.domain isEqual:kGTMSessionFetcherStatusDomain] && + status >= 400 && status <= 499 && + status != 404 && + uploadStatus == kStatusActive && + previousContentLength > 0)) { + self.shouldInitiateOffsetQuery = NO; + [self destroyChunkFetcher]; + hasDestroyedOldChunkFetcher = YES; + [self sendQueryForUploadOffsetWithFetcherProperties:chunkFetcher.properties]; + } else { + // Some unexpected status has occurred; handle it as we would a regular + // object fetcher failure. + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:NO]; + } + } else { + // The chunk has uploaded successfully. + int64_t newOffset = self.currentOffset + previousContentLength; +#if DEBUG + // Verify that if we think all of the uploading data has been sent, the server responded with + // the "final" upload status. + BOOL hasUploadAllData = (newOffset == [self fullUploadLength]); + BOOL isFinalStatus = (uploadStatus == kStatusFinal); + #pragma unused(hasUploadAllData,isFinalStatus) + GTMSESSION_ASSERT_DEBUG(hasUploadAllData == isFinalStatus || !hasKnownChunkSize, + @"uploadStatus:%@ newOffset:%lld (%lld + %lld) fullUploadLength:%lld" + @" chunkFetcher:%@ requestHeaders:%@ responseHeaders:%@", + [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], + newOffset, self.currentOffset, previousContentLength, + [self fullUploadLength], + chunkFetcher, chunkFetcher.request.allHTTPHeaderFields, + responseHeaders); +#endif + if (isUploadStatusStopped || (_currentOffset > _uploadFileLength && _uploadFileLength > 0)) { + // This was the last chunk. + if (error == nil && uploadStatus == kStatusCancelled) { + // Report cancelled status as an error. + NSDictionary *userInfo = nil; + if (data.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; + } + data = nil; + error = [self prematureFailureErrorWithUserInfo:userInfo]; + } else { + // The upload is in final status. + // + // Take the chunk fetcher's data as the superclass data. + self.downloadedData = data; + self.statusCode = chunkFetcher.statusCode; + } + + // we're done + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + } else { + // Start the next chunk. + self.currentOffset = newOffset; + + // We want to destroy this chunk fetcher before creating the next one, but + // we want to pass on its properties + NSDictionary *props = [chunkFetcher properties]; + + // We no longer need to be able to cancel this chunkFetcher. Destroy it + // before we create a new chunk fetcher. + [self destroyChunkFetcher]; + hasDestroyedOldChunkFetcher = YES; + + [self uploadNextChunkWithOffset:newOffset + fetcherProperties:props]; + } + } + if (!hasDestroyedOldChunkFetcher) { + [self destroyChunkFetcher]; + } +} + +- (void)destroyChunkFetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_fetcherInFlight == _chunkFetcher) { + _fetcherInFlight = nil; + } + + [_chunkFetcher stopFetching]; + + NSURL *chunkFileURL = _chunkFetcher.bodyFileURL; + BOOL wasTemporaryUploadFile = ![chunkFileURL isEqual:_uploadFileURL]; + if (wasTemporaryUploadFile) { + NSError *error; + [[NSFileManager defaultManager] removeItemAtURL:chunkFileURL + error:&error]; + if (error) { + GTMSESSION_LOG_DEBUG(@"removingItemAtURL failed: %@\n%@", error, chunkFileURL); + } + } + + _recentChunkReponseHeaders = _chunkFetcher.responseHeaders; + + // To avoid retain cycles, remove all properties except the parent identifier. + _chunkFetcher.properties = + @{ kGTMSessionUploadFetcherChunkParentKey : [NSValue valueWithNonretainedObject:self] }; + + _chunkFetcher.retryBlock = nil; + _chunkFetcher.sendProgressBlock = nil; + _chunkFetcher = nil; + } // @synchronized(self) +} + +// This method calculates the proper values to pass to the client's send progress block. +// +// The actual total bytes sent include the initial body sent, plus the +// offset into the batched data prior to the current chunk fetcher + +- (void)invokeDelegateWithDidSendBytes:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent + totalBytesExpectedToSend:(int64_t)totalBytesExpected { + GTMSessionCheckNotSynchronized(self); + + // Ensure the chunk fetcher survives the callback in case the user pauses the upload process. + __block GTMSessionFetcher *holdFetcher = self.chunkFetcher; + + [self invokeOnCallbackQueue:self.delegateCallbackQueue + afterUserStopped:NO + block:^{ + GTMSessionFetcherSendProgressBlock sendProgressBlock = self.sendProgressBlock; + if (sendProgressBlock) { + sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpected); + } + holdFetcher = nil; + }]; +} + +- (void)retrieveUploadChunkGranularityFromResponseHeaders:(NSDictionary *)responseHeaders { + GTMSessionCheckNotSynchronized(self); + + // Standard granularity for Google uploads is 256K. + NSString *chunkGranularityHeader = + [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadChunkGranularity]; + self.uploadGranularity = chunkGranularityHeader.longLongValue; +} + +#pragma mark - + +- (BOOL)isPaused { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isPaused; + } // @synchronized(self) +} + +- (void)pauseFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _isPaused = YES; + } // @synchronized(self) + + // Pausing just means stopping the current chunk from uploading; + // when we resume, we will send a query request to the server to + // figure out what bytes to resume sending. + // + // We won't try to cancel the initial data upload, but rather will check + // for being paused in beginChunkFetches. + [self destroyChunkFetcher]; +} + +- (void)resumeFetching { + BOOL wasPaused; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + wasPaused = _isPaused; + _isPaused = NO; + } // @synchronized(self) + + if (wasPaused) { + [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; + } +} + +- (void)stopFetching { + // Overrides the superclass + [self destroyChunkFetcher]; + + // If we think the server is waiting for more data, then tell it there won't be more. + if (self.uploadLocationURL) { + [self sendCancelUploadWithFetcherProperties:[self properties]]; + self.uploadLocationURL = nil; + } else { + [self invokeOnCallbackQueue:self.callbackQueue + afterUserStopped:YES + block:^{ + // Repeated calls to stopFetching may cause this path to be reached despite having sent a real + // cancel request, check here to ensure that the cancellation handler invocation which fires + // will definitely be for the real request sent previously. + @synchronized(self) { + if (self->_isCancelInFlight) { + return; + } + } + [self triggerCancellationHandlerForFetch:nil data:nil error:nil]; + }]; + } + + [super stopFetching]; +} + +// Fires the cancellation handler, returning whether there was a handler to be fired. +- (BOOL)triggerCancellationHandlerForFetch:(GTMSessionFetcher *)fetcher + data:(NSData *)data + error:(NSError *)error { + GTMSessionUploadFetcherCancellationHandler handler = self.cancellationHandler; + if (handler) { + handler(fetcher, data, error); + self.cancellationHandler = nil; + return YES; + } + return NO; +} + +#pragma mark - + +- (int64_t)updateChunkFetcher:(GTMSessionFetcher *)chunkFetcher + forChunkAtOffset:(int64_t)offset { + BOOL isUploadingFileURL = (self.uploadFileURL != nil); + + // Upload another chunk, meeting server-required granularity. + int64_t chunkSize = self.chunkSize; + + int64_t fullUploadLength = [self fullUploadLength]; + BOOL isFileLengthKnown = fullUploadLength >= 0; + + BOOL isUploadingFullFile = (offset == 0 && isFileLengthKnown && chunkSize >= fullUploadLength); + if (!isUploadingFileURL || !isUploadingFullFile) { + // We're not uploading the entire file and given the file URL. Since we'll be + // allocating a subdata block for a chunk, we need to bound it to something that + // won't blow the process's memory. + if (chunkSize > kGTMSessionUploadFetcherMaximumDemandBufferSize) { + chunkSize = kGTMSessionUploadFetcherMaximumDemandBufferSize; + } + } + + int64_t granularity = self.uploadGranularity; + if (granularity > 0) { + if (chunkSize < granularity) { + chunkSize = granularity; + } else { + chunkSize = chunkSize - (chunkSize % granularity); + } + } + + GTMSESSION_ASSERT_DEBUG(offset < fullUploadLength || fullUploadLength == 0, + @"offset %lld exceeds data length %lld", offset, fullUploadLength); + + if (granularity > 0) { + offset = offset - (offset % granularity); + } + + // If the chunk size is bigger than the remaining data, or else + // it's close enough in size to the remaining data that we'd rather + // avoid having a whole extra http fetch for the leftover bit, then make + // this chunk size exactly match the remaining data size + NSString *command; + int64_t thisChunkSize = chunkSize; + + BOOL isChunkTooBig = (thisChunkSize >= (fullUploadLength - offset)); + BOOL isChunkAlmostBigEnough = (fullUploadLength - offset - 2500 < thisChunkSize); + BOOL isFinalChunk = (isChunkTooBig || isChunkAlmostBigEnough) && isFileLengthKnown; + if (isFinalChunk) { + thisChunkSize = fullUploadLength - offset; + if (thisChunkSize > 0) { + command = @"upload, finalize"; + } else { + command = @"finalize"; + } + } else { + command = @"upload"; + } + NSString *lengthStr = @(thisChunkSize).stringValue; + NSString *offsetStr = @(offset).stringValue; + + [chunkFetcher setRequestValue:command forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + [chunkFetcher setRequestValue:lengthStr forHTTPHeaderField:@"Content-Length"]; + [chunkFetcher setRequestValue:offsetStr forHTTPHeaderField:kGTMSessionHeaderXGoogUploadOffset]; + if (_uploadFileLength != kGTMSessionUploadFetcherUnknownFileSize) { + [chunkFetcher setRequestValue:@([self fullUploadLength]).stringValue + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength]; + } + + // Append the range of bytes in this chunk to the fetcher comment. + NSString *baseComment = self.comment; + [chunkFetcher setCommentWithFormat:@"%@ (%lld-%lld)", + baseComment ? baseComment : @"upload", offset, MAX(0, offset + thisChunkSize - 1)]; + + return thisChunkSize; +} + +// Public properties. +@synthesize currentOffset = _currentOffset, + delegateCompletionHandler = _delegateCompletionHandler, + chunkFetcher = _chunkFetcher, + lastChunkRequest = _lastChunkRequest, + subdataGenerating = _subdataGenerating, + shouldInitiateOffsetQuery = _shouldInitiateOffsetQuery, + uploadGranularity = _uploadGranularity; + +// Internal properties. +@dynamic fetcherInFlight; +@dynamic activeFetcher; +@dynamic statusCode; +@dynamic delegateCallbackQueue; + ++ (void)removePointer:(void *)pointer fromPointerArray:(NSPointerArray *)pointerArray { + for (NSUInteger index = 0, count = pointerArray.count; index < count; ++index) { + void *pointerAtIndex = [pointerArray pointerAtIndex:index]; + if (pointerAtIndex == pointer) { + [pointerArray removePointerAtIndex:index]; + return; + } + } +} + +- (BOOL)useBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _useBackgroundSessionOnChunkFetchers; + } // @synchronized(self +} + +- (void)setUseBackgroundSession:(BOOL)useBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_useBackgroundSessionOnChunkFetchers != useBackgroundSession) { + _useBackgroundSessionOnChunkFetchers = useBackgroundSession; + NSPointerArray *uploadFetcherPointerArrayForBackgroundSessions = + [[self class] uploadFetcherPointerArrayForBackgroundSessions]; + if (_useBackgroundSessionOnChunkFetchers) { + [uploadFetcherPointerArrayForBackgroundSessions addPointer:(__bridge void *)self]; + } else { + [[self class] removePointer:(__bridge void *)self + fromPointerArray:uploadFetcherPointerArrayForBackgroundSessions]; + } + } + } // @synchronized(self +} + +- (BOOL)canFetchWithBackgroundSession { + // The initial upload fetcher is always a foreground session; the + // useBackgroundSession property will apply only to chunk fetchers, + // not to queries. + return NO; +} + +- (NSDictionary *)responseHeaders { + GTMSessionCheckNotSynchronized(self); + // Overrides the superclass + + // If asked for the fetcher's response, use the most recent chunk fetcher's response, + // since the original request's response lacks useful information like the actual + // Content-Type. + NSDictionary *dict = self.chunkFetcher.responseHeaders; + if (dict) { + return dict; + } + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_recentChunkReponseHeaders) { + return _recentChunkReponseHeaders; + } + } // @synchronized(self + + // No chunk fetcher yet completed, so return whatever we have from the initial fetch. + return [super responseHeaders]; +} + +- (NSInteger)statusCodeUnsynchronized { + GTMSessionCheckSynchronized(self); + + if (_recentChunkStatusCode != -1) { + // Overrides the superclass to indicate status appropriate to the initial + // or latest chunk fetch + return _recentChunkStatusCode; + } else { + return [super statusCodeUnsynchronized]; + } +} + + +- (void)setStatusCode:(NSInteger)val { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _recentChunkStatusCode = val; + } +} + +- (int64_t)initialBodyLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _initialBodyLength; + } +} + +- (void)setInitialBodyLength:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _initialBodyLength = length; + } +} + +- (int64_t)initialBodySent { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _initialBodySent; + } +} + +- (void)setInitialBodySent:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _initialBodySent = length; + } +} + +- (NSURL *)uploadLocationURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadLocationURL; + } +} + +- (void)setUploadLocationURL:(NSURL *)locationURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadLocationURL = locationURL; + } +} + +- (GTMSessionFetcher *)activeFetcher { + GTMSessionFetcher *result = self.fetcherInFlight; + if (result) return result; + + return self; +} + +- (BOOL)isFetching { + // If there is an active chunk fetcher, then the upload fetcher is considered + // to still be fetching. + if (self.fetcherInFlight != nil) return YES; + + return [super isFetching]; +} + +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { + NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + + while (self.fetcherInFlight || self.subdataGenerating) { + if ([timeoutDate timeIntervalSinceNow] < 0) return NO; + + if (self.subdataGenerating) { + // Allow time for subdata generation. + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + // Wait for any chunk or query fetchers that still have pending callbacks or + // notifications. + BOOL timedOut; + + if (self.fetcherInFlight == self) { + timedOut = ![super waitForCompletionWithTimeout:timeoutInSeconds]; + } else { + timedOut = ![self.fetcherInFlight waitForCompletionWithTimeout:timeoutInSeconds]; + } + if (timedOut) return NO; + } + } + return YES; +} + +@end + +@implementation GTMSessionFetcher (GTMSessionUploadFetcherMethods) + +- (GTMSessionUploadFetcher *)parentUploadFetcher { + NSValue *property = [self propertyForKey:kGTMSessionUploadFetcherChunkParentKey]; + if (!property) return nil; + + GTMSessionUploadFetcher *uploadFetcher = property.nonretainedObjectValue; + + GTMSESSION_ASSERT_DEBUG([uploadFetcher isKindOfClass:[GTMSessionUploadFetcher class]], + @"Unexpected parent upload fetcher class: %@", [uploadFetcher class]); + return uploadFetcher; +} + +@end diff --git a/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement b/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement new file mode 100755 index 0000000..a43b2d2 Binary files /dev/null and b/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/GoogleAppMeasurement differ diff --git a/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap b/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap new file mode 100755 index 0000000..ea1e687 --- /dev/null +++ b/My Mind/Pods/GoogleAppMeasurement/Frameworks/GoogleAppMeasurement.framework/Modules/module.modulemap @@ -0,0 +1,9 @@ +framework module GoogleAppMeasurement { + export * + module * { export *} + link "sqlite3" + link "z" + link framework "Security" + link framework "StoreKit" + link framework "SystemConfiguration" + link framework "UIKit"} diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m new file mode 100644 index 0000000..59f400d --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m @@ -0,0 +1,718 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "TargetConditionals.h" + +#if TARGET_OS_IOS + +#import +#import +#import +#import "../Common/GULLoggerCodes.h" +#import "Internal/GULAppDelegateSwizzler_Private.h" +#import "Private/GULAppDelegateSwizzler.h" + +#import +#import + +// Implementations need to be typed before calling the implementation directly to cast the +// arguments and the return types correctly. Otherwise, it will crash the app. +typedef BOOL (*GULRealOpenURLSourceApplicationAnnotationIMP)( + id, SEL, UIApplication *, NSURL *, NSString *, id); + +typedef BOOL (*GULRealOpenURLOptionsIMP)( + id, SEL, UIApplication *, NSURL *, NSDictionary *); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wstrict-prototypes" +typedef void (*GULRealHandleEventsForBackgroundURLSessionIMP)( + id, SEL, UIApplication *, NSString *, void (^)()); +#pragma clang diagnostic pop + +// This is needed to for the library to be warning free on iOS versions < 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +typedef BOOL (*GULRealContinueUserActivityIMP)( + id, SEL, UIApplication *, NSUserActivity *, void (^)(NSArray *restorableObjects)); +#pragma clang diagnostic pop + +typedef void (^GULAppDelegateInterceptorCallback)(id); + +// The strings below are the keys for associated objects. +static char const *const kGULContinueUserActivityIMPKey = "GUL_continueUserActivityIMP"; +static char const *const kGULHandleBackgroundSessionIMPKey = "GUL_handleBackgroundSessionIMP"; +static char const *const kGULOpenURLOptionsIMPKey = "GUL_openURLOptionsIMP"; +static char const *const kGULOpenURLOptionsSourceAnnotationsIMPKey = + "GUL_openURLSourceApplicationAnnotationIMP"; +static char const *const kGULRealClassKey = "GUL_realClass"; +static NSString *const kGULAppDelegateKeyPath = @"delegate"; + +static GULLoggerService kGULLoggerSwizzler = @"[GoogleUtilities/AppDelegateSwizzler]"; + +// Since Firebase SDKs also use this for app delegate proxying, in order to not be a breaking change +// we disable App Delegate proxying when either of these two flags are set to NO. + +/** Plist key that allows Firebase developers to disable App Delegate Proxying. */ +static NSString *const kGULFirebaseAppDelegateProxyEnabledPlistKey = + @"FirebaseAppDelegateProxyEnabled"; + +/** Plist key that allows developers not using Firebase to disable App Delegate Proxying. */ +static NSString *const kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey = + @"GoogleUtilitiesAppDelegateProxyEnabled"; + +/** The prefix of the App Delegate. */ +static NSString *const kGULAppDelegatePrefix = @"GUL_"; + +/** The original instance of App Delegate. */ +static id gOriginalAppDelegate; + +/** + * This class is necessary to store the delegates in an NSArray without retaining them. + * [NSValue valueWithNonRetainedObject] also provides this functionality, but does not provide a + * zeroing pointer. This will cause EXC_BAD_ACCESS when trying to access the object after it is + * dealloced. Instead, this container stores a weak, zeroing reference to the object, which + * automatically is set to nil by the runtime when the object is dealloced. + */ +@interface GULZeroingWeakContainer : NSObject + +/** Stores a weak object. */ +@property(nonatomic, weak) id object; + +@end + +@implementation GULZeroingWeakContainer +@end + +@interface GULAppDelegateObserver : NSObject +@end + +@implementation GULAppDelegateObserver { + BOOL _isObserving; +} + ++ (GULAppDelegateObserver *)sharedInstance { + static GULAppDelegateObserver *instance; + static dispatch_once_t once; + dispatch_once(&once, ^{ + instance = [[GULAppDelegateObserver alloc] init]; + }); + return instance; +} + +- (void)observeUIApplication { + if (_isObserving) { + return; + } + [[GULAppDelegateSwizzler sharedApplication] + addObserver:self + forKeyPath:kGULAppDelegateKeyPath + options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld + context:nil]; + _isObserving = YES; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context { + if ([keyPath isEqual:kGULAppDelegateKeyPath]) { + id newValue = change[NSKeyValueChangeNewKey]; + id oldValue = change[NSKeyValueChangeOldKey]; + if ([newValue isEqual:oldValue]) { + return; + } + // Free the stored app delegate instance because it has been changed to a different instance to + // avoid keeping it alive forever. + if ([oldValue isEqual:gOriginalAppDelegate]) { + gOriginalAppDelegate = nil; + // Remove the observer. Parse it to NSObject to avoid warning. + [[GULAppDelegateSwizzler sharedApplication] removeObserver:self + forKeyPath:kGULAppDelegateKeyPath]; + _isObserving = NO; + } + } +} + +@end + +@implementation GULAppDelegateSwizzler + +static dispatch_once_t sProxyAppDelegateOnceToken; + +#pragma mark - Public methods + ++ (BOOL)isAppDelegateProxyEnabled { + NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary; + + id isFirebaseProxyEnabledPlistValue = infoDictionary[kGULFirebaseAppDelegateProxyEnabledPlistKey]; + id isGoogleProxyEnabledPlistValue = + infoDictionary[kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey]; + + // Enabled by default. + BOOL isFirebaseAppDelegateProxyEnabled = YES; + BOOL isGoogleUtilitiesAppDelegateProxyEnabled = YES; + + if ([isFirebaseProxyEnabledPlistValue isKindOfClass:[NSNumber class]]) { + isFirebaseAppDelegateProxyEnabled = [isFirebaseProxyEnabledPlistValue boolValue]; + } + + if ([isGoogleProxyEnabledPlistValue isKindOfClass:[NSNumber class]]) { + isGoogleUtilitiesAppDelegateProxyEnabled = [isGoogleProxyEnabledPlistValue boolValue]; + } + + // Only deactivate the proxy if it is explicitly disabled by app developers using either one of + // the plist flags. + return isFirebaseAppDelegateProxyEnabled && isGoogleUtilitiesAppDelegateProxyEnabled; +} + ++ (GULAppDelegateInterceptorID)registerAppDelegateInterceptor: + (id)interceptor { + NSAssert(interceptor, @"AppDelegateProxy cannot add nil interceptor"); + NSAssert([interceptor conformsToProtocol:@protocol(UIApplicationDelegate)], + @"AppDelegateProxy interceptor does not conform to UIApplicationDelegate"); + + if (!interceptor) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling000], + @"AppDelegateProxy cannot add nil interceptor."); + return nil; + } + if (![interceptor conformsToProtocol:@protocol(UIApplicationDelegate)]) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling001], + @"AppDelegateProxy interceptor does not conform to UIApplicationDelegate"); + return nil; + } + + // The ID should be the same given the same interceptor object. + NSString *interceptorID = [NSString stringWithFormat:@"%@%p", kGULAppDelegatePrefix, interceptor]; + if (!interceptorID.length) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling002], + @"AppDelegateProxy cannot create Interceptor ID."); + return nil; + } + GULZeroingWeakContainer *weakObject = [[GULZeroingWeakContainer alloc] init]; + weakObject.object = interceptor; + [GULAppDelegateSwizzler interceptors][interceptorID] = weakObject; + return interceptorID; +} + ++ (void)unregisterAppDelegateInterceptorWithID:(GULAppDelegateInterceptorID)interceptorID { + NSAssert(interceptorID, @"AppDelegateProxy cannot unregister nil interceptor ID."); + NSAssert(((NSString *)interceptorID).length != 0, + @"AppDelegateProxy cannot unregister empty interceptor ID."); + + if (!interceptorID) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling003], + @"AppDelegateProxy cannot unregister empty interceptor ID."); + return; + } + + GULZeroingWeakContainer *weakContainer = [GULAppDelegateSwizzler interceptors][interceptorID]; + if (!weakContainer.object) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling004], + @"AppDelegateProxy cannot unregister interceptor that was not registered. " + "Interceptor ID %@", + interceptorID); + return; + } + + [[GULAppDelegateSwizzler interceptors] removeObjectForKey:interceptorID]; +} + ++ (void)proxyOriginalDelegate { + dispatch_once(&sProxyAppDelegateOnceToken, ^{ + id originalDelegate = + [GULAppDelegateSwizzler sharedApplication].delegate; + [GULAppDelegateSwizzler proxyAppDelegate:originalDelegate]; + }); +} + +#pragma mark - Create proxy + ++ (UIApplication *)sharedApplication { + if ([GULAppEnvironmentUtil isAppExtension]) { + return nil; + } + id sharedApplication = nil; + Class uiApplicationClass = NSClassFromString(@"UIApplication"); + if (uiApplicationClass && + [uiApplicationClass respondsToSelector:(NSSelectorFromString(@"sharedApplication"))]) { + sharedApplication = [uiApplicationClass sharedApplication]; + } + return sharedApplication; +} + +#pragma mark - Override default methods + +/** Creates a new subclass of the class of the given object and sets the isa value of the given + * object to the new subclass. Additionally this copies methods to that new subclass that allow us + * to intercept UIApplicationDelegate methods. This is better known as isa swizzling. + * + * @param anObject The object to which you want to isa swizzle. This has to conform to the + * UIApplicationDelegate subclass. + */ ++ (void)createSubclassWithObject:(id)anObject { + Class realClass = [anObject class]; + + // Create GUL__ + NSString *classNameWithPrefix = + [kGULAppDelegatePrefix stringByAppendingString:NSStringFromClass(realClass)]; + NSTimeInterval timestamp = [NSDate date].timeIntervalSince1970; + NSString *newClassName = + [NSString stringWithFormat:@"%@-%0.0f", classNameWithPrefix, timestamp * 1000]; + + if (NSClassFromString(newClassName)) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling005], + @"Cannot create a proxy for App Delegate. Subclass already exists. Original Class: " + @"%@, subclass: %@", + NSStringFromClass(realClass), newClassName); + return; + } + + // Register the new class as subclass of the real one. Do not allocate more than the real class + // size. + Class appDelegateSubClass = objc_allocateClassPair(realClass, newClassName.UTF8String, 0); + if (appDelegateSubClass == Nil) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling006], + @"Cannot create a proxy for App Delegate. Subclass already exists. Original Class: " + @"%@, subclass: Nil", + NSStringFromClass(realClass)); + return; + } + + // Add the following methods from GULAppDelegate class, and store the real implementation so it + // can forward to the real one. + // For application:openURL:options: + NSValue *openURLOptionsIMPPointer; + SEL applicationOpenURLOptionsSEL = @selector(application:openURL:options:); + if ([anObject respondsToSelector:applicationOpenURLOptionsSEL]) { + // Only add the application:openURL:options: method if the original AppDelegate implements it. + // This fixes a bug if an app only implements application:openURL:sourceApplication:annotation: + // (if we add the `options` method, iOS sees that one exists and does not call the + // `sourceApplication` method, which in this case is the only one the app implements). + + [GULAppDelegateSwizzler addInstanceMethodWithSelector:applicationOpenURLOptionsSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealOpenURLOptionsIMP openURLOptionsIMP = (GULRealOpenURLOptionsIMP) + [GULAppDelegateSwizzler implementationOfMethodSelector:applicationOpenURLOptionsSEL + fromClass:realClass]; + openURLOptionsIMPPointer = [NSValue valueWithPointer:openURLOptionsIMP]; + } + + // For application:continueUserActivity:restorationHandler: + SEL continueUserActivitySEL = @selector(application:continueUserActivity:restorationHandler:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:continueUserActivitySEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealContinueUserActivityIMP continueUserActivityIMP = (GULRealContinueUserActivityIMP) + [GULAppDelegateSwizzler implementationOfMethodSelector:continueUserActivitySEL + fromClass:realClass]; + NSValue *continueUserActivityIMPPointer = [NSValue valueWithPointer:continueUserActivityIMP]; + + // For application:openURL:sourceApplication:annotation: + SEL openURLSourceApplicationAnnotationSEL = + @selector(application:openURL:sourceApplication:annotation:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:openURLSourceApplicationAnnotationSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealOpenURLSourceApplicationAnnotationIMP openURLSourceApplicationAnnotationIMP = + (GULRealOpenURLSourceApplicationAnnotationIMP)[GULAppDelegateSwizzler + implementationOfMethodSelector:openURLSourceApplicationAnnotationSEL + fromClass:realClass]; + NSValue *openURLSourceAppAnnotationIMPPointer = + [NSValue valueWithPointer:openURLSourceApplicationAnnotationIMP]; + + // For application:handleEventsForBackgroundURLSession:completionHandler: + SEL handleEventsForBackgroundURLSessionSEL = + @selector(application:handleEventsForBackgroundURLSession:completionHandler:); + [GULAppDelegateSwizzler addInstanceMethodWithSelector:handleEventsForBackgroundURLSessionSEL + fromClass:[GULAppDelegateSwizzler class] + toClass:appDelegateSubClass]; + GULRealHandleEventsForBackgroundURLSessionIMP handleBackgroundSessionIMP = + (GULRealHandleEventsForBackgroundURLSessionIMP)[GULAppDelegateSwizzler + implementationOfMethodSelector:handleEventsForBackgroundURLSessionSEL + fromClass:realClass]; + NSValue *handleBackgroundSessionIMPPointer = + [NSValue valueWithPointer:handleBackgroundSessionIMP]; + + // Override the description too so the custom class name will not show up. + [GULAppDelegateSwizzler addInstanceMethodWithDestinationSelector:@selector(description) + withImplementationFromSourceSelector:@selector(fakeDescription) + fromClass:[self class] + toClass:appDelegateSubClass]; + + // Create fake properties for the real app delegate object. + objc_setAssociatedObject(anObject, &kGULContinueUserActivityIMPKey, + continueUserActivityIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(anObject, &kGULHandleBackgroundSessionIMPKey, + handleBackgroundSessionIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + if (openURLOptionsIMPPointer) { + objc_setAssociatedObject(anObject, &kGULOpenURLOptionsIMPKey, openURLOptionsIMPPointer, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + objc_setAssociatedObject(anObject, &kGULOpenURLOptionsSourceAnnotationsIMPKey, + openURLSourceAppAnnotationIMPPointer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(anObject, &kGULRealClassKey, realClass, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // The subclass size has to be exactly the same size with the original class size. The subclass + // cannot have more ivars/properties than its superclass since it will cause an offset in memory + // that can lead to overwriting the isa of an object in the next frame. + if (class_getInstanceSize(realClass) != class_getInstanceSize(appDelegateSubClass)) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling007], + @"Cannot create subclass of App Delegate, because the created subclass is not the " + @"same size. %@", + NSStringFromClass(realClass)); + NSAssert(NO, @"Classes must be the same size to swizzle isa"); + return; + } + + // Make the newly created class to be the subclass of the real App Delegate class. + objc_registerClassPair(appDelegateSubClass); + if (object_setClass(anObject, appDelegateSubClass)) { + GULLogDebug(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling008], + @"Successfully created App Delegate Proxy automatically. To disable the " + @"proxy, set the flag %@ to NO (Boolean) in the Info.plist", + [GULAppDelegateSwizzler correctAppDelegateProxyKey]); + } + + // We have to do this to invalidate the cache that caches the original respondsToSelector of + // openURL handlers. Without this, it won't call the default implementations because the system + // checks and caches them. + // Register KVO only once. Otherwise, the observing method will be called as many times as + // being registered. + id delegate = [GULAppDelegateSwizzler sharedApplication].delegate; + [GULAppDelegateSwizzler sharedApplication].delegate = nil; + [GULAppDelegateSwizzler sharedApplication].delegate = delegate; + gOriginalAppDelegate = delegate; + [[GULAppDelegateObserver sharedInstance] observeUIApplication]; +} + +#pragma mark - Helper methods + ++ (GULMutableDictionary *)interceptors { + static dispatch_once_t onceToken; + static GULMutableDictionary *sInterceptors; + dispatch_once(&onceToken, ^{ + sInterceptors = [[GULMutableDictionary alloc] init]; + }); + return sInterceptors; +} + +/** Copies a method identified by the methodSelector from one class to the other. After this method + * is called, performing [toClassInstance methodSelector] will be similar to calling + * [fromClassInstance methodSelector]. This method does nothing if toClass already has a method + * identified by methodSelector. + * + * @param methodSelector The SEL that identifies both the method on the fromClass as well as the + * one on the toClass. + * @param fromClass The class from which a method is sourced. + * @param toClass The class to which the method is added. If the class already has a method with + * the same selector, this has no effect. + */ ++ (void)addInstanceMethodWithSelector:(SEL)methodSelector + fromClass:(Class)fromClass + toClass:(Class)toClass { + [self addInstanceMethodWithDestinationSelector:methodSelector + withImplementationFromSourceSelector:methodSelector + fromClass:fromClass + toClass:toClass]; +} + +/** Copies a method identified by the sourceSelector from the fromClass as a method for the + * destinationSelector on the toClass. After this method is called, performing + * [toClassInstance destinationSelector] will be similar to calling + * [fromClassInstance sourceSelector]. This method does nothing if toClass already has a method + * identified by destinationSelector. + * + * @param destinationSelector The SEL that identifies the method on the toClass. + * @param sourceSelector The SEL that identifies the method on the fromClass. + * @param fromClass The class from which a method is sourced. + * @param toClass The class to which the method is added. If the class already has a method with + * the same selector, this has no effect. + */ ++ (void)addInstanceMethodWithDestinationSelector:(SEL)destinationSelector + withImplementationFromSourceSelector:(SEL)sourceSelector + fromClass:(Class)fromClass + toClass:(Class)toClass { + Method method = class_getInstanceMethod(fromClass, sourceSelector); + IMP methodIMP = method_getImplementation(method); + const char *types = method_getTypeEncoding(method); + if (!class_addMethod(toClass, destinationSelector, methodIMP, types)) { + GULLogWarning(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling009], + @"Cannot copy method to destination selector %@ as it already exists", + NSStringFromSelector(destinationSelector)); + } +} + +/** Gets the IMP of the instance method on the class identified by the selector. + * + * @param selector The selector of which the IMP is to be fetched. + * @param aClass The class from which the IMP is to be fetched. + * @return The IMP of the instance method identified by selector and aClass. + */ ++ (IMP)implementationOfMethodSelector:(SEL)selector fromClass:(Class)aClass { + Method aMethod = class_getInstanceMethod(aClass, selector); + return method_getImplementation(aMethod); +} + +/** Enumerates through all the interceptors and if they respond to a given selector, executes a + * GULAppDelegateInterceptorCallback with the interceptor. + * + * @param methodSelector The SEL to check if an interceptor responds to. + * @param callback the GULAppDelegateInterceptorCallback. + */ ++ (void)notifyInterceptorsWithMethodSelector:(SEL)methodSelector + callback:(GULAppDelegateInterceptorCallback)callback { + if (!callback) { + return; + } + + NSDictionary *interceptors = [GULAppDelegateSwizzler interceptors].dictionary; + [interceptors enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + GULZeroingWeakContainer *interceptorContainer = obj; + id interceptor = interceptorContainer.object; + if (!interceptor) { + GULLogWarning( + kGULLoggerSwizzler, NO, + [NSString + stringWithFormat:@"I-SWZ%06ld", (long)kGULSwizzlerMessageCodeAppDelegateSwizzling010], + @"AppDelegateProxy cannot find interceptor with ID %@. Removing the interceptor.", key); + [[GULAppDelegateSwizzler interceptors] removeObjectForKey:key]; + return; + } + if ([interceptor respondsToSelector:methodSelector]) { + callback(interceptor); + } + }]; +} + +// The methods below are donor methods which are added to the dynamic subclass of the App Delegate. +// They are called within the scope of the real App Delegate so |self| does not refer to the +// GULAppDelegateSwizzler instance but the real App Delegate instance. + +#pragma mark - [Donor Methods] Overridden instance description method + +- (NSString *)fakeDescription { + Class realClass = objc_getAssociatedObject(self, &kGULRealClassKey); + return [NSString stringWithFormat:@"<%@: %p>", realClass, self]; +} + +#pragma mark - [Donor Methods] URL overridden handler methods + +- (BOOL)application:(UIApplication *)application + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Call the real implementation if the real App Delegate has any. + NSValue *openURLIMPPointer = objc_getAssociatedObject(self, &kGULOpenURLOptionsIMPKey); + GULRealOpenURLOptionsIMP openURLOptionsIMP = [openURLIMPPointer pointerValue]; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:openURL:options:); + +// This is needed to for the library to be warning free on iOS versions < 9. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + returnedValue |= [interceptor application:application + openURL:url + options:options]; + }]; +#pragma clang diagnostic pop + if (openURLOptionsIMP) { + returnedValue |= openURLOptionsIMP(self, methodSelector, application, url, options); + } + return returnedValue; +} + +- (BOOL)application:(UIApplication *)application + openURL:(NSURL *)url + sourceApplication:(NSString *)sourceApplication + annotation:(id)annotation { + // Call the real implementation if the real App Delegate has any. + NSValue *openURLSourceAppAnnotationIMPPointer = + objc_getAssociatedObject(self, &kGULOpenURLOptionsSourceAnnotationsIMPKey); + GULRealOpenURLSourceApplicationAnnotationIMP openURLSourceApplicationAnnotationIMP = + [openURLSourceAppAnnotationIMPPointer pointerValue]; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:openURL:sourceApplication:annotation:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + returnedValue |= [interceptor application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; +#pragma clang diagnostic pop + }]; + if (openURLSourceApplicationAnnotationIMP) { + returnedValue |= openURLSourceApplicationAnnotationIMP(self, methodSelector, application, url, + sourceApplication, annotation); + } + return returnedValue; +} + +#pragma mark - [Donor Methods] Network overridden handler methods + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wstrict-prototypes" +- (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(void (^)())completionHandler API_AVAILABLE(ios(7.0)) { +#pragma clang diagnostic pop + NSValue *handleBackgroundSessionPointer = + objc_getAssociatedObject(self, &kGULHandleBackgroundSessionIMPKey); + GULRealHandleEventsForBackgroundURLSessionIMP handleBackgroundSessionIMP = + [handleBackgroundSessionPointer pointerValue]; + + // Notify interceptors. + SEL methodSelector = + @selector(application:handleEventsForBackgroundURLSession:completionHandler:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + [interceptor application:application + handleEventsForBackgroundURLSession:identifier + completionHandler:completionHandler]; + }]; + // Call the real implementation if the real App Delegate has any. + if (handleBackgroundSessionIMP) { + handleBackgroundSessionIMP(self, methodSelector, application, identifier, completionHandler); + } +} + +#pragma mark - [Donor Methods] User Activities overridden handler methods + +// This is needed to for the library to be warning free on iOS versions < 8. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (BOOL)application:(UIApplication *)application + continueUserActivity:(NSUserActivity *)userActivity + restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { + NSValue *continueUserActivityIMPPointer = + objc_getAssociatedObject(self, &kGULContinueUserActivityIMPKey); + GULRealContinueUserActivityIMP continueUserActivityIMP = + continueUserActivityIMPPointer.pointerValue; + + __block BOOL returnedValue = NO; + SEL methodSelector = @selector(application:continueUserActivity:restorationHandler:); + [GULAppDelegateSwizzler + notifyInterceptorsWithMethodSelector:methodSelector + callback:^(id interceptor) { + returnedValue |= [interceptor application:application + continueUserActivity:userActivity + restorationHandler:restorationHandler]; + }]; + // Call the real implementation if the real App Delegate has any. + if (continueUserActivityIMP) { + returnedValue |= continueUserActivityIMP(self, methodSelector, application, userActivity, + restorationHandler); + } + return returnedValue; +} +#pragma clang diagnostic pop + ++ (void)proxyAppDelegate:(id)appDelegate { + id originalDelegate = appDelegate; + // Do not create a subclass if it is not enabled. + if (![GULAppDelegateSwizzler isAppDelegateProxyEnabled]) { + GULLogNotice(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling011], + @"App Delegate Proxy is disabled. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } + // Do not accept nil delegate. + if (!originalDelegate) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling012], + @"Cannot create App Delegate Proxy because App Delegate instance is nil. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } + + @try { + [self createSubclassWithObject:originalDelegate]; + } @catch (NSException *exception) { + GULLogError(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeAppDelegateSwizzling013], + @"Cannot create App Delegate Proxy. %@", + [GULAppDelegateSwizzler correctAlternativeWhenAppDelegateProxyNotCreated]); + return; + } +} + +#pragma mark - Methods to print correct debug logs + ++ (NSString *)correctAppDelegateProxyKey { + return NSClassFromString(@"FIRCore") ? kGULFirebaseAppDelegateProxyEnabledPlistKey + : kGULGoogleUtilitiesAppDelegateProxyEnabledPlistKey; +} + ++ (NSString *)correctAlternativeWhenAppDelegateProxyNotCreated { + return NSClassFromString(@"FIRCore") + ? @"To log deep link campaigns manually, call the methods in " + @"FIRAnalytics+AppDelegate.h." + : @""; +} + +#pragma mark - Private Methods for Testing + +#ifdef GUL_APP_DELEGATE_TESTING + ++ (void)clearInterceptors { + [[self interceptors] removeAllObjects]; +} + ++ (void)resetProxyOriginalDelegateOnceToken { + sProxyAppDelegateOnceToken = 0; +} + ++ (id)originalDelegate { + return gOriginalAppDelegate; +} + +#endif // GUL_APP_DELEGATE_TESTING + +@end + +#endif // TARGET_OS_IOS diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h new file mode 100644 index 0000000..219b220 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h @@ -0,0 +1,64 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 UIApplication; + +NS_ASSUME_NONNULL_BEGIN + +@interface GULAppDelegateSwizzler () + +/** Returns the current sharedApplication. + * + * @return the current UIApplication if in an app, or nil if in extension or if it doesn't exist. + */ ++ (nullable UIApplication *)sharedApplication; + +/** ISA Swizzles the given appDelegate as the original app delegate would be. + * + * @param appDelegate The object that needs to be isa swizzled. This should conform to the + * UIApplicationDelegate protocol. + */ ++ (void)proxyAppDelegate:(id)appDelegate; + +/** Returns a dictionary containing interceptor IDs mapped to a GULZeroingWeakContainer. + * + * @return A dictionary of the form {NSString : GULZeroingWeakContainer}, where the NSString is + * the interceptorID. + */ ++ (GULMutableDictionary *)interceptors; + +#ifdef GUL_APP_DELEGATE_TESTING // Methods only used in tests. + +/** Deletes all the registered interceptors. */ ++ (void)clearInterceptors; + +/** Resets the token that prevents the app delegate proxy from being isa swizzled multiple times. */ ++ (void)resetProxyOriginalDelegateOnceToken; + +/** Returns the original app delegate that was proxied. + * + * @return The original app delegate instance that was proxied. + */ ++ (id)originalDelegate; + +#endif // GUL_APP_DELEGATE_TESTING + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h new file mode 100644 index 0000000..31fc4b0 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h @@ -0,0 +1,63 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 + +@protocol UIApplicationDelegate; + +NS_ASSUME_NONNULL_BEGIN + +typedef NSString *const GULAppDelegateInterceptorID; + +/** This class contains methods that isa swizzle the app delegate. */ +@interface GULAppDelegateSwizzler : NSProxy + +/** Registers an app delegate interceptor whose methods will be invoked as they're invoked on the + * original app delegate. + * + * @param interceptor An instance of a class that conforms to the UIApplicationDelegate protocol. + * The interceptor is NOT retained. + * @return A unique GULAppDelegateInterceptorID if interceptor was successfully registered; nil + * if it fails. + */ ++ (nullable GULAppDelegateInterceptorID)registerAppDelegateInterceptor: + (id)interceptor; + +/** Unregisters an interceptor with the given ID if it exists. + * + * @param interceptorID The object that was generated when the interceptor was registered. + */ ++ (void)unregisterAppDelegateInterceptorWithID:(GULAppDelegateInterceptorID)interceptorID; + +/** This method ensures that the original app delegate has been proxied. Call this before + * registering your interceptor. This method is safe to call multiple times (but it only proxies + * the app delegate once). + */ ++ (void)proxyOriginalDelegate NS_EXTENSION_UNAVAILABLE( + "App delegate proxy doesn't support extensions."); + +/** Indicates whether app delegate proxy is explicitly disabled or enabled. Enabled by default. + * + * @return YES if AppDelegateProxy is Enabled, NO otherwise. + */ ++ (BOOL)isAppDelegateProxyEnabled; + +/** Do not initialize this class. */ +- (instancetype)init NS_UNAVAILABLE; + +NS_ASSUME_NONNULL_END + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h new file mode 100644 index 0000000..b71c037 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Common/GULLoggerCodes.h @@ -0,0 +1,36 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +typedef NS_ENUM(NSInteger, GULSwizzlerMessageCode) { + // App Delegate Swizzling. + kGULSwizzlerMessageCodeAppDelegateSwizzling000 = 1000, // I-SWZ001000 + kGULSwizzlerMessageCodeAppDelegateSwizzling001 = 1001, // I-SWZ001001 + kGULSwizzlerMessageCodeAppDelegateSwizzling002 = 1002, // I-SWZ001002 + kGULSwizzlerMessageCodeAppDelegateSwizzling003 = 1003, // I-SWZ001003 + kGULSwizzlerMessageCodeAppDelegateSwizzling004 = 1004, // I-SWZ001004 + kGULSwizzlerMessageCodeAppDelegateSwizzling005 = 1005, // I-SWZ001005 + kGULSwizzlerMessageCodeAppDelegateSwizzling006 = 1006, // I-SWZ001006 + kGULSwizzlerMessageCodeAppDelegateSwizzling007 = 1007, // I-SWZ001007 + kGULSwizzlerMessageCodeAppDelegateSwizzling008 = 1008, // I-SWZ001008 + kGULSwizzlerMessageCodeAppDelegateSwizzling009 = 1009, // I-SWZ001009 + kGULSwizzlerMessageCodeAppDelegateSwizzling010 = 1010, // I-SWZ001010 + kGULSwizzlerMessageCodeAppDelegateSwizzling011 = 1011, // I-SWZ001011 + kGULSwizzlerMessageCodeAppDelegateSwizzling012 = 1012, // I-SWZ001012 + kGULSwizzlerMessageCodeAppDelegateSwizzling013 = 1013, // I-SWZ001013 + + // Method Swizzling. + kGULSwizzlerMessageCodeMethodSwizzling000 = 2000, // I-SWZ002000 +}; diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h new file mode 100644 index 0000000..5b56271 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface GULAppEnvironmentUtil : NSObject + +/// Indicates whether the app is from Apple Store or not. Returns NO if the app is on simulator, +/// development environment or sideloaded. ++ (BOOL)isFromAppStore; + +/// Indicates whether the app is a Testflight app. Returns YES if the app has sandbox receipt. +/// Returns NO otherwise. ++ (BOOL)isAppStoreReceiptSandbox; + +/// Indicates whether the app is on simulator or not at runtime depending on the device +/// architecture. ++ (BOOL)isSimulator; + +/// The current device model. Returns an empty string if device model cannot be retrieved. ++ (NSString *)deviceModel; + +/// The current operating system version. Returns an empty string if the system version cannot be +/// retrieved. ++ (NSString *)systemVersion; + +/// Indicates whether it is running inside an extension or an app. ++ (BOOL)isAppExtension; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m new file mode 100644 index 0000000..1fa767b --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m @@ -0,0 +1,250 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "GULAppEnvironmentUtil.h" + +#import +#import +#import +#import + +#if TARGET_OS_IOS +#import +#endif + +/// The encryption info struct and constants are missing from the iPhoneSimulator SDK, but not from +/// the iPhoneOS or Mac OS X SDKs. Since one doesn't ever ship a Simulator binary, we'll just +/// provide the definitions here. +#if TARGET_OS_SIMULATOR && !defined(LC_ENCRYPTION_INFO) +#define LC_ENCRYPTION_INFO 0x21 +struct encryption_info_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t cryptoff; + uint32_t cryptsize; + uint32_t cryptid; +}; +#endif + +@implementation GULAppEnvironmentUtil + +/// A key for the Info.plist to enable or disable checking if the App Store is running in a sandbox. +/// This will affect your data integrity when using Firebase Analytics, as it will disable some +/// necessary checks. +static NSString *const kFIRAppStoreReceiptURLCheckEnabledKey = + @"FirebaseAppStoreReceiptURLCheckEnabled"; + +/// The file name of the sandbox receipt. This is available on iOS >= 8.0 +static NSString *const kFIRAIdentitySandboxReceiptFileName = @"sandboxReceipt"; + +/// The following copyright from Landon J. Fuller applies to the isAppEncrypted function. +/// +/// Copyright (c) 2017 Landon J. Fuller +/// 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. +/// +/// Comment from iPhone Dev Wiki +/// Crack Prevention: +/// App Store binaries are signed by both their developer and Apple. This encrypts the binary so +/// that decryption keys are needed in order to make the binary readable. When iOS executes the +/// binary, the decryption keys are used to decrypt the binary into a readable state where it is +/// then loaded into memory and executed. iOS can tell the encryption status of a binary via the +/// cryptid structure member of LC_ENCRYPTION_INFO MachO load command. If cryptid is a non-zero +/// value then the binary is encrypted. +/// +/// 'Cracking' works by letting the kernel decrypt the binary then siphoning the decrypted data into +/// a new binary file, resigning, and repackaging. This will only work on jailbroken devices as +/// codesignature validation has been removed. Resigning takes place because while the codesignature +/// doesn't have to be valid thanks to the jailbreak, it does have to be in place unless you have +/// AppSync or similar to disable codesignature checks. +/// +/// More information at Landon Fuller's blog +static BOOL IsAppEncrypted() { + const struct mach_header *executableHeader = NULL; + for (uint32_t i = 0; i < _dyld_image_count(); i++) { + const struct mach_header *header = _dyld_get_image_header(i); + if (header && header->filetype == MH_EXECUTE) { + executableHeader = header; + break; + } + } + + if (!executableHeader) { + return NO; + } + + BOOL is64bit = (executableHeader->magic == MH_MAGIC_64); + uintptr_t cursor = (uintptr_t)executableHeader + + (is64bit ? sizeof(struct mach_header_64) : sizeof(struct mach_header)); + const struct segment_command *segmentCommand = NULL; + uint32_t i = 0; + + while (i++ < executableHeader->ncmds) { + segmentCommand = (struct segment_command *)cursor; + + if (!segmentCommand) { + continue; + } + + if ((!is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO) || + (is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO_64)) { + if (is64bit) { + struct encryption_info_command_64 *cryptCmd = + (struct encryption_info_command_64 *)segmentCommand; + return cryptCmd && cryptCmd->cryptid != 0; + } else { + struct encryption_info_command *cryptCmd = (struct encryption_info_command *)segmentCommand; + return cryptCmd && cryptCmd->cryptid != 0; + } + } + cursor += segmentCommand->cmdsize; + } + + return NO; +} + +static BOOL HasSCInfoFolder() { +#if TARGET_OS_IOS || TARGET_OS_TV + NSString *bundlePath = [NSBundle mainBundle].bundlePath; + NSString *scInfoPath = [bundlePath stringByAppendingPathComponent:@"SC_Info"]; + return [[NSFileManager defaultManager] fileExistsAtPath:scInfoPath]; +#elif TARGET_OS_OSX + return NO; +#endif +} + +static BOOL HasEmbeddedMobileProvision() { +#if TARGET_OS_IOS || TARGET_OS_TV + return [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"].length > 0; +#elif TARGET_OS_OSX + return NO; +#endif +} + ++ (BOOL)isFromAppStore { + static dispatch_once_t isEncryptedOnce; + static BOOL isEncrypted = NO; + + dispatch_once(&isEncryptedOnce, ^{ + isEncrypted = IsAppEncrypted(); + }); + + if ([GULAppEnvironmentUtil isSimulator]) { + return NO; + } + + // If an app contain the sandboxReceipt file, it means its coming from TestFlight + // This must be checked before the SCInfo Folder check below since TestFlight apps may + // also have an SCInfo folder. + if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox]) { + return NO; + } + + if (HasSCInfoFolder()) { + // When iTunes downloads a .ipa, it also gets a customized .sinf file which is added to the + // main SC_Info directory. + return YES; + } + + // For iOS >= 8.0, iTunesMetadata.plist is moved outside of the sandbox. Any attempt to read + // the iTunesMetadata.plist outside of the sandbox will be rejected by Apple. + // If the app does not contain the embedded.mobileprovision which is stripped out by Apple when + // the app is submitted to store, then it is highly likely that it is from Apple Store. + return isEncrypted && !HasEmbeddedMobileProvision(); +} + ++ (BOOL)isAppStoreReceiptSandbox { + // Since checking the App Store's receipt URL can be memory intensive, check the option in the + // Info.plist if developers opted out of this check. + id enableSandboxCheck = + [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRAppStoreReceiptURLCheckEnabledKey]; + if (enableSandboxCheck && [enableSandboxCheck isKindOfClass:[NSNumber class]] && + ![enableSandboxCheck boolValue]) { + return NO; + } +// The #else is for pre Xcode 9 where @available is not yet implemented. +#if __has_builtin(__builtin_available) + if (@available(iOS 7.0, *)) { +#else + if ([[UIDevice currentDevice].systemVersion integerValue] >= 7) { +#endif + NSURL *appStoreReceiptURL = [NSBundle mainBundle].appStoreReceiptURL; + NSString *appStoreReceiptFileName = appStoreReceiptURL.lastPathComponent; + return [appStoreReceiptFileName isEqualToString:kFIRAIdentitySandboxReceiptFileName]; + } + return NO; +} + ++ (BOOL)isSimulator { +#if TARGET_OS_IOS || TARGET_OS_TV + NSString *platform = [GULAppEnvironmentUtil deviceModel]; + return [platform isEqual:@"x86_64"] || [platform isEqual:@"i386"]; +#elif TARGET_OS_OSX + return NO; +#endif +} + ++ (NSString *)deviceModel { + static dispatch_once_t once; + static NSString *deviceModel; + + dispatch_once(&once, ^{ + struct utsname systemInfo; + if (uname(&systemInfo) == 0) { + deviceModel = [NSString stringWithUTF8String:systemInfo.machine]; + } + }); + return deviceModel; +} + ++ (NSString *)systemVersion { +#if TARGET_OS_IOS + return [UIDevice currentDevice].systemVersion; +#elif TARGET_OS_OSX || TARGET_OS_TV + // Assemble the systemVersion, excluding the patch version if it's 0. + NSOperatingSystemVersion osVersion = [NSProcessInfo processInfo].operatingSystemVersion; + NSMutableString *versionString = [[NSMutableString alloc] + initWithFormat:@"%ld.%ld", (long)osVersion.majorVersion, (long)osVersion.minorVersion]; + if (osVersion.patchVersion != 0) { + [versionString appendFormat:@".%ld", (long)osVersion.patchVersion]; + } + return versionString; +#endif +} + ++ (BOOL)isAppExtension { +#if TARGET_OS_IOS || TARGET_OS_TV + // Documented by Apple + BOOL appExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]; + return appExtension; +#elif TARGET_OS_OSX + return NO; +#endif +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m new file mode 100644 index 0000000..4feb77a --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/GULLogger.m @@ -0,0 +1,207 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULLogger.h" + +#include + +#import +#import "Public/GULLoggerLevel.h" + +/// ASL client facility name used by GULLogger. +const char *kGULLoggerASLClientFacilityName = "com.google.utilities.logger"; + +static dispatch_once_t sGULLoggerOnceToken; + +static aslclient sGULLoggerClient; + +static dispatch_queue_t sGULClientQueue; + +static BOOL sGULLoggerDebugMode; + +static GULLoggerLevel sGULLoggerMaximumLevel; + +// Allow clients to register a version to include in the log. +static const char *sVersion = ""; + +static GULLoggerService kGULLoggerLogger = @"[GULLogger]"; + +#ifdef DEBUG +/// The regex pattern for the message code. +static NSString *const kMessageCodePattern = @"^I-[A-Z]{3}[0-9]{6}$"; +static NSRegularExpression *sMessageCodeRegex; +#endif + +void GULLoggerInitializeASL(void) { + dispatch_once(&sGULLoggerOnceToken, ^{ + NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue]; + uint32_t aslOptions = ASL_OPT_STDERR; +#if TARGET_OS_SIMULATOR + // The iOS 11 simulator doesn't need the ASL_OPT_STDERR flag. + if (majorOSVersion >= 11) { + aslOptions = 0; + } +#else + // Devices running iOS 10 or higher don't need the ASL_OPT_STDERR flag. + if (majorOSVersion >= 10) { + aslOptions = 0; + } +#endif // TARGET_OS_SIMULATOR + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // asl is deprecated + // Initialize the ASL client handle. + sGULLoggerClient = asl_open(NULL, kGULLoggerASLClientFacilityName, aslOptions); + sGULLoggerMaximumLevel = GULLoggerLevelNotice; + + // Set the filter used by system/device log. Initialize in default mode. + asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_NOTICE)); + + sGULClientQueue = dispatch_queue_create("GULLoggingClientQueue", DISPATCH_QUEUE_SERIAL); + dispatch_set_target_queue(sGULClientQueue, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)); +#ifdef DEBUG + sMessageCodeRegex = + [NSRegularExpression regularExpressionWithPattern:kMessageCodePattern options:0 error:NULL]; +#endif + }); +} + +void GULLoggerEnableSTDERR(void) { + asl_add_log_file(sGULLoggerClient, STDERR_FILENO); +} + +void GULLoggerForceDebug(void) { + // We should enable debug mode if we're not running from App Store. + if (![GULAppEnvironmentUtil isFromAppStore]) { + sGULLoggerDebugMode = YES; + GULSetLoggerLevel(GULLoggerLevelDebug); + } +} + +__attribute__((no_sanitize("thread"))) void GULSetLoggerLevel(GULLoggerLevel loggerLevel) { + if (loggerLevel < GULLoggerLevelMin || loggerLevel > GULLoggerLevelMax) { + GULLogError(kGULLoggerLogger, NO, @"I-COR000023", @"Invalid logger level, %ld", + (long)loggerLevel); + return; + } + GULLoggerInitializeASL(); + // We should not raise the logger level if we are running from App Store. + if (loggerLevel >= GULLoggerLevelNotice && [GULAppEnvironmentUtil isFromAppStore]) { + return; + } + + sGULLoggerMaximumLevel = loggerLevel; + dispatch_async(sGULClientQueue, ^{ + asl_set_filter(sGULLoggerClient, ASL_FILTER_MASK_UPTO(loggerLevel)); + }); +} + +/** + * Check if the level is high enough to be loggable. + */ +__attribute__((no_sanitize("thread"))) BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel) { + GULLoggerInitializeASL(); + if (sGULLoggerDebugMode) { + return YES; + } + return (BOOL)(loggerLevel <= sGULLoggerMaximumLevel); +} + +#ifdef DEBUG +void GULResetLogger() { + sGULLoggerOnceToken = 0; +} + +aslclient getGULLoggerClient() { + return sGULLoggerClient; +} + +dispatch_queue_t getGULClientQueue() { + return sGULClientQueue; +} + +BOOL getGULLoggerDebugMode() { + return sGULLoggerDebugMode; +} +#endif + +void GULLoggerRegisterVersion(const char *version) { + sVersion = version; +} + +void GULLogBasic(GULLoggerLevel level, + GULLoggerService service, + BOOL forceLog, + NSString *messageCode, + NSString *message, + va_list args_ptr) { + GULLoggerInitializeASL(); + if (!(level <= sGULLoggerMaximumLevel || sGULLoggerDebugMode || forceLog)) { + return; + } + +#ifdef DEBUG + NSCAssert(messageCode.length == 11, @"Incorrect message code length."); + NSRange messageCodeRange = NSMakeRange(0, messageCode.length); + NSUInteger numberOfMatches = + [sMessageCodeRegex numberOfMatchesInString:messageCode options:0 range:messageCodeRange]; + NSCAssert(numberOfMatches == 1, @"Incorrect message code format."); +#endif + NSString *logMsg = [[NSString alloc] initWithFormat:message arguments:args_ptr]; + logMsg = [NSString stringWithFormat:@"%s - %@[%@] %@", sVersion, service, messageCode, logMsg]; + dispatch_async(sGULClientQueue, ^{ + asl_log(sGULLoggerClient, NULL, level, "%s", logMsg.UTF8String); + }); +} +#pragma clang diagnostic pop + +/** + * Generates the logging functions using macros. + * + * Calling GULLogError(kGULLoggerCore, @"I-COR000001", @"Configure %@ failed.", @"blah") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [{service}][I-COR000001] Configure blah failed. + * Calling GULLogDebug(kGULLoggerCore, @"I-COR000001", @"Configure succeed.") shows: + * yyyy-mm-dd hh:mm:ss.SSS sender[PID] [{service}][I-COR000001] Configure succeed. + */ +#define GUL_LOGGING_FUNCTION(level) \ + void GULLog##level(GULLoggerService service, BOOL force, NSString *messageCode, \ + NSString *message, ...) { \ + va_list args_ptr; \ + va_start(args_ptr, message); \ + GULLogBasic(GULLoggerLevel##level, service, force, messageCode, message, args_ptr); \ + va_end(args_ptr); \ + } + +GUL_LOGGING_FUNCTION(Error) +GUL_LOGGING_FUNCTION(Warning) +GUL_LOGGING_FUNCTION(Notice) +GUL_LOGGING_FUNCTION(Info) +GUL_LOGGING_FUNCTION(Debug) + +#undef GUL_MAKE_LOGGER + +#pragma mark - GULLoggerWrapper + +@implementation GULLoggerWrapper + ++ (void)logWithLevel:(GULLoggerLevel)level + withService:(GULLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args { + GULLogBasic(level, service, NO, messageCode, message, args); +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h new file mode 100644 index 0000000..ff42576 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Private/GULLogger.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * The services used in the logger. + */ +typedef NSString *const GULLoggerService; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Initialize GULLogger. + */ +extern void GULLoggerInitializeASL(void); + +/** + * Override log level to Debug. + */ +void GULLoggerForceDebug(void); + +/** + * Turn on logging to STDERR. + */ +extern void GULLoggerEnableSTDERR(void); + +/** + * Changes the default logging level of GULLoggerLevelNotice to a user-specified level. + * The default level cannot be set above GULLoggerLevelNotice if the app is running from App Store. + * (required) log level (one of the GULLoggerLevel enum values). + */ +extern void GULSetLoggerLevel(GULLoggerLevel loggerLevel); + +/** + * Checks if the specified logger level is loggable given the current settings. + * (required) log level (one of the GULLoggerLevel enum values). + */ +extern BOOL GULIsLoggableLevel(GULLoggerLevel loggerLevel); + +/** + * Register version to include in logs. + * (required) version + */ +extern void GULLoggerRegisterVersion(const char *version); + +/** + * Logs a message to the Xcode console and the device log. If running from AppStore, will + * not log any messages with a level higher than GULLoggerLevelNotice to avoid log spamming. + * (required) log level (one of the GULLoggerLevel enum values). + * (required) service name of type GULLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ +extern void GULLogBasic(GULLoggerLevel level, + GULLoggerService service, + BOOL forceLog, + NSString *messageCode, + NSString *message, +// On 64-bit simulators, va_list is not a pointer, so cannot be marked nullable +// See: http://stackoverflow.com/q/29095469 +#if __LP64__ && TARGET_OS_SIMULATOR || TARGET_OS_OSX + va_list args_ptr +#else + va_list _Nullable args_ptr +#endif +); + +/** + * The following functions accept the following parameters in order: + * (required) service name of type GULLoggerService. + * (required) message code starting from "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * See go/firebase-log-proposal for details. + * (required) message string which can be a format string. + * (optional) the list of arguments to substitute into the format string. + * Example usage: + * GULLogError(kGULLoggerCore, @"I-COR000001", @"Configuration of %@ failed.", app.name); + */ +extern void GULLogError(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogWarning(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogNotice(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogInfo(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); +extern void GULLogDebug(GULLoggerService service, + BOOL force, + NSString *messageCode, + NSString *message, + ...) NS_FORMAT_FUNCTION(4, 5); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +@interface GULLoggerWrapper : NSObject + +/** + * Objective-C wrapper for GULLogBasic to allow weak linking to GULLogger + * (required) log level (one of the GULLoggerLevel enum values). + * (required) service name of type GULLoggerService. + * (required) message code starting with "I-" which means iOS, followed by a capitalized + * three-character service identifier and a six digit integer message ID that is unique + * within the service. + * An example of the message code is @"I-COR000001". + * (required) message string which can be a format string. + * (optional) variable arguments list obtained from calling va_start, used when message is a format + * string. + */ + ++ (void)logWithLevel:(GULLoggerLevel)level + withService:(GULLoggerService)service + withCode:(NSString *)messageCode + withMessage:(NSString *)message + withArgs:(va_list)args; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h new file mode 100644 index 0000000..81ff212 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Logger/Public/GULLoggerLevel.h @@ -0,0 +1,35 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The log levels used by internal logging. + */ +typedef NS_ENUM(NSInteger, GULLoggerLevel) { + /** Error level, matches ASL_LEVEL_ERR. */ + GULLoggerLevelError = 3, + /** Warning level, matches ASL_LEVEL_WARNING. */ + GULLoggerLevelWarning = 4, + /** Notice level, matches ASL_LEVEL_NOTICE. */ + GULLoggerLevelNotice = 5, + /** Info level, matches ASL_LEVEL_INFO. */ + GULLoggerLevelInfo = 6, + /** Debug level, matches ASL_LEVEL_DEBUG. */ + GULLoggerLevelDebug = 7, + /** Minimum log level. */ + GULLoggerLevelMin = GULLoggerLevelError, + /** Maximum log level. */ + GULLoggerLevelMax = GULLoggerLevelDebug +} NS_SWIFT_NAME(GoogleLoggerLevel); diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m new file mode 100644 index 0000000..9839124 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/GULSwizzler.m @@ -0,0 +1,185 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Private/GULSwizzler.h" + +#import + +#import +#import "../Common/GULLoggerCodes.h" + +#ifdef GUL_UNSWIZZLING_ENABLED +#import +// We need a private method for an assert. +#import +#endif + +static GULLoggerService kGULLoggerSwizzler = @"[GoogleUtilites/MethodSwizzler]"; + +dispatch_queue_t GetGULSwizzlingQueue() { + static dispatch_queue_t queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + queue = dispatch_queue_create("com.google.GULSwizzler", DISPATCH_QUEUE_SERIAL); + }); + return queue; +} + +@implementation GULSwizzler + ++ (void)swizzleClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector + withBlock:(nullable id)block { + dispatch_sync(GetGULSwizzlingQueue(), ^{ + NSAssert(selector, @"The selector cannot be NULL"); + NSAssert(aClass, @"The class cannot be Nil"); + Class resolvedClass = aClass; + Method method = nil; + if (isClassSelector) { + method = class_getClassMethod(aClass, selector); + resolvedClass = object_getClass(aClass); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"You're attempting to swizzle a method that doesn't exist. (%@, %@)", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + IMP newImp = imp_implementationWithBlock(block); + +#ifdef GUL_UNSWIZZLING_ENABLED + IMP currentImp = class_getMethodImplementation(resolvedClass, selector); + [[GULSwizzlingCache sharedInstance] cacheCurrentIMP:currentImp + forNewIMP:newImp + forClass:resolvedClass + withSelector:selector]; +#endif + + const char *typeEncoding = method_getTypeEncoding(method); + __unused IMP originalImpOfClass = + class_replaceMethod(resolvedClass, selector, newImp, typeEncoding); + +#ifdef GUL_UNSWIZZLING_ENABLED + // If !originalImpOfClass, then the IMP came from a superclass. + if (originalImpOfClass) { + if (originalImpOfClass != + [[GULSwizzlingCache sharedInstance] originalIMPOfCurrentIMP:currentImp]) { + GULLogWarning(kGULLoggerSwizzler, NO, + [NSString stringWithFormat:@"I-SWZ%06ld", + (long)kGULSwizzlerMessageCodeMethodSwizzling000], + @"Swizzling class: %@ SEL:%@ after it has been previously been swizzled.", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + } + } +#endif + }); +} + ++ (void)unswizzleClass:(Class)aClass selector:(SEL)selector isClassSelector:(BOOL)isClassSelector { +#ifdef GUL_UNSWIZZLING_ENABLED + dispatch_sync(GetGULSwizzlingQueue(), ^{ + NSAssert(aClass != nil && selector != nil, @"You cannot unswizzle a nil class or selector."); + Method method = nil; + Class resolvedClass = aClass; + if (isClassSelector) { + resolvedClass = object_getClass(aClass); + method = class_getClassMethod(aClass, selector); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"Couldn't find the method you're unswizzling in the runtime."); + IMP originalImp = + [[GULSwizzlingCache sharedInstance] cachedIMPForClass:resolvedClass withSelector:selector]; + NSAssert(originalImp, @"This class/selector combination hasn't been swizzled"); + IMP currentImp = method_setImplementation(method, originalImp); + BOOL didRemoveBlock = imp_removeBlock(currentImp); + NSAssert(didRemoveBlock, @"Wasn't able to remove the block of a swizzled IMP."); + [[GULSwizzlingCache sharedInstance] clearCacheForSwizzledIMP:currentImp + selector:selector + aClass:resolvedClass]; + }); +#else + NSAssert(NO, @"Unswizzling is disabled."); +#endif +} + ++ (nullable IMP)originalImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector { +#ifdef GUL_UNSWIZZLING_ENABLED + __block IMP originalImp = nil; + dispatch_sync(GetGULSwizzlingQueue(), ^{ + Class resolvedClass = isClassSelector ? object_getClass(aClass) : aClass; + originalImp = + [[GULSwizzlingCache sharedInstance] cachedIMPForClass:resolvedClass withSelector:selector]; + NSAssert(originalImp, @"The IMP for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(resolvedClass), NSStringFromSelector(selector)); + }); + return originalImp; +#else + NSAssert(NO, @"Unswizzling is disabled and the original IMP is not cached."); + return nil; +#endif +} + ++ (nullable IMP)currentImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector { + NSAssert(selector, @"The selector cannot be NULL"); + NSAssert(aClass, @"The class cannot be Nil"); + if (selector == NULL || aClass == nil) { + return nil; + } + __block IMP currentIMP = nil; + dispatch_sync(GetGULSwizzlingQueue(), ^{ + Method method = nil; + if (isClassSelector) { + method = class_getClassMethod(aClass, selector); + } else { + method = class_getInstanceMethod(aClass, selector); + } + NSAssert(method, @"The Method for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(aClass), NSStringFromSelector(selector)); + if (method == nil) { + return; + } + currentIMP = method_getImplementation(method); + NSAssert(currentIMP, @"The IMP for this class/selector combo doesn't exist (%@, %@).", + NSStringFromClass(aClass), NSStringFromSelector(selector)); + }); + return currentIMP; +} + ++ (BOOL)selector:(SEL)selector existsInClass:(Class)aClass isClassSelector:(BOOL)isClassSelector { + Method method = isClassSelector ? class_getClassMethod(aClass, selector) + : class_getInstanceMethod(aClass, selector); + return method != nil; +} + ++ (NSArray *)ivarObjectsForObject:(id)object { + NSMutableArray *array = [NSMutableArray array]; + unsigned int count; + Ivar *vars = class_copyIvarList([object class], &count); + for (NSUInteger i = 0; i < count; i++) { + const char *typeEncoding = ivar_getTypeEncoding(vars[i]); + // Check to see if the ivar is an object. + if (strncmp(typeEncoding, "@", 1) == 0) { + id ivarObject = object_getIvar(object, vars[i]); + [array addObject:ivarObject]; + } + } + free(vars); + return array; +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h new file mode 100644 index 0000000..a33262a --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h @@ -0,0 +1,207 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * GULOriginalIMPConvenienceMacros.h + * + * This header contains convenience macros for invoking the original IMP of a swizzled method. + */ + +/** + * Invokes original IMP when the original selector takes no arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + */ +#define GUL_INVOKE_ORIGINAL_IMP0(__receivingObject, __swizzledSEL, __returnType, __originalIMP) \ + ((__returnType(*)(id, SEL))__originalIMP)(__receivingObject, __swizzledSEL) + +/** + * Invokes original IMP when the original selector takes 1 argument. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP1(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1)))__originalIMP)(__receivingObject, __swizzledSEL, \ + __arg1) + +/** + * Invokes original IMP when the original selector takes 2 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP2(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2) + +/** + * Invokes original IMP when the original selector takes 3 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP3(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), \ + __typeof__(__arg3)))__originalIMP)(__receivingObject, __swizzledSEL, __arg1, \ + __arg2, __arg3) + +/** + * Invokes original IMP when the original selector takes 4 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP4(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4)))__originalIMP)(__receivingObject, __swizzledSEL, __arg1, \ + __arg2, __arg3, __arg4) + +/** + * Invokes original IMP when the original selector takes 5 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP5(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5) + +/** + * Invokes original IMP when the original selector takes 6 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP6(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6) + +/** + * Invokes original IMP when the original selector takes 7 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP7(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7) + +/** + * Invokes original IMP when the original selector takes 8 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + * @param __arg8 The eighth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP8(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7), __typeof__(__arg8)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, \ + __arg8) + +/** + * Invokes original IMP when the original selector takes 9 arguments. + * + * @param __receivingObject The object on which the IMP is invoked. + * @param __swizzledSEL The selector used for swizzling. + * @param __returnType The return type of the original implementation. + * @param __originalIMP The original IMP. + * @param __arg1 The first argument. + * @param __arg2 The second argument. + * @param __arg3 The third argument. + * @param __arg4 The fourth argument. + * @param __arg5 The fifth argument. + * @param __arg6 The sixth argument. + * @param __arg7 The seventh argument. + * @param __arg8 The eighth argument. + * @param __arg9 The ninth argument. + */ +#define GUL_INVOKE_ORIGINAL_IMP9(__receivingObject, __swizzledSEL, __returnType, __originalIMP, \ + __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8, \ + __arg9) \ + ((__returnType(*)(id, SEL, __typeof__(__arg1), __typeof__(__arg2), __typeof__(__arg3), \ + __typeof__(__arg4), __typeof__(__arg5), __typeof__(__arg6), \ + __typeof__(__arg7), __typeof__(__arg8), __typeof__(__arg9)))__originalIMP)( \ + __receivingObject, __swizzledSEL, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, \ + __arg8, __arg9) diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h new file mode 100644 index 0000000..ab008ca --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h @@ -0,0 +1,91 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 + +/** This class handles the runtime manipulation necessary to instrument selectors. It stores the + * classes and selectors that have been swizzled, and runs all operations on its own queue. + */ +@interface GULSwizzler : NSObject + +/** Manipulates the Objective-C runtime to replace the original IMP with the supplied block. + * + * @param aClass The class to swizzle. + * @param selector The selector of the class to swizzle. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @param block The block that replaces the original IMP. + */ ++ (void)swizzleClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector + withBlock:(nullable id)block; + +/** Restores the original implementation. + * + * @param aClass The class to unswizzle. + * @param selector The selector to restore the original implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + */ ++ (void)unswizzleClass:(Class)aClass selector:(SEL)selector isClassSelector:(BOOL)isClassSelector; + +/** Returns the current IMP for the given class and selector. + * + * @param aClass The class to use. + * @param selector The selector to find the implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return The implementation of the selector in the runtime. + */ ++ (nullable IMP)currentImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector; + +/** Returns the original IMP for the given class and selector. + * + * @param aClass The class to use. + * @param selector The selector to find the implementation of. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return The implementation of the selector in the runtime before any consumer or GULSwizzler + * swizzled. + */ ++ (nullable IMP)originalImplementationForClass:(Class)aClass + selector:(SEL)selector + isClassSelector:(BOOL)isClassSelector; + +/** Checks the runtime to see if a selector exists on a class. If a property is declared as + * @dynamic, we have a reverse swizzling situation, where the implementation of a method exists + * only in concrete subclasses, and NOT in the superclass. We can detect that situation using + * this helper method. Similarly, we can detect situations where a class doesn't implement a + * protocol method. + * + * @param selector The selector to check for. + * @param aClass The class to check. + * @param isClassSelector A BOOL specifying whether the selector is a class or instance selector. + * @return YES if the method was found in this selector/class combination, NO otherwise. + */ ++ (BOOL)selector:(SEL)selector existsInClass:(Class)aClass isClassSelector:(BOOL)isClassSelector; + +/** Returns a list of all Objective-C (and not primitive) ivars contained by the given object. + * + * @param object The object whose ivars will be iterated. + * @return The list of ivar objects. + */ ++ (NSArray *)ivarObjectsForObject:(id)object; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h new file mode 100644 index 0000000..36f94a7 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.h @@ -0,0 +1,49 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +/// This is a copy of Google Toolbox for Mac library to avoid creating an extra framework. + +// NOTE: For 64bit, none of these apis handle input sizes >32bits, they will return nil when given +// such data. To handle data of that size you really should be streaming it rather then doing it all +// in memory. + +@interface NSData (GULGzip) + +/// Returns an data as the result of decompressing the payload of |data|.The data to decompress must +/// be a gzipped payloads. ++ (NSData *)gul_dataByInflatingGzippedData:(NSData *)data error:(NSError **)error; + +/// Returns an compressed data with the result of gzipping the payload of |data|. Uses the default +/// compression level. ++ (NSData *)gul_dataByGzippingData:(NSData *)data error:(NSError **)error; + +FOUNDATION_EXPORT NSString *const GULNSDataZlibErrorDomain; +FOUNDATION_EXPORT NSString *const GULNSDataZlibErrorKey; // NSNumber +FOUNDATION_EXPORT NSString *const GULNSDataZlibRemainingBytesKey; // NSNumber + +typedef NS_ENUM(NSInteger, GULNSDataZlibError) { + GULNSDataZlibErrorGreaterThan32BitsToCompress = 1024, + // An internal zlib error. + // GULNSDataZlibErrorKey will contain the error value. + // NSLocalizedDescriptionKey may contain an error string from zlib. + // Look in zlib.h for list of errors. + GULNSDataZlibErrorInternal, + // There was left over data in the buffer that was not used. + // GULNSDataZlibRemainingBytesKey will contain number of remaining bytes. + GULNSDataZlibErrorDataRemaining +}; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m new file mode 100644 index 0000000..cd3394a --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/NSData+zlib/GULNSData+zlib.m @@ -0,0 +1,207 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "GULNSData+zlib.h" + +#import + +#define kChunkSize 1024 +#define Z_DEFAULT_COMPRESSION (-1) + +NSString *const GULNSDataZlibErrorDomain = @"com.google.GULNSDataZlibErrorDomain"; +NSString *const GULNSDataZlibErrorKey = @"GULNSDataZlibErrorKey"; +NSString *const GULNSDataZlibRemainingBytesKey = @"GULNSDataZlibRemainingBytesKey"; + +@implementation NSData (GULGzip) + ++ (NSData *)gul_dataByInflatingGzippedData:(NSData *)data error:(NSError **)error { + const void *bytes = [data bytes]; + NSUInteger length = [data length]; + if (!bytes || !length) { + return nil; + } + +#if defined(__LP64__) && __LP64__ + // Don't support > 32bit length for 64 bit, see note in header. + if (length > UINT_MAX) { + return nil; + } +#endif + + z_stream strm; + bzero(&strm, sizeof(z_stream)); + + // Setup the input. + strm.avail_in = (unsigned int)length; + strm.next_in = (unsigned char *)bytes; + + int windowBits = 15; // 15 to enable any window size + windowBits += 32; // and +32 to enable zlib or gzip header detection. + + int retCode; + if ((retCode = inflateInit2(&strm, windowBits)) != Z_OK) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + return nil; + } + + // Hint the size at 4x the input size. + NSMutableData *result = [NSMutableData dataWithCapacity:(length * 4)]; + unsigned char output[kChunkSize]; + + // Loop to collect the data. + do { + // Update what we're passing in. + strm.avail_out = kChunkSize; + strm.next_out = output; + retCode = inflate(&strm, Z_NO_FLUSH); + if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { + if (error) { + NSMutableDictionary *userInfo = + [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + if (strm.msg) { + NSString *message = [NSString stringWithUTF8String:strm.msg]; + if (message) { + [userInfo setObject:message forKey:NSLocalizedDescriptionKey]; + } + } + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + inflateEnd(&strm); + return nil; + } + // Collect what we got. + unsigned gotBack = kChunkSize - strm.avail_out; + if (gotBack > 0) { + [result appendBytes:output length:gotBack]; + } + + } while (retCode == Z_OK); + + // Make sure there wasn't more data tacked onto the end of a valid compressed stream. + if (strm.avail_in != 0) { + if (error) { + NSDictionary *userInfo = + [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:strm.avail_in] + forKey:GULNSDataZlibRemainingBytesKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorDataRemaining + userInfo:userInfo]; + } + result = nil; + } + // The only way out of the loop was by hitting the end of the stream. + NSAssert(retCode == Z_STREAM_END, + @"Thought we finished inflate w/o getting a result of stream end, code %d", retCode); + + // Clean up. + inflateEnd(&strm); + + return result; +} + ++ (NSData *)gul_dataByGzippingData:(NSData *)data error:(NSError **)error { + const void *bytes = [data bytes]; + NSUInteger length = [data length]; + + int level = Z_DEFAULT_COMPRESSION; + if (!bytes || !length) { + return nil; + } + +#if defined(__LP64__) && __LP64__ + // Don't support > 32bit length for 64 bit, see note in header. + if (length > UINT_MAX) { + if (error) { + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorGreaterThan32BitsToCompress + userInfo:nil]; + } + return nil; + } +#endif + + z_stream strm; + bzero(&strm, sizeof(z_stream)); + + int memLevel = 8; // Default. + int windowBits = 15 + 16; // Enable gzip header instead of zlib header. + + int retCode; + if ((retCode = deflateInit2(&strm, level, Z_DEFLATED, windowBits, memLevel, + Z_DEFAULT_STRATEGY)) != Z_OK) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + return nil; + } + + // Hint the size at 1/4 the input size. + NSMutableData *result = [NSMutableData dataWithCapacity:(length / 4)]; + unsigned char output[kChunkSize]; + + // Setup the input. + strm.avail_in = (unsigned int)length; + strm.next_in = (unsigned char *)bytes; + + // Collect the data. + do { + // update what we're passing in + strm.avail_out = kChunkSize; + strm.next_out = output; + retCode = deflate(&strm, Z_FINISH); + if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { + if (error) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] + forKey:GULNSDataZlibErrorKey]; + *error = [NSError errorWithDomain:GULNSDataZlibErrorDomain + code:GULNSDataZlibErrorInternal + userInfo:userInfo]; + } + deflateEnd(&strm); + return nil; + } + // Collect what we got. + unsigned gotBack = kChunkSize - strm.avail_out; + if (gotBack > 0) { + [result appendBytes:output length:gotBack]; + } + + } while (retCode == Z_OK); + + // If the loop exits, it used all input and the stream ended. + NSAssert(strm.avail_in == 0, + @"Should have finished deflating without using all input, %u bytes left", strm.avail_in); + NSAssert(retCode == Z_STREAM_END, + @"thought we finished deflate w/o getting a result of stream end, code %d", retCode); + + // Clean up. + deflateEnd(&strm); + + return result; +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m new file mode 100644 index 0000000..d281eb4 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULMutableDictionary.m @@ -0,0 +1,97 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULMutableDictionary.h" + +@implementation GULMutableDictionary { + /// The mutable dictionary. + NSMutableDictionary *_objects; + + /// Serial synchronization queue. All reads should use dispatch_sync, while writes use + /// dispatch_async. + dispatch_queue_t _queue; +} + +- (instancetype)init { + self = [super init]; + + if (self) { + _objects = [[NSMutableDictionary alloc] init]; + _queue = dispatch_queue_create("GULMutableDictionary", DISPATCH_QUEUE_SERIAL); + } + + return self; +} + +- (NSString *)description { + __block NSString *description; + dispatch_sync(_queue, ^{ + description = self->_objects.description; + }); + return description; +} + +- (id)objectForKey:(id)key { + __block id object; + dispatch_sync(_queue, ^{ + object = self->_objects[key]; + }); + return object; +} + +- (void)setObject:(id)object forKey:(id)key { + dispatch_async(_queue, ^{ + self->_objects[key] = object; + }); +} + +- (void)removeObjectForKey:(id)key { + dispatch_async(_queue, ^{ + [self->_objects removeObjectForKey:key]; + }); +} + +- (void)removeAllObjects { + dispatch_async(_queue, ^{ + [self->_objects removeAllObjects]; + }); +} + +- (NSUInteger)count { + __block NSUInteger count; + dispatch_sync(_queue, ^{ + count = self->_objects.count; + }); + return count; +} + +- (id)objectForKeyedSubscript:(id)key { + // The method this calls is already synchronized. + return [self objectForKey:key]; +} + +- (void)setObject:(id)obj forKeyedSubscript:(id)key { + // The method this calls is already synchronized. + [self setObject:obj forKey:key]; +} + +- (NSDictionary *)dictionary { + __block NSDictionary *dictionary; + dispatch_sync(_queue, ^{ + dictionary = [self->_objects copy]; + }); + return dictionary; +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m new file mode 100644 index 0000000..233500b --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetwork.m @@ -0,0 +1,388 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULNetwork.h" +#import "Private/GULNetworkMessageCode.h" + +#import +#import +#import +#import "Private/GULMutableDictionary.h" +#import "Private/GULNetworkConstants.h" + +/// Constant string for request header Content-Encoding. +static NSString *const kGULNetworkContentCompressionKey = @"Content-Encoding"; + +/// Constant string for request header Content-Encoding value. +static NSString *const kGULNetworkContentCompressionValue = @"gzip"; + +/// Constant string for request header Content-Length. +static NSString *const kGULNetworkContentLengthKey = @"Content-Length"; + +/// Constant string for request header Content-Type. +static NSString *const kGULNetworkContentTypeKey = @"Content-Type"; + +/// Constant string for request header Content-Type value. +static NSString *const kGULNetworkContentTypeValue = @"application/x-www-form-urlencoded"; + +/// Constant string for GET request method. +static NSString *const kGULNetworkGETRequestMethod = @"GET"; + +/// Constant string for POST request method. +static NSString *const kGULNetworkPOSTRequestMethod = @"POST"; + +/// Default constant string as a prefix for network logger. +static NSString *const kGULNetworkLogTag = @"Google/Utilities/Network"; + +@interface GULNetwork () +@end + +@implementation GULNetwork { + /// Network reachability. + GULReachabilityChecker *_reachability; + + /// The dictionary of requests by session IDs { NSString : id }. + GULMutableDictionary *_requests; +} + +- (instancetype)init { + return [self initWithReachabilityHost:kGULNetworkReachabilityHost]; +} + +- (instancetype)initWithReachabilityHost:(NSString *)reachabilityHost { + self = [super init]; + if (self) { + // Setup reachability. + _reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self + withHost:reachabilityHost]; + if (![_reachability start]) { + return nil; + } + + _requests = [[GULMutableDictionary alloc] init]; + _timeoutInterval = kGULNetworkTimeOutInterval; + } + return self; +} + +- (void)dealloc { + _reachability.reachabilityDelegate = nil; + [_reachability stop]; +} + +#pragma mark - External Methods + ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler { + [GULNetworkURLSession handleEventsForBackgroundURLSessionID:sessionID + completionHandler:completionHandler]; +} + +- (NSString *)postURL:(NSURL *)url + payload:(NSData *)payload + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler { + if (!url.absoluteString.length) { + [self handleErrorWithCode:GULErrorCodeNetworkInvalidURL queue:queue withHandler:handler]; + return nil; + } + + NSTimeInterval timeOutInterval = _timeoutInterval ?: kGULNetworkTimeOutInterval; + + NSMutableURLRequest *request = + [[NSMutableURLRequest alloc] initWithURL:url + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:timeOutInterval]; + + if (!request) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + NSError *compressError = nil; + NSData *compressedData = [NSData gul_dataByGzippingData:payload error:&compressError]; + if (!compressedData || compressError) { + if (compressError || payload.length > 0) { + // If the payload is not empty but it fails to compress the payload, something has been wrong. + [self handleErrorWithCode:GULErrorCodeNetworkPayloadCompression + queue:queue + withHandler:handler]; + return nil; + } + compressedData = [[NSData alloc] init]; + } + + NSString *postLength = @(compressedData.length).stringValue; + + // Set up the request with the compressed data. + [request setValue:postLength forHTTPHeaderField:kGULNetworkContentLengthKey]; + request.HTTPBody = compressedData; + request.HTTPMethod = kGULNetworkPOSTRequestMethod; + [request setValue:kGULNetworkContentTypeValue forHTTPHeaderField:kGULNetworkContentTypeKey]; + [request setValue:kGULNetworkContentCompressionValue + forHTTPHeaderField:kGULNetworkContentCompressionKey]; + + GULNetworkURLSession *fetcher = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:self]; + fetcher.backgroundNetworkEnabled = usingBackgroundSession; + + __weak GULNetwork *weakSelf = self; + NSString *requestID = [fetcher + sessionIDFromAsyncPOSTRequest:request + completionHandler:^(NSHTTPURLResponse *response, NSData *data, + NSString *sessionID, NSError *error) { + GULNetwork *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + if (sessionID.length) { + [strongSelf->_requests removeObjectForKey:sessionID]; + } + if (handler) { + handler(response, data, error); + } + }); + }]; + if (!requestID) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + [self GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeNetwork000 + message:@"Uploading data. Host" + context:url]; + _requests[requestID] = fetcher; + return requestID; +} + +- (NSString *)getURL:(NSURL *)url + headers:(NSDictionary *)headers + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler { + if (!url.absoluteString.length) { + [self handleErrorWithCode:GULErrorCodeNetworkInvalidURL queue:queue withHandler:handler]; + return nil; + } + + NSTimeInterval timeOutInterval = _timeoutInterval ?: kGULNetworkTimeOutInterval; + NSMutableURLRequest *request = + [[NSMutableURLRequest alloc] initWithURL:url + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:timeOutInterval]; + + if (!request) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + request.HTTPMethod = kGULNetworkGETRequestMethod; + request.allHTTPHeaderFields = headers; + + GULNetworkURLSession *fetcher = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:self]; + fetcher.backgroundNetworkEnabled = usingBackgroundSession; + + __weak GULNetwork *weakSelf = self; + NSString *requestID = [fetcher + sessionIDFromAsyncGETRequest:request + completionHandler:^(NSHTTPURLResponse *response, NSData *data, NSString *sessionID, + NSError *error) { + GULNetwork *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + if (sessionID.length) { + [strongSelf->_requests removeObjectForKey:sessionID]; + } + if (handler) { + handler(response, data, error); + } + }); + }]; + + if (!requestID) { + [self handleErrorWithCode:GULErrorCodeNetworkSessionTaskCreation + queue:queue + withHandler:handler]; + return nil; + } + + [self GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeNetwork001 + message:@"Downloading data. Host" + context:url]; + _requests[requestID] = fetcher; + return requestID; +} + +- (BOOL)hasUploadInProgress { + return _requests.count > 0; +} + +#pragma mark - Network Reachability + +/// Tells reachability delegate to call reachabilityDidChangeToStatus: to notify the network +/// reachability has changed. +- (void)reachability:(GULReachabilityChecker *)reachability + statusChanged:(GULReachabilityStatus)status { + _networkConnected = (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi); + [_reachabilityDelegate reachabilityDidChange]; +} + +#pragma mark - Network logger delegate + +- (void)setLoggerDelegate:(id)loggerDelegate { + // Explicitly check whether the delegate responds to the methods because conformsToProtocol does + // not work correctly even though the delegate does respond to the methods. + if (!loggerDelegate || + ![loggerDelegate + respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:contexts:)] || + ![loggerDelegate + respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:context:)] || + ! + [loggerDelegate respondsToSelector:@selector(GULNetwork_logWithLevel:messageCode:message:)]) { + GULLogError(kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULNetworkMessageCodeNetwork002], + @"Cannot set the network logger delegate: delegate does not conform to the network " + "logger protocol."); + return; + } + _loggerDelegate = loggerDelegate; +} + +#pragma mark - Private methods + +/// Handles network error and calls completion handler with the error. +- (void)handleErrorWithCode:(NSInteger)code + queue:(dispatch_queue_t)queue + withHandler:(GULNetworkCompletionHandler)handler { + NSDictionary *userInfo = @{kGULNetworkErrorContext : @"Failed to create network request"}; + NSError *error = + [[NSError alloc] initWithDomain:kGULNetworkErrorDomain code:code userInfo:userInfo]; + [self GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeNetwork002 + message:@"Failed to create network request. Code, error" + contexts:@[ @(code), error ]]; + if (handler) { + dispatch_queue_t queueToDispatch = queue ? queue : dispatch_get_main_queue(); + dispatch_async(queueToDispatch, ^{ + handler(nil, nil, error); + }); + } +} + +#pragma mark - Network logger + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + contexts:(NSArray *)contexts { + // Let the delegate log the message if there is a valid logger delegate. Otherwise, just log + // errors/warnings/info messages to the console log. + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel + messageCode:messageCode + message:message + contexts:contexts]; + return; + } + if (_isDebugModeEnabled || logLevel == kGULNetworkLogLevelError || + logLevel == kGULNetworkLogLevelWarning || logLevel == kGULNetworkLogLevelInfo) { + NSString *formattedMessage = GULStringWithLogMessage(message, logLevel, contexts); + NSLog(@"%@", formattedMessage); + GULLogBasic((GULLoggerLevel)logLevel, kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)messageCode], formattedMessage, + NULL); + } +} + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + context:(id)context { + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel + messageCode:messageCode + message:message + context:context]; + return; + } + NSArray *contexts = context ? @[ context ] : @[]; + [self GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message contexts:contexts]; +} + +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message { + if (_loggerDelegate) { + [_loggerDelegate GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message]; + return; + } + [self GULNetwork_logWithLevel:logLevel messageCode:messageCode message:message contexts:@[]]; +} + +/// Returns a string for the given log level (e.g. kGULNetworkLogLevelError -> @"ERROR"). +static NSString *GULLogLevelDescriptionFromLogLevel(GULNetworkLogLevel logLevel) { + static NSDictionary *levelNames = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + levelNames = @{ + @(kGULNetworkLogLevelError) : @"ERROR", + @(kGULNetworkLogLevelWarning) : @"WARNING", + @(kGULNetworkLogLevelInfo) : @"INFO", + @(kGULNetworkLogLevelDebug) : @"DEBUG" + }; + }); + return levelNames[@(logLevel)]; +} + +/// Returns a formatted string to be used for console logging. +static NSString *GULStringWithLogMessage(NSString *message, + GULNetworkLogLevel logLevel, + NSArray *contexts) { + if (!message) { + message = @"(Message was nil)"; + } else if (!message.length) { + message = @"(Message was empty)"; + } + NSMutableString *result = [[NSMutableString alloc] + initWithFormat:@"<%@/%@> %@", kGULNetworkLogTag, GULLogLevelDescriptionFromLogLevel(logLevel), + message]; + + if (!contexts.count) { + return result; + } + + NSMutableArray *formattedContexts = [[NSMutableArray alloc] init]; + for (id item in contexts) { + [formattedContexts addObject:(item != [NSNull null] ? item : @"(nil)")]; + } + + [result appendString:@": "]; + [result appendString:[formattedContexts componentsJoinedByString:@", "]]; + return result; +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m new file mode 100644 index 0000000..90bd03d --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkConstants.m @@ -0,0 +1,40 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULNetworkConstants.h" + +#import + +NSString *const kGULNetworkBackgroundSessionConfigIDPrefix = @"com.gul.network.background-upload"; +NSString *const kGULNetworkApplicationSupportSubdirectory = @"GUL/Network"; +NSString *const kGULNetworkTempDirectoryName = @"GULNetworkTemporaryDirectory"; +const NSTimeInterval kGULNetworkTempFolderExpireTime = 60 * 60; // 1 hour +const NSTimeInterval kGULNetworkTimeOutInterval = 60; // 1 minute. +NSString *const kGULNetworkReachabilityHost = @"app-measurement.com"; +NSString *const kGULNetworkErrorContext = @"Context"; + +const int kGULNetworkHTTPStatusOK = 200; +const int kGULNetworkHTTPStatusNoContent = 204; +const int kGULNetworkHTTPStatusCodeMultipleChoices = 300; +const int kGULNetworkHTTPStatusCodeMovedPermanently = 301; +const int kGULNetworkHTTPStatusCodeFound = 302; +const int kGULNetworkHTTPStatusCodeNotModified = 304; +const int kGULNetworkHTTPStatusCodeMovedTemporarily = 307; +const int kGULNetworkHTTPStatusCodeNotFound = 404; +const int kGULNetworkHTTPStatusCodeCannotAcceptTraffic = 429; +const int kGULNetworkHTTPStatusCodeUnavailable = 503; + +NSString *const kGULNetworkErrorDomain = @"com.gul.network.ErrorDomain"; + +GULLoggerService kGULLoggerNetwork = @"[GULNetwork]"; diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m new file mode 100644 index 0000000..3f0ac76 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/GULNetworkURLSession.m @@ -0,0 +1,740 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +#import "Private/GULNetworkURLSession.h" + +#import +#import "Private/GULMutableDictionary.h" +#import "Private/GULNetworkConstants.h" +#import "Private/GULNetworkMessageCode.h" + +@interface GULNetworkURLSession () +@end + +@implementation GULNetworkURLSession { + /// The handler to be called when the request completes or error has occurs. + GULNetworkURLSessionCompletionHandler _completionHandler; + + /// Session ID generated randomly with a fixed prefix. + NSString *_sessionID; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + /// The session configuration. NSURLSessionConfiguration' is only available on iOS 7.0 or newer. + NSURLSessionConfiguration *_sessionConfig; +#pragma clang diagnostic pop + + /// The path to the directory where all temporary files are stored before uploading. + NSURL *_networkDirectoryURL; + + /// The downloaded data from fetching. + NSData *_downloadedData; + + /// The path to the temporary file which stores the uploading data. + NSURL *_uploadingFileURL; + + /// The current request. + NSURLRequest *_request; + + /// The current NSURLSession. + NSURLSession *__weak _Nullable _URLSession; +} + +#pragma mark - Init + +- (instancetype)initWithNetworkLoggerDelegate:(id)networkLoggerDelegate { + self = [super init]; + if (self) { + // Create URL to the directory where all temporary files to upload have to be stored. + NSArray *paths = + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSString *applicationSupportDirectory = paths.firstObject; + NSArray *tempPathComponents = @[ + applicationSupportDirectory, kGULNetworkApplicationSupportSubdirectory, + kGULNetworkTempDirectoryName + ]; + _networkDirectoryURL = [NSURL fileURLWithPathComponents:tempPathComponents]; + _sessionID = [NSString stringWithFormat:@"%@-%@", kGULNetworkBackgroundSessionConfigIDPrefix, + [[NSUUID UUID] UUIDString]]; + _loggerDelegate = networkLoggerDelegate; + } + return self; +} + +#pragma mark - External Methods + +#pragma mark - To be called from AppDelegate + ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler: + (GULNetworkSystemCompletionHandler)systemCompletionHandler { + // The session may not be Analytics background. Ignore those that do not have the prefix. + if (![sessionID hasPrefix:kGULNetworkBackgroundSessionConfigIDPrefix]) { + return; + } + GULNetworkURLSession *fetcher = [self fetcherWithSessionIdentifier:sessionID]; + if (fetcher != nil) { + [fetcher addSystemCompletionHandler:systemCompletionHandler forSession:sessionID]; + } else { + GULLogError(kGULLoggerNetwork, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULNetworkMessageCodeNetwork003], + @"Failed to retrieve background session with ID %@ after app is relaunched.", + sessionID); + } +} + +#pragma mark - External Methods + +/// Sends an async POST request using NSURLSession for iOS >= 7.0, and returns an ID of the +/// connection. +- (nullable NSString *)sessionIDFromAsyncPOSTRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler + API_AVAILABLE(ios(7.0)) { + // NSURLSessionUploadTask does not work with NSData in the background. + // To avoid this issue, write the data to a temporary file to upload it. + // Make a temporary file with the data subset. + _uploadingFileURL = [self temporaryFilePathWithSessionID:_sessionID]; + NSError *writeError; + NSURLSessionUploadTask *postRequestTask; + NSURLSession *session; + BOOL didWriteFile = NO; + + // Clean up the entire temp folder to avoid temp files that remain in case the previous session + // crashed and did not clean up. + [self maybeRemoveTempFilesAtURL:_networkDirectoryURL + expiringTime:kGULNetworkTempFolderExpireTime]; + + // If there is no background network enabled, no need to write to file. This will allow default + // network session which runs on the foreground. + if (_backgroundNetworkEnabled && [self ensureTemporaryDirectoryExists]) { + didWriteFile = [request.HTTPBody writeToFile:_uploadingFileURL.path + options:NSDataWritingAtomic + error:&writeError]; + + if (writeError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession000 + message:@"Failed to write request data to file" + context:writeError]; + } + } + + if (didWriteFile) { + // Exclude this file from backing up to iTunes. There are conflicting reports that excluding + // directory from backing up does not exclude files of that directory from backing up. + [self excludeFromBackupForURL:_uploadingFileURL]; + + _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID]; + [self populateSessionConfig:_sessionConfig withRequest:request]; + session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + postRequestTask = [session uploadTaskWithRequest:request fromFile:_uploadingFileURL]; + } else { + // If we cannot write to file, just send it in the foreground. + _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + [self populateSessionConfig:_sessionConfig withRequest:request]; + session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + postRequestTask = [session uploadTaskWithRequest:request fromData:request.HTTPBody]; + } + + if (!session || !postRequestTask) { + NSError *error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkRequestCreation + userInfo:@{kGULNetworkErrorContext : @"Cannot create network session"}]; + [self callCompletionHandler:handler withResponse:nil data:nil error:error]; + return nil; + } + + _URLSession = session; + + // Save the session into memory. + [[self class] setSessionInFetcherMap:self forSessionID:_sessionID]; + + _request = [request copy]; + + // Store completion handler because background session does not accept handler block but custom + // delegate. + _completionHandler = [handler copy]; + [postRequestTask resume]; + + return _sessionID; +} + +/// Sends an async GET request using NSURLSession for iOS >= 7.0, and returns an ID of the session. +- (nullable NSString *)sessionIDFromAsyncGETRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler + API_AVAILABLE(ios(7.0)) { + if (_backgroundNetworkEnabled) { + _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID]; + } else { + _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + [self populateSessionConfig:_sessionConfig withRequest:request]; + + // Do not cache the GET request. + _sessionConfig.URLCache = nil; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:_sessionConfig + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request]; + + if (!session || !downloadTask) { + NSError *error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkRequestCreation + userInfo:@{kGULNetworkErrorContext : @"Cannot create network session"}]; + [self callCompletionHandler:handler withResponse:nil data:nil error:error]; + return nil; + } + + _URLSession = session; + + // Save the session into memory. + [[self class] setSessionInFetcherMap:self forSessionID:_sessionID]; + + _request = [request copy]; + + _completionHandler = [handler copy]; + [downloadTask resume]; + + return _sessionID; +} + +#pragma mark - NSURLSessionTaskDelegate + +/// Called by the NSURLSession once the download task is completed. The file is saved in the +/// provided URL so we need to read the data and store into _downloadedData. Once the session is +/// completed, URLSession:task:didCompleteWithError will be called and the completion handler will +/// be called with the downloaded data. +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)task + didFinishDownloadingToURL:(NSURL *)url API_AVAILABLE(ios(7.0)) { + if (!url.path) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession001 + message:@"Unable to read downloaded data from empty temp path"]; + _downloadedData = nil; + return; + } + + NSError *error; + _downloadedData = [NSData dataWithContentsOfFile:url.path options:0 error:&error]; + + if (error) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession002 + message:@"Cannot read the content of downloaded data" + context:error]; + _downloadedData = nil; + } +} + +#if TARGET_OS_IOS || TARGET_OS_TV +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session + API_AVAILABLE(ios(7.0)) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession003 + message:@"Background session finished" + context:session.configuration.identifier]; + [self callSystemCompletionHandler:session.configuration.identifier]; +} +#endif + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didCompleteWithError:(NSError *)error API_AVAILABLE(ios(7.0)) { + // Avoid any chance of recursive behavior leading to it being used repeatedly. + GULNetworkURLSessionCompletionHandler handler = _completionHandler; + _completionHandler = nil; + + if (task.response) { + // The following assertion should always be true for HTTP requests, see https://goo.gl/gVLxT7. + NSAssert([task.response isKindOfClass:[NSHTTPURLResponse class]], @"URL response must be HTTP"); + + // The server responded so ignore the error created by the system. + error = nil; + } else if (!error) { + error = [[NSError alloc] + initWithDomain:kGULNetworkErrorDomain + code:GULErrorCodeNetworkInvalidResponse + userInfo:@{kGULNetworkErrorContext : @"Network Error: Empty network response"}]; + } + + [self callCompletionHandler:handler + withResponse:(NSHTTPURLResponse *)task.response + data:_downloadedData + error:error]; + + // Remove the temp file to avoid trashing devices with lots of temp files. + [self removeTempItemAtURL:_uploadingFileURL]; + + // Try to clean up stale files again. + [self maybeRemoveTempFilesAtURL:_networkDirectoryURL + expiringTime:kGULNetworkTempFolderExpireTime]; + + // This is called without checking the sessionID here since non-background sessions + // won't have an ID. + [session finishTasksAndInvalidate]; + + // Explicitly remove the session so it won't be reused. The weak map table should + // remove the session on deallocation, but dealloc may not happen immediately after + // calling `finishTasksAndInvalidate`. + NSString *sessionID = session.configuration.identifier; + [[self class] setSessionInFetcherMap:nil forSessionID:sessionID]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential *credential))completionHandler + API_AVAILABLE(ios(7.0)) { + // The handling is modeled after GTMSessionFetcher. + if ([challenge.protectionSpace.authenticationMethod + isEqualToString:NSURLAuthenticationMethodServerTrust]) { + SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; + if (serverTrust == NULL) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession004 + message:@"Received empty server trust for host. Host" + context:_request.URL]; + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + return; + } + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + if (!credential) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession005 + message:@"Unable to verify server identity. Host" + context:_request.URL]; + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + return; + } + + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession006 + message:@"Received SSL challenge for host. Host" + context:_request.URL]; + + void (^callback)(BOOL) = ^(BOOL allow) { + if (allow) { + completionHandler(NSURLSessionAuthChallengeUseCredential, credential); + } else { + [self->_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession007 + message:@"Cancelling authentication challenge for host. Host" + context:self->_request.URL]; + completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + }; + + // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7. + CFRetain(serverTrust); + + // Evaluate the certificate chain. + // + // The delegate queue may be the main thread. Trust evaluation could cause some + // blocking network activity, so we must evaluate async, as documented at + // https://developer.apple.com/library/ios/technotes/tn2232/ + dispatch_queue_t evaluateBackgroundQueue = + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_async(evaluateBackgroundQueue, ^{ + SecTrustResultType trustEval = kSecTrustResultInvalid; + BOOL shouldAllow; + OSStatus trustError; + + @synchronized([GULNetworkURLSession class]) { + trustError = SecTrustEvaluate(serverTrust, &trustEval); + } + + if (trustError != errSecSuccess) { + [self->_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession008 + message:@"Cannot evaluate server trust. Error, host" + contexts:@[ @(trustError), self->_request.URL ]]; + shouldAllow = NO; + } else { + // Having a trust level "unspecified" by the user is the usual result, described at + // https://developer.apple.com/library/mac/qa/qa1360 + shouldAllow = + (trustEval == kSecTrustResultUnspecified || trustEval == kSecTrustResultProceed); + } + + // Call the call back with the permission. + callback(shouldAllow); + + CFRelease(serverTrust); + }); + return; + } + + // Default handling for other Auth Challenges. + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); +} + +#pragma mark - Internal Methods + +/// Stores system completion handler with session ID as key. +- (void)addSystemCompletionHandler:(GULNetworkSystemCompletionHandler)handler + forSession:(NSString *)identifier { + if (!handler) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession009 + message:@"Cannot store nil system completion handler in network"]; + return; + } + + if (!identifier.length) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession010 + message: + @"Cannot store system completion handler with empty network " + "session identifier"]; + return; + } + + GULMutableDictionary *systemCompletionHandlers = + [[self class] sessionIDToSystemCompletionHandlerDictionary]; + if (systemCompletionHandlers[identifier]) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession011 + message:@"Got multiple system handlers for a single session ID" + context:identifier]; + } + + systemCompletionHandlers[identifier] = handler; +} + +/// Calls the system provided completion handler with the session ID stored in the dictionary. +/// The handler will be removed from the dictionary after being called. +- (void)callSystemCompletionHandler:(NSString *)identifier { + GULMutableDictionary *systemCompletionHandlers = + [[self class] sessionIDToSystemCompletionHandlerDictionary]; + GULNetworkSystemCompletionHandler handler = [systemCompletionHandlers objectForKey:identifier]; + + if (handler) { + [systemCompletionHandlers removeObjectForKey:identifier]; + + dispatch_async(dispatch_get_main_queue(), ^{ + handler(); + }); + } +} + +/// Sets or updates the session ID of this session. +- (void)setSessionID:(NSString *)sessionID { + _sessionID = [sessionID copy]; +} + +/// Creates a background session configuration with the session ID using the supported method. +- (NSURLSessionConfiguration *)backgroundSessionConfigWithSessionID:(NSString *)sessionID + API_AVAILABLE(ios(7.0)) { +#if (TARGET_OS_OSX && defined(MAC_OS_X_VERSION_10_10) && \ + MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) || \ + TARGET_OS_TV || \ + (TARGET_OS_IOS && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) + + // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name. + return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID]; + +#elif (TARGET_OS_OSX && defined(MAC_OS_X_VERSION_10_10) && \ + MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) || \ + (TARGET_OS_IOS && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0) + + // Do a runtime check to avoid a deprecation warning about using + // +backgroundSessionConfiguration: on iOS 8. + if ([NSURLSessionConfiguration + respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) { + // Running on iOS 8+/OS X 10.10+. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID]; +#pragma clang diagnostic pop + } else { + // Running on iOS 7/OS X 10.9. + return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID]; + } + +#else + // Building with an SDK earlier than iOS 8/OS X 10.10. + return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID]; +#endif +} + +- (void)maybeRemoveTempFilesAtURL:(NSURL *)folderURL expiringTime:(NSTimeInterval)staleTime { + if (!folderURL.absoluteString.length) { + return; + } + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + NSArray *properties = @[ NSURLCreationDateKey ]; + NSArray *directoryContent = + [fileManager contentsOfDirectoryAtURL:folderURL + includingPropertiesForKeys:properties + options:NSDirectoryEnumerationSkipsSubdirectoryDescendants + error:&error]; + if (error && error.code != NSFileReadNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelDebug + messageCode:kGULNetworkMessageCodeURLSession012 + message:@"Cannot get files from the temporary network folder. Error" + context:error]; + return; + } + + if (!directoryContent.count) { + return; + } + + NSTimeInterval now = [NSDate date].timeIntervalSince1970; + for (NSURL *tempFile in directoryContent) { + NSDate *creationDate; + BOOL getCreationDate = + [tempFile getResourceValue:&creationDate forKey:NSURLCreationDateKey error:NULL]; + if (!getCreationDate) { + continue; + } + NSTimeInterval creationTimeInterval = creationDate.timeIntervalSince1970; + if (fabs(now - creationTimeInterval) > staleTime) { + [self removeTempItemAtURL:tempFile]; + } + } +} + +/// Removes the temporary file written to disk for sending the request. It has to be cleaned up +/// after the session is done. +- (void)removeTempItemAtURL:(NSURL *)fileURL { + if (!fileURL.absoluteString.length) { + return; + } + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + if (![fileManager removeItemAtURL:fileURL error:&error] && error.code != NSFileNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession013 + message:@"Failed to remove temporary uploading data file. Error" + context:error.localizedDescription]; + } +} + +/// Gets the fetcher with the session ID. ++ (instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier { + GULNetworkURLSession *session = [self sessionFromFetcherMapForSessionID:sessionIdentifier]; + if (!session && [sessionIdentifier hasPrefix:kGULNetworkBackgroundSessionConfigIDPrefix]) { + session = [[GULNetworkURLSession alloc] initWithNetworkLoggerDelegate:nil]; + [session setSessionID:sessionIdentifier]; + [self setSessionInFetcherMap:session forSessionID:sessionIdentifier]; + } + return session; +} + +/// Returns a map of the fetcher by session ID. Creates a map if it is not created. +/// When reading and writing from/to the session map, don't use this method directly. +/// To avoid thread safety issues, use one of the helper methods at the bottom of the +/// file: setSessionInFetcherMap:forSessionID:, sessionFromFetcherMapForSessionID: ++ (NSMapTable *)sessionIDToFetcherMap { + static NSMapTable *sessionIDToFetcherMap; + + static dispatch_once_t sessionMapOnceToken; + dispatch_once(&sessionMapOnceToken, ^{ + sessionIDToFetcherMap = [NSMapTable strongToWeakObjectsMapTable]; + }); + return sessionIDToFetcherMap; +} + ++ (NSLock *)sessionIDToFetcherMapReadWriteLock { + static NSLock *lock; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + lock = [[NSLock alloc] init]; + }); + return lock; +} + +/// Returns a map of system provided completion handler by session ID. Creates a map if it is not +/// created. ++ (GULMutableDictionary *)sessionIDToSystemCompletionHandlerDictionary { + static GULMutableDictionary *systemCompletionHandlers; + + static dispatch_once_t systemCompletionHandlerOnceToken; + dispatch_once(&systemCompletionHandlerOnceToken, ^{ + systemCompletionHandlers = [[GULMutableDictionary alloc] init]; + }); + return systemCompletionHandlers; +} + +- (NSURL *)temporaryFilePathWithSessionID:(NSString *)sessionID { + NSString *tempName = [NSString stringWithFormat:@"GULUpload_temp_%@", sessionID]; + return [_networkDirectoryURL URLByAppendingPathComponent:tempName]; +} + +/// Makes sure that the directory to store temp files exists. If not, tries to create it and returns +/// YES. If there is anything wrong, returns NO. +- (BOOL)ensureTemporaryDirectoryExists { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *error = nil; + + // Create a temporary directory if it does not exist or was deleted. + if ([_networkDirectoryURL checkResourceIsReachableAndReturnError:&error]) { + return YES; + } + + if (error && error.code != NSFileReadNoSuchFileError) { + [_loggerDelegate + GULNetwork_logWithLevel:kGULNetworkLogLevelWarning + messageCode:kGULNetworkMessageCodeURLSession014 + message:@"Error while trying to access Network temp folder. Error" + context:error]; + } + + NSError *writeError = nil; + + [fileManager createDirectoryAtURL:_networkDirectoryURL + withIntermediateDirectories:YES + attributes:nil + error:&writeError]; + if (writeError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession015 + message:@"Cannot create temporary directory. Error" + context:writeError]; + return NO; + } + + // Set the iCloud exclusion attribute on the Documents URL. + [self excludeFromBackupForURL:_networkDirectoryURL]; + + return YES; +} + +- (void)excludeFromBackupForURL:(NSURL *)url { + if (!url.path) { + return; + } + + // Set the iCloud exclusion attribute on the Documents URL. + NSError *preventBackupError = nil; + [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&preventBackupError]; + if (preventBackupError) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession016 + message:@"Cannot exclude temporary folder from iTunes backup"]; + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler API_AVAILABLE(ios(7.0)) { + NSArray *nonAllowedRedirectionCodes = @[ + @(kGULNetworkHTTPStatusCodeFound), @(kGULNetworkHTTPStatusCodeMovedPermanently), + @(kGULNetworkHTTPStatusCodeMovedTemporarily), @(kGULNetworkHTTPStatusCodeMultipleChoices) + ]; + + // Allow those not in the non allowed list to be followed. + if (![nonAllowedRedirectionCodes containsObject:@(response.statusCode)]) { + completionHandler(request); + return; + } + + // Do not allow redirection if the response code is in the non-allowed list. + NSURLRequest *newRequest = request; + + if (response) { + newRequest = nil; + } + + completionHandler(newRequest); +} + +#pragma mark - Helper Methods + ++ (void)setSessionInFetcherMap:(GULNetworkURLSession *)session forSessionID:(NSString *)sessionID { + [[self sessionIDToFetcherMapReadWriteLock] lock]; + GULNetworkURLSession *existingSession = + [[[self class] sessionIDToFetcherMap] objectForKey:sessionID]; + if (existingSession) { + if (session) { + NSString *message = [NSString stringWithFormat:@"Discarding session: %@", existingSession]; + [existingSession->_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelInfo + messageCode:kGULNetworkMessageCodeURLSession019 + message:message]; + } + [existingSession->_URLSession finishTasksAndInvalidate]; + } + if (session) { + [[[self class] sessionIDToFetcherMap] setObject:session forKey:sessionID]; + } else { + [[[self class] sessionIDToFetcherMap] removeObjectForKey:sessionID]; + } + [[self sessionIDToFetcherMapReadWriteLock] unlock]; +} + ++ (nullable GULNetworkURLSession *)sessionFromFetcherMapForSessionID:(NSString *)sessionID { + [[self sessionIDToFetcherMapReadWriteLock] lock]; + GULNetworkURLSession *session = [[[self class] sessionIDToFetcherMap] objectForKey:sessionID]; + [[self sessionIDToFetcherMapReadWriteLock] unlock]; + return session; +} + +- (void)callCompletionHandler:(GULNetworkURLSessionCompletionHandler)handler + withResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *)error { + if (error) { + [_loggerDelegate GULNetwork_logWithLevel:kGULNetworkLogLevelError + messageCode:kGULNetworkMessageCodeURLSession017 + message:@"Encounter network error. Code, error" + contexts:@[ @(error.code), error ]]; + } + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(response, data, self->_sessionID, error); + }); + } +} + +// Always use the request parameters even if the default session configuration is more restrictive. +- (void)populateSessionConfig:(NSURLSessionConfiguration *)sessionConfig + withRequest:(NSURLRequest *)request API_AVAILABLE(ios(7.0)) { + sessionConfig.HTTPAdditionalHeaders = request.allHTTPHeaderFields; + sessionConfig.timeoutIntervalForRequest = request.timeoutInterval; + sessionConfig.timeoutIntervalForResource = request.timeoutInterval; + sessionConfig.requestCachePolicy = request.cachePolicy; +} + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h new file mode 100644 index 0000000..a8cc45b --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULMutableDictionary.h @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +/// A mutable dictionary that provides atomic accessor and mutators. +@interface GULMutableDictionary : NSObject + +/// Returns an object given a key in the dictionary or nil if not found. +- (id)objectForKey:(id)key; + +/// Updates the object given its key or adds it to the dictionary if it is not in the dictionary. +- (void)setObject:(id)object forKey:(id)key; + +/// Removes the object given its session ID from the dictionary. +- (void)removeObjectForKey:(id)key; + +/// Removes all objects. +- (void)removeAllObjects; + +/// Returns the number of current objects in the dictionary. +- (NSUInteger)count; + +/// Returns an object given a key in the dictionary or nil if not found. +- (id)objectForKeyedSubscript:(id)key; + +/// Updates the object given its key or adds it to the dictionary if it is not in the dictionary. +- (void)setObject:(id)obj forKeyedSubscript:(id)key; + +/// Returns the immutable dictionary. +- (NSDictionary *)dictionary; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h new file mode 100644 index 0000000..0e75ae5 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetwork.h @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "GULNetworkConstants.h" +#import "GULNetworkLoggerProtocol.h" +#import "GULNetworkURLSession.h" + +/// Delegate protocol for GULNetwork events. +@protocol GULNetworkReachabilityDelegate + +/// Tells the delegate to handle events when the network reachability changes to connected or not +/// connected. +- (void)reachabilityDidChange; + +@end + +/// The Network component that provides network status and handles network requests and responses. +/// This is not thread safe. +/// +/// NOTE: +/// User must add FIRAnalytics handleEventsForBackgroundURLSessionID:completionHandler to the +/// AppDelegate application:handleEventsForBackgroundURLSession:completionHandler: +@interface GULNetwork : NSObject + +/// Indicates if network connectivity is available. +@property(nonatomic, readonly, getter=isNetworkConnected) BOOL networkConnected; + +/// Indicates if there are any uploads in progress. +@property(nonatomic, readonly, getter=hasUploadInProgress) BOOL uploadInProgress; + +/// An optional delegate that can be used in the event when network reachability changes. +@property(nonatomic, weak) id reachabilityDelegate; + +/// An optional delegate that can be used to log messages, warnings or errors that occur in the +/// network operations. +@property(nonatomic, weak) id loggerDelegate; + +/// Indicates whether the logger should display debug messages. +@property(nonatomic, assign) BOOL isDebugModeEnabled; + +/// The time interval in seconds for the network request to timeout. +@property(nonatomic, assign) NSTimeInterval timeoutInterval; + +/// Initializes with the default reachability host. +- (instancetype)init; + +/// Initializes with a custom reachability host. +- (instancetype)initWithReachabilityHost:(NSString *)reachabilityHost; + +/// Handles events when background session with the given ID has finished. ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler; + +/// Compresses and sends a POST request with the provided data to the URL. The session will be +/// background session if usingBackgroundSession is YES. Otherwise, the POST session is default +/// session. Returns a session ID or nil if an error occurs. +- (NSString *)postURL:(NSURL *)url + payload:(NSData *)payload + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler; + +/// Sends a GET request with the provided data to the URL. The session will be background session +/// if usingBackgroundSession is YES. Otherwise, the GET session is default session. Returns a +/// session ID or nil if an error occurs. +- (NSString *)getURL:(NSURL *)url + headers:(NSDictionary *)headers + queue:(dispatch_queue_t)queue + usingBackgroundSession:(BOOL)usingBackgroundSession + completionHandler:(GULNetworkCompletionHandler)handler; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h new file mode 100644 index 0000000..44d440b --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkConstants.h @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +/// Error codes in Firebase Network error domain. +/// Note: these error codes should never change. It would make it harder to decode the errors if +/// we inadvertently altered any of these codes in a future SDK version. +typedef NS_ENUM(NSInteger, GULNetworkErrorCode) { + /// Unknown error. + GULNetworkErrorCodeUnknown = 0, + /// Error occurs when the request URL is invalid. + GULErrorCodeNetworkInvalidURL = 1, + /// Error occurs when request cannot be constructed. + GULErrorCodeNetworkRequestCreation = 2, + /// Error occurs when payload cannot be compressed. + GULErrorCodeNetworkPayloadCompression = 3, + /// Error occurs when session task cannot be created. + GULErrorCodeNetworkSessionTaskCreation = 4, + /// Error occurs when there is no response. + GULErrorCodeNetworkInvalidResponse = 5 +}; + +#pragma mark - Network constants + +/// The prefix of the ID of the background session. +extern NSString *const kGULNetworkBackgroundSessionConfigIDPrefix; + +/// The sub directory to store the files of data that is being uploaded in the background. +extern NSString *const kGULNetworkApplicationSupportSubdirectory; + +/// Name of the temporary directory that stores files for background uploading. +extern NSString *const kGULNetworkTempDirectoryName; + +/// The period when the temporary uploading file can stay. +extern const NSTimeInterval kGULNetworkTempFolderExpireTime; + +/// The default network request timeout interval. +extern const NSTimeInterval kGULNetworkTimeOutInterval; + +/// The host to check the reachability of the network. +extern NSString *const kGULNetworkReachabilityHost; + +/// The key to get the error context of the UserInfo. +extern NSString *const kGULNetworkErrorContext; + +#pragma mark - Network Status Code + +extern const int kGULNetworkHTTPStatusOK; +extern const int kGULNetworkHTTPStatusNoContent; +extern const int kGULNetworkHTTPStatusCodeMultipleChoices; +extern const int kGULNetworkHTTPStatusCodeMovedPermanently; +extern const int kGULNetworkHTTPStatusCodeFound; +extern const int kGULNetworkHTTPStatusCodeNotModified; +extern const int kGULNetworkHTTPStatusCodeMovedTemporarily; +extern const int kGULNetworkHTTPStatusCodeNotFound; +extern const int kGULNetworkHTTPStatusCodeCannotAcceptTraffic; +extern const int kGULNetworkHTTPStatusCodeUnavailable; + +#pragma mark - Error Domain + +extern NSString *const kGULNetworkErrorDomain; + +/// The logger service for GULNetwork. +extern GULLoggerService kGULLoggerNetwork; diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h new file mode 100644 index 0000000..f1be590 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import + +#import "GULNetworkMessageCode.h" + +/// The log levels used by GULNetworkLogger. +typedef NS_ENUM(NSInteger, GULNetworkLogLevel) { + kGULNetworkLogLevelError = GULLoggerLevelError, + kGULNetworkLogLevelWarning = GULLoggerLevelWarning, + kGULNetworkLogLevelInfo = GULLoggerLevelInfo, + kGULNetworkLogLevelDebug = GULLoggerLevelDebug, +}; + +@protocol GULNetworkLoggerDelegate + +@required +/// Tells the delegate to log a message with an array of contexts and the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + contexts:(NSArray *)contexts; + +/// Tells the delegate to log a message with a context and the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message + context:(id)context; + +/// Tells the delegate to log a message with the log level. +- (void)GULNetwork_logWithLevel:(GULNetworkLogLevel)logLevel + messageCode:(GULNetworkMessageCode)messageCode + message:(NSString *)message; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h new file mode 100644 index 0000000..f9d1628 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Make sure these codes do not overlap with any contained in the FIRAMessageCode enum. +typedef NS_ENUM(NSInteger, GULNetworkMessageCode) { + // GULNetwork.m + kGULNetworkMessageCodeNetwork000 = 900000, // I-NET900000 + kGULNetworkMessageCodeNetwork001 = 900001, // I-NET900001 + kGULNetworkMessageCodeNetwork002 = 900002, // I-NET900002 + kGULNetworkMessageCodeNetwork003 = 900003, // I-NET900003 + // GULNetworkURLSession.m + kGULNetworkMessageCodeURLSession000 = 901000, // I-NET901000 + kGULNetworkMessageCodeURLSession001 = 901001, // I-NET901001 + kGULNetworkMessageCodeURLSession002 = 901002, // I-NET901002 + kGULNetworkMessageCodeURLSession003 = 901003, // I-NET901003 + kGULNetworkMessageCodeURLSession004 = 901004, // I-NET901004 + kGULNetworkMessageCodeURLSession005 = 901005, // I-NET901005 + kGULNetworkMessageCodeURLSession006 = 901006, // I-NET901006 + kGULNetworkMessageCodeURLSession007 = 901007, // I-NET901007 + kGULNetworkMessageCodeURLSession008 = 901008, // I-NET901008 + kGULNetworkMessageCodeURLSession009 = 901009, // I-NET901009 + kGULNetworkMessageCodeURLSession010 = 901010, // I-NET901010 + kGULNetworkMessageCodeURLSession011 = 901011, // I-NET901011 + kGULNetworkMessageCodeURLSession012 = 901012, // I-NET901012 + kGULNetworkMessageCodeURLSession013 = 901013, // I-NET901013 + kGULNetworkMessageCodeURLSession014 = 901014, // I-NET901014 + kGULNetworkMessageCodeURLSession015 = 901015, // I-NET901015 + kGULNetworkMessageCodeURLSession016 = 901016, // I-NET901016 + kGULNetworkMessageCodeURLSession017 = 901017, // I-NET901017 + kGULNetworkMessageCodeURLSession018 = 901018, // I-NET901018 + kGULNetworkMessageCodeURLSession019 = 901019, // I-NET901019 +}; diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h new file mode 100644 index 0000000..3f9f7f9 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkURLSession.h @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "GULNetworkLoggerProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^GULNetworkCompletionHandler)(NSHTTPURLResponse *_Nullable response, + NSData *_Nullable data, + NSError *_Nullable error); +typedef void (^GULNetworkURLSessionCompletionHandler)(NSHTTPURLResponse *_Nullable response, + NSData *_Nullable data, + NSString *sessionID, + NSError *_Nullable error); +typedef void (^GULNetworkSystemCompletionHandler)(void); + +/// The protocol that uses NSURLSession for iOS >= 7.0 to handle requests and responses. +@interface GULNetworkURLSession : NSObject + +/// Indicates whether the background network is enabled. Default value is NO. +@property(nonatomic, getter=isBackgroundNetworkEnabled) BOOL backgroundNetworkEnabled; + +/// The logger delegate to log message, errors or warnings that occur during the network operations. +@property(nonatomic, weak, nullable) id loggerDelegate; + +/// Calls the system provided completion handler after the background session is finished. ++ (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID + completionHandler:(GULNetworkSystemCompletionHandler)completionHandler; + +/// Initializes with logger delegate. +- (instancetype)initWithNetworkLoggerDelegate: + (nullable id)networkLoggerDelegate NS_DESIGNATED_INITIALIZER; + +- (instancetype)init NS_UNAVAILABLE; + +/// Sends an asynchronous POST request and calls the provided completion handler when the request +/// completes or when errors occur, and returns an ID of the session/connection. +- (nullable NSString *)sessionIDFromAsyncPOSTRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler; + +/// Sends an asynchronous GET request and calls the provided completion handler when the request +/// completes or when errors occur, and returns an ID of the session. +- (nullable NSString *)sessionIDFromAsyncGETRequest:(NSURLRequest *)request + completionHandler:(GULNetworkURLSessionCompletionHandler)handler; + +NS_ASSUME_NONNULL_END +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h new file mode 100644 index 0000000..8883c4d --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +typedef SCNetworkReachabilityRef (*GULReachabilityCreateWithNameFn)(CFAllocatorRef allocator, + const char *host); + +typedef Boolean (*GULReachabilitySetCallbackFn)(SCNetworkReachabilityRef target, + SCNetworkReachabilityCallBack callback, + SCNetworkReachabilityContext *context); +typedef Boolean (*GULReachabilityScheduleWithRunLoopFn)(SCNetworkReachabilityRef target, + CFRunLoopRef runLoop, + CFStringRef runLoopMode); +typedef Boolean (*GULReachabilityUnscheduleFromRunLoopFn)(SCNetworkReachabilityRef target, + CFRunLoopRef runLoop, + CFStringRef runLoopMode); + +typedef void (*GULReachabilityReleaseFn)(CFTypeRef cf); + +struct GULReachabilityApi { + GULReachabilityCreateWithNameFn createWithNameFn; + GULReachabilitySetCallbackFn setCallbackFn; + GULReachabilityScheduleWithRunLoopFn scheduleWithRunLoopFn; + GULReachabilityUnscheduleFromRunLoopFn unscheduleFromRunLoopFn; + GULReachabilityReleaseFn releaseFn; +}; + +@interface GULReachabilityChecker (Internal) + +- (const struct GULReachabilityApi *)reachabilityApi; +- (void)setReachabilityApi:(const struct GULReachabilityApi *)reachabilityApi; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m new file mode 100644 index 0000000..1ddacdf --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/GULReachabilityChecker.m @@ -0,0 +1,240 @@ +// Copyright 2017 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +#import "GULReachabilityChecker+Internal.h" +#import "Private/GULReachabilityChecker.h" +#import "Private/GULReachabilityMessageCode.h" + +#import +#import + +static GULLoggerService kGULLoggerReachability = @"[GULReachability]"; + +static void ReachabilityCallback(SCNetworkReachabilityRef reachability, + SCNetworkReachabilityFlags flags, + void *info); + +static const struct GULReachabilityApi kGULDefaultReachabilityApi = { + SCNetworkReachabilityCreateWithName, + SCNetworkReachabilitySetCallback, + SCNetworkReachabilityScheduleWithRunLoop, + SCNetworkReachabilityUnscheduleFromRunLoop, + CFRelease, +}; + +static NSString *const kGULReachabilityUnknownStatus = @"Unknown"; +static NSString *const kGULReachabilityConnectedStatus = @"Connected"; +static NSString *const kGULReachabilityDisconnectedStatus = @"Disconnected"; + +@interface GULReachabilityChecker () + +@property(nonatomic, assign) const struct GULReachabilityApi *reachabilityApi; +@property(nonatomic, assign) GULReachabilityStatus reachabilityStatus; +@property(nonatomic, copy) NSString *host; +@property(nonatomic, assign) SCNetworkReachabilityRef reachability; + +@end + +@implementation GULReachabilityChecker + +@synthesize reachabilityApi = reachabilityApi_; +@synthesize reachability = reachability_; + +- (const struct GULReachabilityApi *)reachabilityApi { + return reachabilityApi_; +} + +- (void)setReachabilityApi:(const struct GULReachabilityApi *)reachabilityApi { + if (reachability_) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode000], + @"Cannot change reachability API while reachability is running. " + @"Call stop first."); + return; + } + reachabilityApi_ = reachabilityApi; +} + +@synthesize reachabilityStatus = reachabilityStatus_; +@synthesize host = host_; +@synthesize reachabilityDelegate = reachabilityDelegate_; + +- (BOOL)isActive { + return reachability_ != nil; +} + +- (void)setReachabilityDelegate:(id)reachabilityDelegate { + if (reachabilityDelegate && + (![(NSObject *)reachabilityDelegate conformsToProtocol:@protocol(GULReachabilityDelegate)])) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-NET%06ld", (long)kGULReachabilityMessageCode005], + @"Reachability delegate doesn't conform to Reachability protocol."); + return; + } + reachabilityDelegate_ = reachabilityDelegate; +} + +- (instancetype)initWithReachabilityDelegate:(id)reachabilityDelegate + withHost:(NSString *)host { + self = [super init]; + + if (!host || !host.length) { + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode001], + @"Invalid host specified"); + return nil; + } + if (self) { + [self setReachabilityDelegate:reachabilityDelegate]; + reachabilityApi_ = &kGULDefaultReachabilityApi; + reachabilityStatus_ = kGULReachabilityUnknown; + host_ = [host copy]; + reachability_ = nil; + } + return self; +} + +- (void)dealloc { + reachabilityDelegate_ = nil; + [self stop]; +} + +- (BOOL)start { + if (!reachability_) { + reachability_ = reachabilityApi_->createWithNameFn(kCFAllocatorDefault, [host_ UTF8String]); + if (!reachability_) { + return NO; + } + SCNetworkReachabilityContext context = { + 0, /* version */ + (__bridge void *)(self), /* info (passed as last parameter to reachability callback) */ + NULL, /* retain */ + NULL, /* release */ + NULL /* copyDescription */ + }; + if (!reachabilityApi_->setCallbackFn(reachability_, ReachabilityCallback, &context) || + !reachabilityApi_->scheduleWithRunLoopFn(reachability_, CFRunLoopGetMain(), + kCFRunLoopCommonModes)) { + reachabilityApi_->releaseFn(reachability_); + reachability_ = nil; + + GULLogError(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode002], + @"Failed to start reachability handle"); + return NO; + } + } + GULLogDebug(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode003], + @"Monitoring the network status"); + return YES; +} + +- (void)stop { + if (reachability_) { + reachabilityStatus_ = kGULReachabilityUnknown; + reachabilityApi_->unscheduleFromRunLoopFn(reachability_, CFRunLoopGetMain(), + kCFRunLoopCommonModes); + reachabilityApi_->releaseFn(reachability_); + reachability_ = nil; + } +} + +- (GULReachabilityStatus)statusForFlags:(SCNetworkReachabilityFlags)flags { + GULReachabilityStatus status = kGULReachabilityNotReachable; + // If the Reachable flag is not set, we definitely don't have connectivity. + if (flags & kSCNetworkReachabilityFlagsReachable) { + // Reachable flag is set. Check further flags. + if (!(flags & kSCNetworkReachabilityFlagsConnectionRequired)) { +// Connection required flag is not set, so we have connectivity. +#if TARGET_OS_IOS || TARGET_OS_TV + status = (flags & kSCNetworkReachabilityFlagsIsWWAN) ? kGULReachabilityViaCellular + : kGULReachabilityViaWifi; +#elif TARGET_OS_OSX + status = kGULReachabilityViaWifi; +#endif + } else if ((flags & (kSCNetworkReachabilityFlagsConnectionOnDemand | + kSCNetworkReachabilityFlagsConnectionOnTraffic)) && + !(flags & kSCNetworkReachabilityFlagsInterventionRequired)) { +// If the connection on demand or connection on traffic flag is set, and user intervention +// is not required, we have connectivity. +#if TARGET_OS_IOS || TARGET_OS_TV + status = (flags & kSCNetworkReachabilityFlagsIsWWAN) ? kGULReachabilityViaCellular + : kGULReachabilityViaWifi; +#elif TARGET_OS_OSX + status = kGULReachabilityViaWifi; +#endif + } + } + return status; +} + +- (void)reachabilityFlagsChanged:(SCNetworkReachabilityFlags)flags { + GULReachabilityStatus status = [self statusForFlags:flags]; + if (reachabilityStatus_ != status) { + NSString *reachabilityStatusString; + if (status == kGULReachabilityUnknown) { + reachabilityStatusString = kGULReachabilityUnknownStatus; + } else { + reachabilityStatusString = (status == kGULReachabilityNotReachable) + ? kGULReachabilityDisconnectedStatus + : kGULReachabilityConnectedStatus; + } + + GULLogDebug(kGULLoggerReachability, NO, + [NSString stringWithFormat:@"I-REA%06ld", (long)kGULReachabilityMessageCode004], + @"Network status has changed. Code:%@, status:%@", @(status), + reachabilityStatusString); + reachabilityStatus_ = status; + [reachabilityDelegate_ reachability:self statusChanged:reachabilityStatus_]; + } +} + +@end + +static void ReachabilityCallback(SCNetworkReachabilityRef reachability, + SCNetworkReachabilityFlags flags, + void *info) { + GULReachabilityChecker *checker = (__bridge GULReachabilityChecker *)info; + [checker reachabilityFlagsChanged:flags]; +} + +// This function used to be at the top of the file, but it was moved here +// as a workaround for a suspected compiler bug. When compiled in Release mode +// and run on an iOS device with WiFi disabled, the reachability code crashed +// when calling SCNetworkReachabilityScheduleWithRunLoop, or shortly thereafter. +// After unsuccessfully trying to diagnose the cause of the crash, it was +// discovered that moving this function to the end of the file magically fixed +// the crash. If you are going to edit this file, exercise caution and make sure +// to test thoroughly with an iOS device under various network conditions. +const NSString *GULReachabilityStatusString(GULReachabilityStatus status) { + switch (status) { + case kGULReachabilityUnknown: + return @"Reachability Unknown"; + + case kGULReachabilityNotReachable: + return @"Not reachable"; + + case kGULReachabilityViaWifi: + return @"Reachable via Wifi"; + + case kGULReachabilityViaCellular: + return @"Reachable via Cellular Data"; + + default: + return [NSString stringWithFormat:@"Invalid reachability status %d", (int)status]; + } +} diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h new file mode 100644 index 0000000..b317a0b --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityChecker.h @@ -0,0 +1,77 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +/// Reachability Status +typedef enum { + kGULReachabilityUnknown, ///< Have not yet checked or been notified whether host is reachable. + kGULReachabilityNotReachable, ///< Host is not reachable. + kGULReachabilityViaWifi, ///< Host is reachable via Wifi. + kGULReachabilityViaCellular, ///< Host is reachable via cellular. +} GULReachabilityStatus; + +const NSString *GULReachabilityStatusString(GULReachabilityStatus status); + +@class GULReachabilityChecker; + +/// Google Analytics iOS Reachability Checker. +@protocol GULReachabilityDelegate +@required +/// Called when network status has changed. +- (void)reachability:(GULReachabilityChecker *)reachability + statusChanged:(GULReachabilityStatus)status; +@end + +/// Google Analytics iOS Network Status Checker. +@interface GULReachabilityChecker : NSObject + +/// The last known reachability status, or GULReachabilityStatusUnknown if the +/// checker is not active. +@property(nonatomic, readonly) GULReachabilityStatus reachabilityStatus; +/// The host to which reachability status is to be checked. +@property(nonatomic, copy, readonly) NSString *host; +/// The delegate to be notified of reachability status changes. +@property(nonatomic, weak) id reachabilityDelegate; +/// `YES` if the reachability checker is active, `NO` otherwise. +@property(nonatomic, readonly) BOOL isActive; + +/// Initialize the reachability checker. Note that you must call start to begin checking for and +/// receiving notifications about network status changes. +/// +/// @param reachabilityDelegate The delegate to be notified when reachability status to host +/// changes. +/// +/// @param host The name of the host. +/// +- (instancetype)initWithReachabilityDelegate:(id)reachabilityDelegate + withHost:(NSString *)host; + +- (instancetype)init NS_UNAVAILABLE; + +/// Start checking for reachability to the specified host. This has no effect if the status +/// checker is already checking for connectivity. +/// +/// @return `YES` if initiating status checking was successful or the status checking has already +/// been initiated, `NO` otherwise. +- (BOOL)start; + +/// Stop checking for reachability to the specified host. This has no effect if the status +/// checker is not checking for connectivity. +- (void)stop; + +@end diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h new file mode 100644 index 0000000..283cdd5 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Make sure these codes do not overlap with any contained in the FIRAMessageCode enum. +typedef NS_ENUM(NSInteger, GULReachabilityMessageCode) { + // GULReachabilityChecker.m + kGULReachabilityMessageCode000 = 902000, // I-NET902000 + kGULReachabilityMessageCode001 = 902001, // I-NET902001 + kGULReachabilityMessageCode002 = 902002, // I-NET902002 + kGULReachabilityMessageCode003 = 902003, // I-NET902003 + kGULReachabilityMessageCode004 = 902004, // I-NET902004 + kGULReachabilityMessageCode005 = 902005, // I-NET902005 + kGULReachabilityMessageCode006 = 902006, // I-NET902006 +}; diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m b/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m new file mode 100644 index 0000000..1b1bafb --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/GULUserDefaults.m @@ -0,0 +1,235 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import "Private/GULUserDefaults.h" + +#import + +NS_ASSUME_NONNULL_BEGIN + +static NSTimeInterval const kGULSynchronizeInterval = 1.0; + +static NSString *const kGULLogFormat = @"I-GUL%06ld"; + +static GULLoggerService kGULLogUserDefaultsService = @"[GoogleUtilities/UserDefaults]"; + +typedef NS_ENUM(NSInteger, GULUDMessageCode) { + GULUDMessageCodeInvalidKeyGet = 1, + GULUDMessageCodeInvalidKeySet = 2, + GULUDMessageCodeInvalidObjectSet = 3, + GULUDMessageCodeSynchronizeFailed = 4, +}; + +@interface GULUserDefaults () + +/// Equivalent to the suite name for NSUserDefaults. +@property(readonly) CFStringRef appNameRef; + +@property(atomic) BOOL isPreferenceFileExcluded; + +@end + +@implementation GULUserDefaults { + // The application name is the same with the suite name of the NSUserDefaults, and it is used for + // preferences. + CFStringRef _appNameRef; +} + ++ (GULUserDefaults *)standardUserDefaults { + static GULUserDefaults *standardUserDefaults; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + standardUserDefaults = [[GULUserDefaults alloc] init]; + }); + return standardUserDefaults; +} + +- (instancetype)init { + return [self initWithSuiteName:nil]; +} + +- (instancetype)initWithSuiteName:(nullable NSString *)suiteName { + self = [super init]; + + NSString *name = [suiteName copy]; + + if (self) { + // `kCFPreferencesCurrentApplication` maps to the same defaults database as + // `[NSUserDefaults standardUserDefaults]`. + _appNameRef = + name.length ? (__bridge_retained CFStringRef)name : kCFPreferencesCurrentApplication; + } + + return self; +} + +- (void)dealloc { + // If we're using a custom `_appNameRef` it needs to be released. If it's a constant, it shouldn't + // need to be released since we don't own it. + if (CFStringCompare(_appNameRef, kCFPreferencesCurrentApplication, 0) != kCFCompareEqualTo) { + CFRelease(_appNameRef); + } + + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(synchronize) + object:nil]; +} + +- (nullable id)objectForKey:(NSString *)defaultName { + NSString *key = [defaultName copy]; + if (![key isKindOfClass:[NSString class]] || !key.length) { + GULLogWarning(@"", NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidKeyGet], + @"Cannot get object for invalid user default key."); + return nil; + } + return (__bridge_transfer id)CFPreferencesCopyAppValue((__bridge CFStringRef)key, _appNameRef); +} + +- (void)setObject:(nullable id)value forKey:(NSString *)defaultName { + NSString *key = [defaultName copy]; + if (![key isKindOfClass:[NSString class]] || !key.length) { + GULLogWarning(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidKeySet], + @"Cannot set object for invalid user default key."); + return; + } + if (!value) { + CFPreferencesSetAppValue((__bridge CFStringRef)key, NULL, _appNameRef); + [self scheduleSynchronize]; + return; + } + BOOL isAcceptableValue = + [value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]] || + [value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]] || + [value isKindOfClass:[NSDate class]] || [value isKindOfClass:[NSData class]]; + if (!isAcceptableValue) { + GULLogWarning(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeInvalidObjectSet], + @"Cannot set invalid object to user defaults. Must be a string, number, array, " + @"dictionary, date, or data. Value: %@", + value); + return; + } + + CFPreferencesSetAppValue((__bridge CFStringRef)key, (__bridge CFStringRef)value, _appNameRef); + [self scheduleSynchronize]; +} + +- (void)removeObjectForKey:(NSString *)key { + [self setObject:nil forKey:key]; +} + +#pragma mark - Getters + +- (NSInteger)integerForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.integerValue; +} + +- (float)floatForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.floatValue; +} + +- (double)doubleForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.doubleValue; +} + +- (BOOL)boolForKey:(NSString *)defaultName { + NSNumber *object = [self objectForKey:defaultName]; + return object.boolValue; +} + +- (nullable NSString *)stringForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +- (nullable NSArray *)arrayForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +- (nullable NSDictionary *)dictionaryForKey:(NSString *)defaultName { + return [self objectForKey:defaultName]; +} + +#pragma mark - Setters + +- (void)setInteger:(NSInteger)integer forKey:(NSString *)defaultName { + [self setObject:@(integer) forKey:defaultName]; +} + +- (void)setFloat:(float)value forKey:(NSString *)defaultName { + [self setObject:@(value) forKey:defaultName]; +} + +- (void)setDouble:(double)doubleNumber forKey:(NSString *)defaultName { + [self setObject:@(doubleNumber) forKey:defaultName]; +} + +- (void)setBool:(BOOL)boolValue forKey:(NSString *)defaultName { + [self setObject:@(boolValue) forKey:defaultName]; +} + +#pragma mark - Save data + +- (void)synchronize { + if (!CFPreferencesAppSynchronize(_appNameRef)) { + GULLogError(kGULLogUserDefaultsService, NO, + [NSString stringWithFormat:kGULLogFormat, (long)GULUDMessageCodeSynchronizeFailed], + @"Cannot synchronize user defaults to disk"); + } +} + +#pragma mark - Private methods + +/// Removes all values from the search list entry specified by 'domainName', the current user, and +/// any host. The change is persistent. Equivalent to -removePersistentDomainForName: of +/// NSUserDefaults. +- (void)clearAllData { + // On macOS, using `kCFPreferencesCurrentHost` will not set all the keys necessary to match + // `NSUserDefaults`. +#if TARGET_OS_MAC + CFStringRef host = kCFPreferencesAnyHost; +#else + CFStringRef host = kCFPreferencesCurrentHost; +#endif // TARGET_OS_OSX + + CFArrayRef keyList = CFPreferencesCopyKeyList(_appNameRef, kCFPreferencesCurrentUser, host); + if (!keyList) { + return; + } + + CFPreferencesSetMultiple(NULL, keyList, _appNameRef, kCFPreferencesCurrentUser, host); + CFRelease(keyList); + [self scheduleSynchronize]; +} + +- (void)scheduleSynchronize { + // Synchronize data using a timer so that multiple set... calls can be coalesced under one + // synchronize. + [NSObject cancelPreviousPerformRequestsWithTarget:self + selector:@selector(synchronize) + object:nil]; + // This method may be called on multiple queues (due to set... methods can be called on any queue) + // synchronize can be scheduled on different queues, so make sure that it does not crash. If this + // instance goes away, self will be released also, no one will retain it and the schedule won't be + // called. + [self performSelector:@selector(synchronize) withObject:nil afterDelay:kGULSynchronizeInterval]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h b/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h new file mode 100644 index 0000000..0d04781 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/GoogleUtilities/UserDefaults/Private/GULUserDefaults.h @@ -0,0 +1,110 @@ +// Copyright 2018 Google +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// A thread-safe user defaults that uses C functions from CFPreferences.h instead of +/// `NSUserDefaults`. This is to avoid sending an `NSNotification` when it's changed from a +/// background thread to avoid crashing. // TODO: Insert radar number here. +@interface GULUserDefaults : NSObject + +/// A shared user defaults similar to +[NSUserDefaults standardUserDefaults] and accesses the same +/// data of the standardUserDefaults. ++ (GULUserDefaults *)standardUserDefaults; + +/// Initializes preferences with a suite name that is the same with the NSUserDefaults' suite name. +/// Both of CFPreferences and NSUserDefaults share the same plist file so their data will exactly +/// the same. +/// +/// @param suiteName The name of the suite of the user defaults. +- (instancetype)initWithSuiteName:(nullable NSString *)suiteName; + +#pragma mark - Getters + +/// Searches the receiver's search list for a default with the key 'defaultName' and return it. If +/// another process has changed defaults in the search list, NSUserDefaults will automatically +/// update to the latest values. If the key in question has been marked as ubiquitous via a Defaults +/// Configuration File, the latest value may not be immediately available, and the registered value +/// will be returned instead. +- (nullable id)objectForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will return nil if the value is not an NSArray. +- (nullable NSArray *)arrayForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will return nil if the value +/// is not an NSDictionary. +- (nullable NSDictionary *)dictionaryForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it will convert NSNumber values to their NSString +/// representation. If a non-string non-number value is found, nil will be returned. +- (nullable NSString *)stringForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it converts the returned value to an NSInteger. If the +/// value is an NSNumber, the result of -integerValue will be returned. If the value is an NSString, +/// it will be converted to NSInteger if possible. If the value is a boolean, it will be converted +/// to either 1 for YES or 0 for NO. If the value is absent or can't be converted to an integer, 0 +/// will be returned. +- (NSInteger)integerForKey:(NSString *)defaultName; + +/// Similar to -integerForKey:, except that it returns a float, and boolean values will not be +/// converted. +- (float)floatForKey:(NSString *)defaultName; + +/// Similar to -integerForKey:, except that it returns a double, and boolean values will not be +/// converted. +- (double)doubleForKey:(NSString *)defaultName; + +/// Equivalent to -objectForKey:, except that it converts the returned value to a BOOL. If the value +/// is an NSNumber, NO will be returned if the value is 0, YES otherwise. If the value is an +/// NSString, values of "YES" or "1" will return YES, and values of "NO", "0", or any other string +/// will return NO. If the value is absent or can't be converted to a BOOL, NO will be returned. +- (BOOL)boolForKey:(NSString *)defaultName; + +#pragma mark - Setters + +/// Immediately stores a value (or removes the value if `nil` is passed as the value) for the +/// provided key in the search list entry for the receiver's suite name in the current user and any +/// host, then asynchronously stores the value persistently, where it is made available to other +/// processes. +- (void)setObject:(nullable id)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a float to an NSNumber. +- (void)setFloat:(float)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a double to an +/// NSNumber. +- (void)setDouble:(double)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from an NSInteger to an +/// NSNumber. +- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName; + +/// Equivalent to -setObject:forKey: except that the value is converted from a BOOL to an NSNumber. +- (void)setBool:(BOOL)value forKey:(NSString *)defaultName; + +#pragma mark - Removing Defaults + +/// Equivalent to -[... setObject:nil forKey:defaultName] +- (void)removeObjectForKey:(NSString *)defaultName; + +#pragma mark - Save data + +/// Blocks the calling thread until all in-progress set operations have completed. +- (void)synchronize; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/GoogleUtilities/LICENSE b/My Mind/Pods/GoogleUtilities/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/LICENSE @@ -0,0 +1,202 @@ + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/My Mind/Pods/GoogleUtilities/README.md b/My Mind/Pods/GoogleUtilities/README.md new file mode 100644 index 0000000..d414a4c --- /dev/null +++ b/My Mind/Pods/GoogleUtilities/README.md @@ -0,0 +1,193 @@ +# Firebase iOS Open Source Development [![Build Status](https://travis-ci.org/firebase/firebase-ios-sdk.svg?branch=master)](https://travis-ci.org/firebase/firebase-ios-sdk) + +This repository contains a subset of the Firebase iOS SDK source. It currently +includes FirebaseCore, FirebaseAuth, FirebaseDatabase, FirebaseFirestore, +FirebaseFunctions, FirebaseInAppMessagingDisplay, FirebaseMessaging and +FirebaseStorage. + +The repository also includes GoogleUtilities source. The +[GoogleUtilities](GoogleUtilities/README.md) pod is +a set of utilities used by Firebase and other Google products. + +Firebase is an app development platform with tools to help you build, grow and +monetize your app. More information about Firebase can be found at +[https://firebase.google.com](https://firebase.google.com). + +## Installation + +See the three subsections for details about three different installation methods. +1. [Standard pod install](README.md#standard-pod-install) +1. [Installing from the GitHub repo](README.md#installing-from-github) +1. [Experimental Carthage](README.md#carthage-ios-only) + +### Standard pod install + +Go to +[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup). + +### Installing from GitHub + +For releases starting with 5.0.0, the source for each release is also deployed +to CocoaPods master and available via standard +[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod). + +These instructions can be used to access the Firebase repo at other branches, +tags, or commits. + +#### Background + +See +[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod) +for instructions and options about overriding pod source locations. + +#### Accessing Firebase Source Snapshots + +All of the official releases are tagged in this repo and available via CocoaPods. To access a local +source snapshot or unreleased branch, use Podfile directives like the following: + +To access FirebaseFirestore via a branch: +``` +pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master' +``` + +To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do: + +``` +pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk' +pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk' +``` + +### Carthage (iOS only) + +Instructions for the experimental Carthage distribution are at +[Carthage](Carthage.md). + +### Rome + +Instructions for installing binary frameworks via +[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md). + +## Development + +Follow the subsequent instructions to develop, debug, unit test, run integration +tests, and try out reference samples: + +``` +$ git clone git@github.com:firebase/firebase-ios-sdk.git +$ cd firebase-ios-sdk/Example +$ pod update +$ open Firebase.xcworkspace +``` + +Firestore and Functions have self contained Xcode projects. See +[Firestore/README.md](Firestore/README.md) and +[Functions/README.md](Functions/README.md). + +### Code Formatting + +Travis will verify that any code changes are done in a style compliant way. Install +`clang-format` and `swiftformat`. +This command will get the right `clang-format` version: + +`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/0743d748ba8b41eec074a0a787dc80219142c525/Formula/clang-format.rb` + +### Running Unit Tests + +Select a scheme and press Command-u to build a component and run its unit tests. + +### Running Sample Apps +In order to run the sample apps and integration tests, you'll need valid +`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist +files without real values, but can be replaced with real plist files. To get your own +`GoogleService-Info.plist` files: + +1. Go to the [Firebase Console](https://console.firebase.google.com/) +2. Create a new Firebase project, if you don't already have one +3. For each sample app you want to test, create a new Firebase app with the sample app's bundle +identifier (e.g. `com.google.Database-Example`) +4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file +(e.g. in [Example/Database/App/](Example/Database/App/)); + +Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require +special Apple capabilities, and you will have to change the sample app to use a unique bundle +identifier that you can control in your own Apple Developer account. + +## Specific Component Instructions +See the sections below for any special instructions for those components. + +### Firebase Auth + +If you're doing specific Firebase Auth development, see +[the Auth Sample README](Example/Auth/README.md) for instructions about +building and running the FirebaseAuth pod along with various samples and tests. + +### Firebase Database + +To run the Database Integration tests, make your database authentication rules +[public](https://firebase.google.com/docs/database/security/quickstart). + +### Firebase Storage + +To run the Storage Integration tests, follow the instructions in +[FIRStorageIntegrationTests.m](Example/Storage/Tests/Integration/FIRStorageIntegrationTests.m). + +#### Push Notifications + +Push notifications can only be delivered to specially provisioned App IDs in the developer portal. +In order to actually test receiving push notifications, you will need to: + +1. Change the bundle identifier of the sample app to something you own in your Apple Developer +account, and enable that App ID for push notifications. +2. You'll also need to +[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs) +at **Project Settings > Cloud Messaging > [Your Firebase App]**. +3. Ensure your iOS device is added to your Apple Developer portal as a test device. + +#### iOS Simulator + +The iOS Simulator cannot register for remote notifications, and will not receive push notifications. +In order to receive push notifications, you'll have to follow the steps above and run the app on a +physical device. + +## Community Supported Efforts + +We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are +very grateful! We'd like to empower as many developers as we can to be able to use Firebase and +participate in the Firebase community. + +### macOS and tvOS +FirebaseAuth, FirebaseCore, FirebaseDatabase and FirebaseStorage now compile, run unit tests, and +work on macOS and tvOS, thanks to contributions from the community. There are a few tweaks needed, +like ensuring iOS-only, macOS-only, or tvOS-only code is correctly guarded with checks for +`TARGET_OS_IOS`, `TARGET_OS_OSX` and `TARGET_OS_TV`. + +For tvOS, checkout the [Sample](Example/tvOSSample). + +Keep in mind that macOS and tvOS are not officially supported by Firebase, and this repository is +actively developed primarily for iOS. While we can catch basic unit test issues with Travis, there +may be some changes where the SDK no longer works as expected on macOS or tvOS. If you encounter +this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues). + +For installation instructions, see [above](README.md#accessing-firebase-source-snapshots). + +Note that the Firebase pod is not available for macOS and tvOS. Install a selection of the +`FirebaseAuth`, `FirebaseCore`, `FirebaseDatabase` and `FirebaseStorage` CocoaPods. + +## Roadmap + +See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source +plans and directions. + +## Contributing + +See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase +iOS SDK. + +## License + +The contents of this repository is licensed under the +[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0). + +Your use of Firebase is governed by the +[Terms of Service for Firebase Services](https://firebase.google.com/terms/). diff --git a/My Mind/Pods/Headers/Private/Firebase/Firebase.h b/My Mind/Pods/Headers/Private/Firebase/Firebase.h new file mode 120000 index 0000000..07ac6eb --- /dev/null +++ b/My Mind/Pods/Headers/Private/Firebase/Firebase.h @@ -0,0 +1 @@ +../../../Firebase/CoreOnly/Sources/Firebase.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h new file mode 120000 index 0000000..e01a43a --- /dev/null +++ b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRAnalyticsInterop.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropEventNames.h b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropEventNames.h new file mode 120000 index 0000000..dbda3ec --- /dev/null +++ b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropEventNames.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropEventNames.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropParameterNames.h b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropParameterNames.h new file mode 120000 index 0000000..5145843 --- /dev/null +++ b/My Mind/Pods/Headers/Private/FirebaseAnalyticsInterop/FIRInteropParameterNames.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropParameterNames.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Private/FirebaseAuthInterop/FIRAuthInterop.h b/My Mind/Pods/Headers/Private/FirebaseAuthInterop/FIRAuthInterop.h new file mode 120000 index 0000000..0253e25 --- /dev/null +++ b/My Mind/Pods/Headers/Private/FirebaseAuthInterop/FIRAuthInterop.h @@ -0,0 +1 @@ +../../../FirebaseAuthInterop/Interop/Auth/Public/FIRAuthInterop.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Public/Firebase/Firebase.h b/My Mind/Pods/Headers/Public/Firebase/Firebase.h new file mode 120000 index 0000000..07ac6eb --- /dev/null +++ b/My Mind/Pods/Headers/Public/Firebase/Firebase.h @@ -0,0 +1 @@ +../../../Firebase/CoreOnly/Sources/Firebase.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h new file mode 120000 index 0000000..e01a43a --- /dev/null +++ b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRAnalyticsInterop.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRAnalyticsInterop.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropEventNames.h b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropEventNames.h new file mode 120000 index 0000000..dbda3ec --- /dev/null +++ b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropEventNames.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropEventNames.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropParameterNames.h b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropParameterNames.h new file mode 120000 index 0000000..5145843 --- /dev/null +++ b/My Mind/Pods/Headers/Public/FirebaseAnalyticsInterop/FIRInteropParameterNames.h @@ -0,0 +1 @@ +../../../FirebaseAnalyticsInterop/Interop/Analytics/Public/FIRInteropParameterNames.h \ No newline at end of file diff --git a/My Mind/Pods/Headers/Public/FirebaseAuthInterop/FIRAuthInterop.h b/My Mind/Pods/Headers/Public/FirebaseAuthInterop/FIRAuthInterop.h new file mode 120000 index 0000000..0253e25 --- /dev/null +++ b/My Mind/Pods/Headers/Public/FirebaseAuthInterop/FIRAuthInterop.h @@ -0,0 +1 @@ +../../../FirebaseAuthInterop/Interop/Auth/Public/FIRAuthInterop.h \ No newline at end of file diff --git a/My Mind/Pods/Manifest.lock b/My Mind/Pods/Manifest.lock new file mode 100644 index 0000000..4a9fc77 --- /dev/null +++ b/My Mind/Pods/Manifest.lock @@ -0,0 +1,139 @@ +PODS: + - Firebase/Auth (5.15.0): + - Firebase/CoreOnly + - FirebaseAuth (= 5.2.0) + - Firebase/Core (5.15.0): + - Firebase/CoreOnly + - FirebaseAnalytics (= 5.4.0) + - Firebase/CoreOnly (5.15.0): + - FirebaseCore (= 5.1.10) + - Firebase/Database (5.15.0): + - Firebase/CoreOnly + - FirebaseDatabase (= 5.0.4) + - Firebase/Messaging (5.15.0): + - Firebase/CoreOnly + - FirebaseMessaging (= 3.2.2) + - Firebase/Storage (5.15.0): + - Firebase/CoreOnly + - FirebaseStorage (= 3.0.3) + - FirebaseAnalytics (5.4.0): + - FirebaseCore (~> 5.1) + - FirebaseInstanceID (~> 3.3) + - GoogleAppMeasurement (= 5.4.0) + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - FirebaseAnalyticsInterop (1.1.0) + - FirebaseAuth (5.2.0): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - GoogleUtilities/Environment (~> 5.2) + - GTMSessionFetcher/Core (~> 1.1) + - FirebaseAuthInterop (1.0.0) + - FirebaseCore (5.1.10): + - GoogleUtilities/Logger (~> 5.2) + - FirebaseDatabase (5.0.4): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - leveldb-library (~> 1.18) + - FirebaseInstanceID (3.3.0): + - FirebaseCore (~> 5.1) + - GoogleUtilities/Environment (~> 5.3) + - GoogleUtilities/UserDefaults (~> 5.3) + - FirebaseMessaging (3.2.2): + - FirebaseAnalyticsInterop (~> 1.1) + - FirebaseCore (~> 5.1) + - FirebaseInstanceID (~> 3.0) + - GoogleUtilities/Environment (~> 5.2) + - GoogleUtilities/Reachability (~> 5.2) + - Protobuf (~> 3.1) + - FirebaseStorage (3.0.3): + - FirebaseAuthInterop (~> 1.0) + - FirebaseCore (~> 5.1) + - GTMSessionFetcher/Core (~> 1.1) + - GoogleAppMeasurement (5.4.0): + - GoogleUtilities/AppDelegateSwizzler (~> 5.2) + - GoogleUtilities/MethodSwizzler (~> 5.2) + - GoogleUtilities/Network (~> 5.2) + - "GoogleUtilities/NSData+zlib (~> 5.2)" + - nanopb (~> 0.3) + - GoogleUtilities/AppDelegateSwizzler (5.3.6): + - GoogleUtilities/Environment + - GoogleUtilities/Logger + - GoogleUtilities/Network + - GoogleUtilities/Environment (5.3.6) + - GoogleUtilities/Logger (5.3.6): + - GoogleUtilities/Environment + - GoogleUtilities/MethodSwizzler (5.3.6): + - GoogleUtilities/Logger + - GoogleUtilities/Network (5.3.6): + - GoogleUtilities/Logger + - "GoogleUtilities/NSData+zlib" + - GoogleUtilities/Reachability + - "GoogleUtilities/NSData+zlib (5.3.6)" + - GoogleUtilities/Reachability (5.3.6): + - GoogleUtilities/Logger + - GoogleUtilities/UserDefaults (5.3.6): + - GoogleUtilities/Logger + - GTMSessionFetcher/Core (1.2.1) + - leveldb-library (1.20) + - nanopb (0.3.901): + - nanopb/decode (= 0.3.901) + - nanopb/encode (= 0.3.901) + - nanopb/decode (0.3.901) + - nanopb/encode (0.3.901) + - Protobuf (3.6.1) + - SwiftForms (1.8.2) + +DEPENDENCIES: + - Firebase/Auth + - Firebase/Core + - Firebase/Database + - Firebase/Messaging + - Firebase/Storage + - SwiftForms + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Firebase + - FirebaseAnalytics + - FirebaseAnalyticsInterop + - FirebaseAuth + - FirebaseAuthInterop + - FirebaseCore + - FirebaseDatabase + - FirebaseInstanceID + - FirebaseMessaging + - FirebaseStorage + - GoogleAppMeasurement + - GoogleUtilities + - GTMSessionFetcher + - leveldb-library + - nanopb + - Protobuf + - SwiftForms + +SPEC CHECKSUMS: + Firebase: 8bb9268bff82374f2cbaaabb143e725743c316ae + FirebaseAnalytics: c06f9d70577d79074214700a71fd5d39de5550fb + FirebaseAnalyticsInterop: e5f21be9af6548372e2f0815834ff909bff395a2 + FirebaseAuth: 02e969ff430e156d99d4cb842d77b806b71ad7bb + FirebaseAuthInterop: 0ffa57668be100582bb7643d4fcb7615496c41fc + FirebaseCore: 35747502d9e8c6ee217385ad04446c7c2aaf9c5c + FirebaseDatabase: 0621689f77528d62b47e1c06ca737c4c19275d1a + FirebaseInstanceID: e2fa4cb35ef5558c200f7f0ad8a53e212215f93e + FirebaseMessaging: b412996f6a09337d232bb3a6676ce4d1f353d024 + FirebaseStorage: 3d22c041370593e639fba013d1eb698a8dae2881 + GoogleAppMeasurement: 98b71f5e04142793729a5ef23e5b96651ff4b70f + GoogleUtilities: 95996bea7c7d9b8fb811b7507669a4a8762f80c7 + GTMSessionFetcher: 32aeca0aa144acea523e1c8e053089dec2cb98ca + leveldb-library: 08cba283675b7ed2d99629a4bc5fd052cd2bb6a5 + nanopb: 2901f78ea1b7b4015c860c2fdd1ea2fee1a18d48 + Protobuf: 1eb9700044745f00181c136ef21b8ff3ad5a0fd5 + SwiftForms: f0d4d30401e21de87d9b7b63a4691a3d4e22bab5 + +PODFILE CHECKSUM: 78cec12473e63e23a4acf6cbc3ba860b858ca314 + +COCOAPODS: 1.5.3 diff --git a/My Mind/Pods/Pods.xcodeproj/project.pbxproj b/My Mind/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..48a046e --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,6351 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 0011998EDFF4EB77434BF209F237B958 /* dbformat.cc in Sources */ = {isa = PBXBuildFile; fileRef = F1D8CB7DF2E46250C1C43220C97810B6 /* dbformat.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 0056238FBF1C6575CB347D7D083078C5 /* FIRDatabaseQuery.h in Headers */ = {isa = PBXBuildFile; fileRef = 368E447E635FC44C3CA4A0F09D50292A /* FIRDatabaseQuery.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0124EE669FBEDC523BD6DDE9ED8F2122 /* FIRAuthNotificationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 5546B6C998BFFC4D1BE353AACAB4656B /* FIRAuthNotificationManager.m */; }; + 02AF93487363E896109B3F58B61028F3 /* version_set.h in Headers */ = {isa = PBXBuildFile; fileRef = E56C14A11112A55CF82997DF7D888028 /* version_set.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 02FA9DA67EC27D7D1635AE5DCB37D33E /* FSparseSnapshotTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 02867E76AFD212132A577D295F36FAFE /* FSparseSnapshotTree.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 032A4184AEB5DEA1C6084C79403BAE15 /* FIRGetProjectConfigResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 64EB27157BEA9B6EBFBC9D30A55480BE /* FIRGetProjectConfigResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 038F9D42B1874E7571006B01D193236A /* FIRComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = 03232B0207F9B72BCA1F06FB31EAF211 /* FIRComponent.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 04C0284B8DDB1B5AC6778E52655985B5 /* FTreeSortedDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = 160B2A098D6BE7E4FB1B11DD186189BB /* FTreeSortedDictionary.m */; }; + 04D1E6C33139E1AF51B425DF61C3102E /* FValueIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = 27D9867266FC937A80456C5B2C28AF13 /* FValueIndex.m */; }; + 05B6D642BDBCB1168280F41EF68EA73E /* FChildChangeAccumulator.m in Sources */ = {isa = PBXBuildFile; fileRef = 4AEF839E0EBB783AE6036DF684293321 /* FChildChangeAccumulator.m */; }; + 0933B8143BA9B7E6C7D01554FCAF47CE /* FIROptionsInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = AD7412CA4B83C16AF5D10344627F2226 /* FIROptionsInternal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 095B92373278C10C8A3B1F4A1F73A2B3 /* FIRVerifyCustomTokenRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = D37225295D40A9C051F75D0BC81405E1 /* FIRVerifyCustomTokenRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 098D39DE9C26B96FF172AB259D640933 /* skiplist.h in Headers */ = {isa = PBXBuildFile; fileRef = E53EA631D6B0E9EEA7B2FADB660D1EEA /* skiplist.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 09C7FC923342D1439EFEC22810BA44D0 /* NSError+FIRMessaging.h in Headers */ = {isa = PBXBuildFile; fileRef = 8FA1D93D5FF3EDB8C2273A0FC52FDD92 /* NSError+FIRMessaging.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0A0160BC832D6FF67F17DA09C069069B /* FIRStorageTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 880603C3679A606EFFF7E1252ED39621 /* FIRStorageTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0A4C5C81804C50CBDF57EF842DE97ED0 /* nanopb-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2810E3E1AC8BFA36AB5702CEF85BEE34 /* nanopb-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0A6FB62F43961D9D35D2867BB2105AB7 /* coding.cc in Sources */ = {isa = PBXBuildFile; fileRef = 2120AEB3891B803C5271166BBAB0F0A5 /* coding.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 0B21E5E6E330CDE16FFDDD34F8019159 /* FIRGoogleAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 6CBEB890F1BD0F79AC3D8CE936C581EE /* FIRGoogleAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0BA4942A6786CA873CC79CCF36D9DA7A /* FIRCoreConfigurable.h in Headers */ = {isa = PBXBuildFile; fileRef = 36D45A7FA49317344BF019A206D17B1E /* FIRCoreConfigurable.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 0BB00BA9640DB56A47581FF4BA450A91 /* GPBRuntimeTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = D6BB61D1DB5D35D8FCF2FAC65BB2D959 /* GPBRuntimeTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0BBD78F0EFC19D7ADA110339ECCCBE66 /* FIRDependency.m in Sources */ = {isa = PBXBuildFile; fileRef = 00A0CB9CA5B1E26BDE9D15F6F93F607F /* FIRDependency.m */; }; + 0BCF71114FA90D213BD09C4FCFBDACC7 /* version_edit.cc in Sources */ = {isa = PBXBuildFile; fileRef = 935886C7F3E7579A7743B85BFAB68601 /* version_edit.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 0BF462EC03EDCD8D42388A5AC89DA392 /* FIRDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = B2A3E3AFFA8F8C86271BA4D6C7F4C875 /* FIRDatabase.m */; }; + 0C01DD7C812E040851CB1CC9460D7395 /* FormValueCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B8BFBA5B3F70CF09022BCF57C36C70 /* FormValueCell.swift */; }; + 0C34B37D48EF02073D940540E2422EA8 /* FRepoManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 1645988A40396F6E30316B284BD585E5 /* FRepoManager.m */; }; + 0C9039605A7D3D5FDF983ABB650C79D3 /* FParsedUrl.h in Headers */ = {isa = PBXBuildFile; fileRef = 471881B25F65AC42DDD5CF446E5F8504 /* FParsedUrl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0CC702C8F99E23DE8D41425BFDD4240D /* FConnection.h in Headers */ = {isa = PBXBuildFile; fileRef = 3AD4D1243F862167904648922BDAE04D /* FConnection.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0CD1DDB7D4CBEEEB3A9ED1782F27822A /* FIRMessagingSyncMessageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 92DCCD218678B124254F507D53D566A5 /* FIRMessagingSyncMessageManager.m */; }; + 0D611A6D1BA11199662FCA250FFF8CF4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 0D87C3509B6F6D2FE145F8D87165F4F2 /* FIRMessagingRegistrar.m in Sources */ = {isa = PBXBuildFile; fileRef = 5BB790ABECC5AB46EEC32C04E1E3DE9D /* FIRMessagingRegistrar.m */; }; + 0DA255473FD9473B5FBFC73EC16165A7 /* FIRStorageTokenAuthorizer.h in Headers */ = {isa = PBXBuildFile; fileRef = 379E5B5FBE6395CCCDF717529007F6C8 /* FIRStorageTokenAuthorizer.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0DF749F7328C60E4278B1239EC1723A3 /* FIRPhoneAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 2FE952393E91F78CAE5094FFA1EBBA52 /* FIRPhoneAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0DFC6F43F874D2811BECEB7FDB15CC44 /* FIRMutableData.m in Sources */ = {isa = PBXBuildFile; fileRef = 1458408B7F7426DFEC2029E33DB82575 /* FIRMutableData.m */; }; + 0E35A626E81D71D3E50DF441EE4F64C6 /* dbformat.h in Headers */ = {isa = PBXBuildFile; fileRef = 52DDE7C94F2CFD1F4B7D89EAD53BDA16 /* dbformat.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0E44BBAFC10FC09254CCE56198907BC0 /* port_example.h in Headers */ = {isa = PBXBuildFile; fileRef = 484F43D7839874BA43FC7287627443B2 /* port_example.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0E75CBCE786C601A95861E47EFE43715 /* two_level_iterator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 68676BA36D0C984D720E7033B11A06E5 /* two_level_iterator.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 0EA5E387DB55D1696950CF955C845EE5 /* FOverwrite.m in Sources */ = {isa = PBXBuildFile; fileRef = D5FA71E496F7AA410D948D768C02A01C /* FOverwrite.m */; }; + 0EBFA9CC46A6D7AE5E8789A4A46D3464 /* GPBUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 95C84D68BD7EE91EDBA35DD0F59B13E2 /* GPBUtilities.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 0EF1FF5F99EE2A59390ECCBD150F9B2F /* FIRComponentContainerInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = EDB380628BB6381119D18060E3B1363C /* FIRComponentContainerInternal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 0F96D1FE9E7489E5AB0F86B88CBE287D /* FIRResetPasswordResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 19DE6E8E7B6B1372BCE4CC0AAB53C3AC /* FIRResetPasswordResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0FED15ECB6105F4BFF5D25CCE3C9187F /* FIRAuthRequestConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = F838EB368C156DCBF33114DF3D43DF9B /* FIRAuthRequestConfiguration.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0FF066790A34A0E5FB53156289E72ED5 /* FIRAuth.h in Headers */ = {isa = PBXBuildFile; fileRef = 0239D1D4504BAE07E728075902DC1878 /* FIRAuth.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 103B007712D7064A80989956B39C24F9 /* version_set.cc in Sources */ = {isa = PBXBuildFile; fileRef = 94934014090548D4B93291C3A35A43BA /* version_set.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 108AE1F200637096FD3EF529F95E8826 /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 501C43E7B305FE3D8E1CDC5276D26E98 /* Empty.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 113D9C1ABD48861DCDD18601A45FF94D /* FIRLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = A386A5F444120EBDA11F9BF76D51E331 /* FIRLogger.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 1142CEB92FD7C6973C88BFF238734F0D /* GULAppEnvironmentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 48F3B5DB6993BBECE9BD46E853AB5B02 /* GULAppEnvironmentUtil.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 11A6111284FE6C233703C63342B7EC9E /* GULNetworkConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = A70BEAFA51CAAA238419AD526C3A2A20 /* GULNetworkConstants.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 1214F2AD192C812AAFB9DF123B1BD468 /* FIREmailPasswordAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D8E3F4071E80D79F82FA3705A1B7D05 /* FIREmailPasswordAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1288967993058DD01F2D4C9C6748467C /* FSRWebSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 919BAE70A809B028A03EE6536029F65C /* FSRWebSocket.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 129D0B6856747307C78384677F0EA9A8 /* FormDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E31C3BDBFCEDEA18A1165D42EB6C7D4 /* FormDescriptor.swift */; }; + 12A87352FBA9C701F1DE64327348E88B /* log_reader.h in Headers */ = {isa = PBXBuildFile; fileRef = 32549BEEF6A49D7F0A9E0210E5889C34 /* log_reader.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 12B88AB4B994635043A01E9CAAC78CFA /* FIndexedFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 070A02016BB493B1197A81FFEACCC360 /* FIndexedFilter.m */; }; + 131D1E3ED0BA8A75817D5A9D7A5BD9E4 /* FIRMessagingConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = CD5261ED7894617F948B8217A7A98098 /* FIRMessagingConnection.m */; }; + 134B54AFE31E2FA28DFE3E62CCBCB5E8 /* FormTextFieldCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B5056278F8531591B36DB9DB2654F5D /* FormTextFieldCell.swift */; }; + 13537D802C50BE4E1351903E9A85CD38 /* FEmptyNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 43CFD5E85EB4EFD2F6AB4506880B8332 /* FEmptyNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 13B7E538A0B31929B6940CC11AF2D3DD /* FIRVerifyClientResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = D18CEA84295910BAB47D481FA1692F0D /* FIRVerifyClientResponse.m */; }; + 13B9008DAA3745EC8EC09C2058ADF32C /* FAuthTokenProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 693C9B5BD6AC380C76B3E002A24AC9F5 /* FAuthTokenProvider.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1407E6CE7062308AA0AD23777CE4BFF8 /* FIRPhoneAuthCredential_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 33865930EE20D6BBB99E16994933D2BE /* FIRPhoneAuthCredential_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1430115FF4C5E3993B9CD7178956D80E /* FirebaseDatabase-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C08FC41A4A7E8D144554D360A843190E /* FirebaseDatabase-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 146B6E3071A34E0CE9E70DE8F3A24A4C /* FIRAuthTokenResult_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 35C0A0B5A99461EBCFD376962B2F5C0D /* FIRAuthTokenResult_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1493703C0821CA137EA4FF9D4610B992 /* FIRCreateAuthURIResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 12A5C3A9A8DA7A2944A508E1378B93B1 /* FIRCreateAuthURIResponse.m */; }; + 157ADD76801911EB580A646FC171A1B0 /* FirebaseAuth-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C4B963BE88DF9BAD70BB2577285B94FA /* FirebaseAuth-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 15D82D0D27D718FEDA039C5A056BA0A7 /* GPBUnknownFieldSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 390DD1B08C74A9F68476B754216839F8 /* GPBUnknownFieldSet.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 168F962D694946E2CD87CF2C579C02F4 /* GPBUnknownFieldSet.h in Headers */ = {isa = PBXBuildFile; fileRef = EC2F40DC4BABBA1C34D6609803FED9F1 /* GPBUnknownFieldSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 16FC08D09F195371ED8C012975BA4B31 /* FLLRBEmptyNode.h in Headers */ = {isa = PBXBuildFile; fileRef = C9ADC47D30FF0AAF24724A272E5DEBE8 /* FLLRBEmptyNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 17076EA730EE24E55BAE34DD6E396981 /* coding.h in Headers */ = {isa = PBXBuildFile; fileRef = E0F5DF31EC2E62475823F5669748B32A /* coding.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 175DA115BFD549B441954D52D8AAAC64 /* GULLoggerCodes.h in Headers */ = {isa = PBXBuildFile; fileRef = E6ADDAD8E70600449B60E0A2A6A84AA6 /* GULLoggerCodes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 17CB0ABF89CAAAB627292A00AA3529A4 /* FIRAuthGlobalWorkQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 386373BFF6E630E359797C1A82AB1070 /* FIRAuthGlobalWorkQueue.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 181D017519ED05CC259043741928943C /* FIRAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 58DAD62A1384B6C2202497AAECD4FEF9 /* FIRAuthCredential.m */; }; + 1827E4B261CF18BAD9BAB4A23F31E33A /* SourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 9F79D0ADD782AC78C79D540D0AB8B9EB /* SourceContext.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 1837B48509DD924AEB4F9AF8F374F019 /* FIndexedNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 68EDBB86127032AD3CCD427465F5057A /* FIndexedNode.m */; }; + 18F2A93904BE47E327F6772BC92391EE /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 968C73940E1B097EF26967FA1146655A /* Timestamp.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 18FC768873FF702F8DB65711690D44B8 /* FormSelector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7C14FEC5F42750CFF7801E2502AA30 /* FormSelector.swift */; }; + 1906CE819DDF2BA7989489B4B6D70313 /* FIRStorageErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 338F8FAD90ACCD0679A61D9BF3376DAB /* FIRStorageErrors.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 199B7124BD04C34D3152530AF2E35F1D /* FirebaseDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 4316D686D98DA93A0ADDA9AB857CCFEB /* FirebaseDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 19E00149B83420B657999688A62BCC38 /* FIRMessagingPendingTopicsList.h in Headers */ = {isa = PBXBuildFile; fileRef = ADFB0C91FF0A24C4F22AC190030E4908 /* FIRMessagingPendingTopicsList.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1A4E6AEEB9E0813B460A54A99A2FBC2C /* FRangeMerge.h in Headers */ = {isa = PBXBuildFile; fileRef = 39A633CD466937034BA28BBFAC639020 /* FRangeMerge.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1A8227B02B0D98E83CECC24E8373F9B5 /* FIRVerifyCustomTokenResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 68AB70689ECD68BDF9F973D46450CA1F /* FIRVerifyCustomTokenResponse.m */; }; + 1AA4FEE4489E142E7CC8BACE93717E53 /* FIRDeleteAccountRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 389D2E096B89ACC945F9139E64B99063 /* FIRDeleteAccountRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1B53A90973A83551E91EBC14158FBDFE /* FIRMessagingReceiver.h in Headers */ = {isa = PBXBuildFile; fileRef = FFD573F1AB574F736E72462CA185FF02 /* FIRMessagingReceiver.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1B911D16F99091B023C6540EA1D32429 /* FormSegmentedControlCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1371CB007C4703ADBB046374DD799D44 /* FormSegmentedControlCell.swift */; }; + 1BB86F06F8AAE20B17524BB5294D0592 /* FIRStorageTask_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = CE58A9D71591B0BDA8F839EF6D8E13F8 /* FIRStorageTask_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1BD022E15D93903A246A7B62D9F45CE7 /* FIRDatabaseConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = EC5CE6854B764CF987743F870A9DD509 /* FIRDatabaseConfig.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1BDAB2FEFFFF8CE4DAA690ED3293D1E9 /* FIRAuthURLPresenter.m in Sources */ = {isa = PBXBuildFile; fileRef = BA3EDB47D8082026DB6188D3030E770B /* FIRAuthURLPresenter.m */; }; + 1C13280129B885038A3834521227F59F /* atomic_pointer.h in Headers */ = {isa = PBXBuildFile; fileRef = 33210CB84E7E2EA9F5357F167D658407 /* atomic_pointer.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1C3E3391EF8586FB2143ACAF7B1566CF /* arena.h in Headers */ = {isa = PBXBuildFile; fileRef = D17AC93D8B3ED45BD0F5116710A62D29 /* arena.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1C9B3629CD3832E8A80E399A9092C67B /* GPBDictionary_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 5FB080F12F054F57F892AECEA7DFEE41 /* GPBDictionary_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1CC2CDE924AE5455F04D90BB06D7A0DA /* FIRMessagingContextManagerService.h in Headers */ = {isa = PBXBuildFile; fileRef = 90CAF6C078AC9FA0DDDF5AF785F595F4 /* FIRMessagingContextManagerService.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1CFA298A847AA9B4CECCA93F2F85DE1B /* FChange.h in Headers */ = {isa = PBXBuildFile; fileRef = 342B0B60E0420CB2ADAE937A53F52CEC /* FChange.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1D0568C93F531DD88D40C1D41F3104F2 /* GULAppDelegateSwizzler_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 9DBFB549CA0840AFD4B56E933019DF0A /* GULAppDelegateSwizzler_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1D88B103F90AC866D7DFE9B729D62F9E /* filter_block.cc in Sources */ = {isa = PBXBuildFile; fileRef = E09ECF63E89195F26D272FC3BD8C7044 /* filter_block.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 1E1F2D849C58DEE61BEC26F3E5D18428 /* FIRPhoneAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 29343B35E5F2B0EFA39F218482ACB0CB /* FIRPhoneAuthProvider.m */; }; + 1E35F6BFC09BD06406C29176322A6C61 /* FIRStorageReference.h in Headers */ = {isa = PBXBuildFile; fileRef = CDDE3270485F6BA958F0E5A5253C05C9 /* FIRStorageReference.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1EF5C377ECDD43466DE5D1046392982B /* FIRMessagingUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 51B29CF73AD215059BC28D3753ECE814 /* FIRMessagingUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1F411F60AC433B7A8CF2AD16BB33548D /* FLevelDBStorageEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B62BAF73F96F237E93C91E8FDE1A124 /* FLevelDBStorageEngine.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1F5C01F68004EE6E9652798667250024 /* FSyncTree.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BB0171D3D054B9A887BDABC219FDED3 /* FSyncTree.m */; }; + 1FDCEB6A40916796A1FBC79CD126FD23 /* FTypedefs.h in Headers */ = {isa = PBXBuildFile; fileRef = BC4A443A1DF1810B7A9803C462DADFEB /* FTypedefs.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 204A5511FB6690E4F1831E36524FF7E6 /* FTreeSortedDictionaryEnumerator.h in Headers */ = {isa = PBXBuildFile; fileRef = 78440266C0C83884693EF81EF27A2251 /* FTreeSortedDictionaryEnumerator.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 209B69B53B2BB5A3C90A8A4B78AA795C /* FQuerySpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AD846363197EE2C3BD4CA30EC8D8C44 /* FQuerySpec.m */; }; + 20D2F5063CB675E0C06A42363149F916 /* FIRGetOOBConfirmationCodeRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 248D6396DD17D8431F0B3A31293DBA66 /* FIRGetOOBConfirmationCodeRequest.m */; }; + 20E481DB22BC2EEF19A3665138F52A43 /* FIRMessagingRemoteNotificationsProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 26D0C49266BF657CB1AF5A18E8F591DB /* FIRMessagingRemoteNotificationsProxy.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 20E6EA2D2351FC5C0694846164D50BDB /* GPBWellKnownTypes.m in Sources */ = {isa = PBXBuildFile; fileRef = 1175E03AEA34F51B8C8D46A8448670C0 /* GPBWellKnownTypes.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 20EF9D10AB576BC24251E96085D7F62E /* GULNetwork.h in Headers */ = {isa = PBXBuildFile; fileRef = 8762AF452D56EBD17C7FA8105C46E226 /* GULNetwork.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 21842223F770DB476AFE71048612A2E6 /* FIRApp.m in Sources */ = {isa = PBXBuildFile; fileRef = DA833CB65907D992C5524A7B7E0E8342 /* FIRApp.m */; }; + 218670777B0EE4D273341CF28057FC15 /* Pods-My MindUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 42561C54B242579DF60913AD632DCB9D /* Pods-My MindUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 21C6416C31381FB9A488704B9630974C /* GULLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = BE94296B133418A27910B00D5294FF16 /* GULLogger.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 21FB0279FB718F75BA6BF98940DE1583 /* FirebaseCore-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 682FB182ED2813B933EC052FF4298A6F /* FirebaseCore-dummy.m */; }; + 221F3C7C12FC8F748753545E4962BE80 /* FIRGitHubAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = A82B173D007A576E78AC1896EC794E94 /* FIRGitHubAuthCredential.m */; }; + 22419CF604E5F4E71B191A573477E765 /* GPBCodedOutputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 54A71EF90151DC4A91CDE20EBE275C1C /* GPBCodedOutputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 225738FCD97CAC58948F5C69D6EAD994 /* FKeyIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = 6BA5FFAECDA46681242C8C8C12B8DF75 /* FKeyIndex.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 233B83B7F18D89E2529AA35E16AECC0B /* FCacheNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 15436BAF73F24A26CBCCCE13B2C7A5D5 /* FCacheNode.m */; }; + 239677F29755CB7B79AAFD1DC0C0BE21 /* FIRAdditionalUserInfo_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 446370E4A06E1F0DF2205B16D666D0AD /* FIRAdditionalUserInfo_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 23BEFE2651CBC5E150DE1F05D090F45A /* FTransformedEnumerator.m in Sources */ = {isa = PBXBuildFile; fileRef = 28C219F26C922F496FB2CDC879FA9079 /* FTransformedEnumerator.m */; }; + 242FE609A5EDD5ED5E277D18691D773C /* FImmutableSortedSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 07084E38FA564A667FC64E1BA854553D /* FImmutableSortedSet.m */; }; + 2453BE02814DD5B74DBC558A2987C561 /* FirebaseAuth.h in Headers */ = {isa = PBXBuildFile; fileRef = FA90962585855F75431533CD68E4E496 /* FirebaseAuth.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 245636798D7598BEC4AC14A8C3F59195 /* FServerValues.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E654E9A462330D3F03252E972E0DD93 /* FServerValues.m */; }; + 245C416D912CB79A158CE6C0BBA5709C /* FChildrenNode.h in Headers */ = {isa = PBXBuildFile; fileRef = BD4117C893A97D98EE31E12226EB41F9 /* FChildrenNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 24C421100ECFE5936F377CA9005BC9F4 /* FKeepSyncedEventRegistration.m in Sources */ = {isa = PBXBuildFile; fileRef = 080DC43BFB3FA09A4DD2E260312C57F2 /* FKeepSyncedEventRegistration.m */; }; + 25149580AEC71D7F9773870BBD217ACA /* FListenProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E2BB3682A63E5E8457BE4392979C216 /* FListenProvider.m */; }; + 25BD5A9E2BB1FB1B4516291C971ACD0C /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB57BCF1E73C7B8A4B2CAE6F512FB8A5 /* SystemConfiguration.framework */; }; + 25E17FDF9EC685B33382856C071EFB2B /* FIRMessagingAnalytics.m in Sources */ = {isa = PBXBuildFile; fileRef = 8045F511732AF21BD969650BBDB79264 /* FIRMessagingAnalytics.m */; }; + 25E2893DF36B4A33430D1644D82D6511 /* FIRAuthWebUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 5E7945D06F7A9490E3DFDF843C010E48 /* FIRAuthWebUtils.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 260F8F5BECA192212B30CBAD2B769318 /* FIRMessagingPersistentSyncMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = A7C4DF6F92826595F2A84D72365B5505 /* FIRMessagingPersistentSyncMessage.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 261A729A04060A4BD9FE7A598E7DA6B6 /* FChildChangeAccumulator.h in Headers */ = {isa = PBXBuildFile; fileRef = A69039FCDFBA2D22C1736491CC27B108 /* FChildChangeAccumulator.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2681467B53A9411E0F36DCA09C46FF84 /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 31C4337E4E578887B076F5E47A449DCE /* Api.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 2708BCEE56FB1ACEFF6608A821C20962 /* FIRStorageDownloadTask.h in Headers */ = {isa = PBXBuildFile; fileRef = CD292B336F5C12C67D9382555FB39F84 /* FIRStorageDownloadTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 275030A0CA31B8AE5264A0C7EBDDDEC6 /* block.cc in Sources */ = {isa = PBXBuildFile; fileRef = 75F85C975C09185C0E84A04DA191DF1A /* block.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 27C4FCE0C3EBCD347685FE38B934F608 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E17134467E8954E9AF37025460CAB049 /* Security.framework */; }; + 27D03B988D6269D5BB0099E89EB85EFB /* GPBUnknownField.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A3FD15082F1A9ABE77ED609F0DFF1CB /* GPBUnknownField.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 282648B588909BEEB93E033E2A7443A4 /* logging.cc in Sources */ = {isa = PBXBuildFile; fileRef = 48B55CE7E259B813481B4F6DC1EDA605 /* logging.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 2830CF875793D7780A11081310937635 /* FIRVerifyCustomTokenRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 365E83317995CD7525ED8911984FA695 /* FIRVerifyCustomTokenRequest.m */; }; + 283F5343FDCC1331A387D87617651F19 /* FieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 89F5B99A9E0786C553D21D862D2B5827 /* FieldMask.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 2845EFC8CEFA1BBBAA5A84F48525909E /* FView.m in Sources */ = {isa = PBXBuildFile; fileRef = 52989DBD560D819C3DAE5CD912033DD8 /* FView.m */; }; + 286EF599E7C3659EE0EB0929BAF9C43F /* FIRAuthWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = FE9E27ABE098D998E78AD75EBBA7544F /* FIRAuthWebView.m */; }; + 28DB01DD6197B670D9B130A13F94C658 /* fbase64.c in Sources */ = {isa = PBXBuildFile; fileRef = 5E738E7BF1FBC0B364B61BD03515B68F /* fbase64.c */; }; + 290511839CF8EC8F00D125AE26FE9282 /* FIRAuthAppCredentialManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 366FDECE49AF8E55FF1E41E5B8D8A099 /* FIRAuthAppCredentialManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 291689F2D49EF325CEE2B90FF45A455F /* snapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = E9ABDE6BBA1A94C280712138E8C978C7 /* snapshot.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 292EA27E39216AE851ED7F5AF1F3572F /* FTrackedQuery.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C931CB859E88BFAED40B1C16793FB9A /* FTrackedQuery.m */; }; + 2998970FE1A48BFB569225CF4642EE05 /* APLevelDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 5A78F386367CAE629EB35C78D895997D /* APLevelDB.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 299A3A3BEAF3D0864955CA19E44C03A8 /* FConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = B462ABAEB07A7435FB7510B120702773 /* FConstants.m */; }; + 29F9CCFDD78C5672F24E811CD3B0E2F4 /* FIRLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = F647C20117821F0CBC11B9D07F881E2E /* FIRLogger.m */; }; + 2AC4DDC97C6C03DD5E1FB6ABC99A70A7 /* FIRAuthAPNSToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 50D69B40CB7B6EE788D4ED8121EE5627 /* FIRAuthAPNSToken.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2ADFE23A360FDEA4354624A928476953 /* FIRMessagingSecureSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 736C022A06E3955768DC6544360A723E /* FIRMessagingSecureSocket.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2B0EB7AD0CE60D98D92D569E3FFCE97F /* FTupleTSN.m in Sources */ = {isa = PBXBuildFile; fileRef = 38121C21810D6FCA9108041FC4F8FEDA /* FTupleTSN.m */; }; + 2B8C51B8B260D2DF686041D4A040B8B6 /* FIRMessagingDelayedMessageQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 65353A37CF47A6651F323694730E2BC7 /* FIRMessagingDelayedMessageQueue.m */; }; + 2B8D115E3E217504C48E7FA4FC0EDA21 /* options.h in Headers */ = {isa = PBXBuildFile; fileRef = 069EEE870762C0F433A706FFB665A283 /* options.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2C8913832BC7EBA24435CB2D582F142F /* FIRUserInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = C6D1B26A950547F59D7E738E2C779092 /* FIRUserInfo.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2CB575E4C500A3E3F74B4B45B527AA15 /* FIREmailLinkSignInRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = B4DCF5F9A05116C8E5BEB7E4672C77F0 /* FIREmailLinkSignInRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2CF6B039692393B64EFF5E324CE42D4A /* GTMSessionFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C94FF97478A1FE3BF81F60237C1B74C /* GTMSessionFetcher.m */; }; + 2D02C1023D85C1462E5A83DD9AEE07CF /* FIRNoopAuthTokenProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = A383681CA86AE1040605A9AA1AE4E78D /* FIRNoopAuthTokenProvider.m */; }; + 2D2C6D574E05173015E9564AF9EB5BFC /* hash.cc in Sources */ = {isa = PBXBuildFile; fileRef = 11018727FC836C957AB749559F7845ED /* hash.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 2D416CF9647A1D41764FC0B641EC3680 /* FormLabelCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E95E3219504D83CD57E912728E959D3 /* FormLabelCell.swift */; }; + 2DAE9E974339ECC5237F52641C71959E /* FIRMessagingTopicsCommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B5BD339D6126E58145A91C670A79B57 /* FIRMessagingTopicsCommon.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2DBB5514F29F5829C5AE527F6E4FDA05 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 2DE5C6BFD8C35D3343A840DFC3CD718B /* FIRAuthExceptionUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AF6DE6416DB4C133F69C73FA0A99C96 /* FIRAuthExceptionUtils.m */; }; + 2E9C9C5138F8FC9593825B2FE0B115D4 /* FIRSecureTokenRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4879E1F0A6D1768BFA268E9A80030B20 /* FIRSecureTokenRequest.m */; }; + 2EFF484EE070D8D5ADFA763EE9AA7A25 /* GPBMessage_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D031DF463461821CD42F1C393E912D7 /* GPBMessage_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2F1272ED0F06E548CF4C7B00A695B4D1 /* FIRAuthAppCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = C892A85A358C20C1C99EDA725170E12E /* FIRAuthAppCredential.m */; }; + 2F7ED73B8E278D8E2567BAB379F45E29 /* FormSelectorCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D054DB817811112B3951BAA5516B85 /* FormSelectorCell.swift */; }; + 2FE3E801B2DAC1823806BAFC895D0198 /* FChildrenNode.m in Sources */ = {isa = PBXBuildFile; fileRef = DC9B8460FA63820AFA6854A35DA829C6 /* FChildrenNode.m */; }; + 301398C5A141B873CFFFC2BC58D9554E /* leveldb-library-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DEEA04A7AF313BCFBBB48A30AA8E1EF3 /* leveldb-library-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30AEA30323297A18293A0E09E7301849 /* FQueryParams.h in Headers */ = {isa = PBXBuildFile; fileRef = 4AE4970E0E898EB674A647B25B6DBD64 /* FQueryParams.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 31010EF42D84A135C1CB0E1B39A43E4D /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C24FC54E82667CD883433C507452C248 /* MobileCoreServices.framework */; }; + 315787FF4CC7A8C3020173EAA4957447 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 31CE24A1215D3B4FC23D539976017CF5 /* FIRDataEventType.h in Headers */ = {isa = PBXBuildFile; fileRef = 0933AC24273A3B8D18961DB556CCFFED /* FIRDataEventType.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 323478A277D2734E5E5A1AC46E3EDD10 /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = C5D5E994D8F0EFDF52C43C5BA09B95A2 /* GPBExtensionInternals.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 325607B89D32DD326199802A96BA7FDC /* block.h in Headers */ = {isa = PBXBuildFile; fileRef = 0CA1BD6CB3A1AE01107FD8F8FDCA3D2E /* block.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 32CC39E48764CA3467393DCEF2151A08 /* FIRDatabaseReference_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C67A508BEE66D05F3D060B80EB08B92 /* FIRDatabaseReference_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 32E6AFBABCDED50BD6674ADBF424A37E /* table_cache.cc in Sources */ = {isa = PBXBuildFile; fileRef = AB16085037ACA0EF2DB981B3C7993C4E /* table_cache.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 33153F8D6F74310F412A8F8916D03CEE /* GPBUtilities_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E26ACE066B49256AB80223CB1785409 /* GPBUtilities_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 33DB72BBA56DA8E1C805ED2E2E4B54F2 /* FIRStorageGetMetadataTask.m in Sources */ = {isa = PBXBuildFile; fileRef = D56EDA2992910A82DF34AF0EDB0669B2 /* FIRStorageGetMetadataTask.m */; }; + 340AF0D010C3FBE18AC80F6970AA75A4 /* Api.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 05DE1CCF193E0BF6A385C79D1F31920F /* Api.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34142FD524815DEABD01ACF275DA650A /* FIRVerifyPhoneNumberRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 52DFF27FBBEDFDB18FA44BEAD7283C38 /* FIRVerifyPhoneNumberRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 348369D5DA54EAB1F012E5CF19D8B977 /* FormStepperCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF98451C4B15976BDA23D038EBF6A0EC /* FormStepperCell.swift */; }; + 349FEA4C6FDAB3C48BED3982115746D0 /* fbase64.h in Headers */ = {isa = PBXBuildFile; fileRef = 0C5EAA248DD28CE7903CF85278DCF244 /* fbase64.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 352E9C87F64C84CB7C0A6822544063AB /* FTupleStringNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 2C6CDE0E1371445EF3780F7C3AF3CA55 /* FTupleStringNode.m */; }; + 354F3E70D371F81CBE9E65D860DD86DA /* GPBRootObject.h in Headers */ = {isa = PBXBuildFile; fileRef = 34A437CCB33E71BF0316EE12908859A5 /* GPBRootObject.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3552218D2E421ECA1909B93DE2FB959A /* pb_common.c in Sources */ = {isa = PBXBuildFile; fileRef = AAD8583A56D06F8B53175D035AF9D864 /* pb_common.c */; settings = {COMPILER_FLAGS = "-fno-objc-arc -fno-objc-arc -fno-objc-arc"; }; }; + 3576DF3E4D39649AB921933ABB67E18D /* FRepoInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = D940987A9FD15F075D87E6F596C88350 /* FRepoInfo.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3618415B8ADA597762A024D5B7A425BA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 36312D21067D49E3BDAAE12074705FF4 /* FViewProcessor.m in Sources */ = {isa = PBXBuildFile; fileRef = 757B37187411893E58EA0016D7EA32AD /* FViewProcessor.m */; }; + 36A05411E4D438C3DA2E581DF59F0849 /* FIRAuthAppCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 2A48BB8A8D3B8F2F32F334BD438F45DA /* FIRAuthAppCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 36B8264FD3ADAC365EF136BEE736C2D3 /* FImmutableSortedSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCF7C96D9FF6B74D1BB5DD455A95B971 /* FImmutableSortedSet.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 37778510DDB7DD80291094F60C9C8F23 /* FTupleBoolBlock.m in Sources */ = {isa = PBXBuildFile; fileRef = 47E32935FDCB1ACFE19F4A621AA5D7AF /* FTupleBoolBlock.m */; }; + 378285C697294CA4BD74927E4D4CFE43 /* FIRVerifyPasswordRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = D5863210436D92737B63B73087F63968 /* FIRVerifyPasswordRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3854182705A3B78779D0647C64563A5C /* FIRStorageTaskSnapshot.m in Sources */ = {isa = PBXBuildFile; fileRef = 904EFB6F9F30701EA342E10A83813F45 /* FIRStorageTaskSnapshot.m */; }; + 391CCF70D8CC77B7086E64C34809FFCE /* FIRAuthDefaultUIDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = FC900162842DCBE91B0D3CE747B548A0 /* FIRAuthDefaultUIDelegate.m */; }; + 392995C8A9ED047B31DB8591BBEED101 /* FIRMessagingRmq2PersistentStore.h in Headers */ = {isa = PBXBuildFile; fileRef = A950F6251ACB2BC29B9B91DFD2DE3CFD /* FIRMessagingRmq2PersistentStore.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3A6ECB640C1ED73B97C6E905515A88AC /* NSDictionary+FIRMessaging.h in Headers */ = {isa = PBXBuildFile; fileRef = BDE06C7169B511B43A4220DCCA6B9012 /* NSDictionary+FIRMessaging.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3A808D849F138AA9661808DA3A132E80 /* FIRDatabase_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = B9B72DC800D477FEA2AC16E17CC60AE1 /* FIRDatabase_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3AB59DB71D3090FADB8183AE459C74CA /* FIRComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = 43C51F661E1732A453C8FF3CC41FE99B /* FIRComponent.m */; }; + 3AE2C846212FDE3A0D35AEBD9634F435 /* table.h in Headers */ = {isa = PBXBuildFile; fileRef = CC6154B7CE684A1970FFE54F20E8392F /* table.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3AED228769079FB813068D1107E25600 /* Duration.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = AEDB6F9859D5D740703FECC548FF4DB1 /* Duration.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3B08F067675402CD040A3B50963BB89C /* FIRSignInWithGameCenterResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = AA4C3D674727250939C11F0687171F23 /* FIRSignInWithGameCenterResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3B15CBA64BA1D735A7B945E03414E057 /* FNextPushId.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C9B5809B81588128804C82CC7C0A448 /* FNextPushId.m */; }; + 3B1B26729BC1D60B397D5DBC08BD35B9 /* FWriteRecord.h in Headers */ = {isa = PBXBuildFile; fileRef = A8679585BD7F5289E37359EA461A0848 /* FWriteRecord.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3B4D5805A6152892B36CFEC08FF30F82 /* FIRTwitterAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 05E0E3991A44C3DB0537924A5B2482D6 /* FIRTwitterAuthCredential.m */; }; + 3BAF57213FACE87FE0C29899BED430B2 /* GULAppDelegateSwizzler.h in Headers */ = {isa = PBXBuildFile; fileRef = ACB3D17DA57ABABF8DEFB9172C36AF43 /* GULAppDelegateSwizzler.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 3BCBDCDEE41BEB8D092EF0F443C31939 /* log_format.h in Headers */ = {isa = PBXBuildFile; fileRef = 62B3DC5F0A104BF4ACF3B85C55D99BC4 /* log_format.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3BD76326DB9C201D468A25CE8FA76385 /* FIRStorageComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = F6B33E27089631C018426D12DE3BF2B1 /* FIRStorageComponent.m */; }; + 3C1068790CF9D585AD77DF3E1315A0CE /* FIRStoragePath.m in Sources */ = {isa = PBXBuildFile; fileRef = 2D9B0086B87D0C228A92B242FCD33B3C /* FIRStoragePath.m */; }; + 3C27259E4A251B723DB260F8E8B093C2 /* GPBCodedInputStream_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 13E8E20280A59FBF3E16ABB61C7F1857 /* GPBCodedInputStream_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C63E9595463B8F3754AAE476EAFF25A /* Timestamp.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = B4288F3CD86EF1B904C5B60FF214940B /* Timestamp.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C7F3BFB04BFF90E6FCCCC736BA094EC /* FIRAuthSerialTaskQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 44009DA6BD52A71E123946AA1B2A1CCC /* FIRAuthSerialTaskQueue.m */; }; + 3C864CBB8AF42464DE35B28C4EB51D03 /* FIRMessaging_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A2649CC5725FA949A3D54FB633180B6 /* FIRMessaging_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3CAE8FEFEB344131C119530AFA591C69 /* port_posix_sse.cc in Sources */ = {isa = PBXBuildFile; fileRef = 2EC536F0C78D7F592760BB1B26CEE026 /* port_posix_sse.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 3CBB46EE875BF2548D6A79249CBDF4E6 /* FSyncPoint.h in Headers */ = {isa = PBXBuildFile; fileRef = BDA8D286B82FAEEDBA4BB4A834E41412 /* FSyncPoint.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3CBF93EAA1696DDB4018A4C62F998BAD /* GULAppDelegateSwizzler.m in Sources */ = {isa = PBXBuildFile; fileRef = 938DFBB9348CD99AFF254CF39CF17698 /* GULAppDelegateSwizzler.m */; }; + 3CEAE8A4C8D8D58A5757E8E796EF3B53 /* db_impl.cc in Sources */ = {isa = PBXBuildFile; fileRef = A60901D38929C0E04817F7B345B30999 /* db_impl.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 3DE16070D4BDD2E4BA4E2124D9888788 /* FCompleteChildSource.h in Headers */ = {isa = PBXBuildFile; fileRef = EEECFB49B1C1890C57ED844291FCAD69 /* FCompleteChildSource.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3DF871716311E62315A34CD7C8F9C33F /* FormViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B8615B87DA0E29530C8BE4B47E2D4FE /* FormViewController.swift */; }; + 3E8BE1FD810218E8619F39BF30938D66 /* FIRMessagingPubSub.m in Sources */ = {isa = PBXBuildFile; fileRef = 580D3A9DD3E77BC53E3D35F0023DDE1E /* FIRMessagingPubSub.m */; }; + 3EC4BE7BB60B0244BAFF076A8AE4433E /* FIRComponentType.m in Sources */ = {isa = PBXBuildFile; fileRef = C867367352BE84E57F50CB0AD6199922 /* FIRComponentType.m */; }; + 3F1CBF3B83300E405EC2DE2B6AE39D23 /* GTMSessionUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 42BC28884C5305F80E35B4E805480874 /* GTMSessionUploadFetcher.m */; }; + 3F3C9BDE53A474F9FC7F868981B2CEB6 /* FIRConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 0C387A89EF9BCFB1D9AEC1628A6FFB57 /* FIRConfiguration.m */; }; + 3F4A4BEAC4EA288A2EDD82306B56C489 /* Pods-My MindTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 95C32177E2BED1782D2001DFA1FF0550 /* Pods-My MindTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3F57A292C689577986C789440912ABB4 /* FIRSignUpNewUserRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = C2A917B7B3143CB35B45491393EFE099 /* FIRSignUpNewUserRequest.m */; }; + 3FDBCD14B143183DC6700C737B7D9A3A /* FNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 60DDA174CF0B3BB875E4D2CAF65B71EE /* FNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4054A9F1886D80E232E7F8A23BAC7723 /* status.h in Headers */ = {isa = PBXBuildFile; fileRef = A0FC5CBCA095CB6ADDF78AB6763964C3 /* status.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40EACB0ABE34F98A1888FCFF5BBD896C /* GPBUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = F80CC5E45B9D60B0D5733364ECA9F9DF /* GPBUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40EBFB526EFE2237051550143B403E77 /* FIRStorageTaskSnapshot_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 0EF8CB17A97DBCD11218204027BB21FD /* FIRStorageTaskSnapshot_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 416A7760890657DBACC2BF6F6E3242EB /* FIRStorage_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = BF633D289C9053169D2324C32B3F5AEE /* FIRStorage_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 42417A7D0D3025CE0CD3954A5180448D /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB57BCF1E73C7B8A4B2CAE6F512FB8A5 /* SystemConfiguration.framework */; }; + 426B07E572AE6BF3E73255E49A2AF5CE /* APLevelDB.mm in Sources */ = {isa = PBXBuildFile; fileRef = 02A902CB224C60C34D9D9D2D0E204BE4 /* APLevelDB.mm */; }; + 427395F3BCF94DD6BA4C6B8BE6637FA9 /* FTupleFirebase.m in Sources */ = {isa = PBXBuildFile; fileRef = 8DDFE81B108DE6221D7C65724942FB0F /* FTupleFirebase.m */; }; + 427799CB422851F585C02C74820C0463 /* pb_common.h in Headers */ = {isa = PBXBuildFile; fileRef = C0579785095D37C75777806A0548CD41 /* pb_common.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 42B789CC191942A3436F0FA69BCEE805 /* FOperationSource.m in Sources */ = {isa = PBXBuildFile; fileRef = C8C7086328E78F3238E42C4FFFF6C84D /* FOperationSource.m */; }; + 431A3EDD24915839AF1415F635EAD7BE /* FTypedefs_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 8D26ADA472AEBC9DE9C44BEB18259C0E /* FTypedefs_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 432117374790242BA5EDD0991F56DA2E /* FIRGetProjectConfigResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 83AA3E602C3A2961790AEAADF22D1659 /* FIRGetProjectConfigResponse.m */; }; + 43332954BA84B54F3F6B5DFBA2EB46AE /* FLLRBEmptyNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 09395751F30ACA695886327117B5E571 /* FLLRBEmptyNode.m */; }; + 434050B360E1A4F6AB30179C4625918A /* FIRMessagingAnalytics.h in Headers */ = {isa = PBXBuildFile; fileRef = 24C4C8F54426C9EFB4F6CEA3C77E8E45 /* FIRMessagingAnalytics.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 435E994C1DF537D573EF0434A08684D1 /* FirebaseAuthVersion.h in Headers */ = {isa = PBXBuildFile; fileRef = A9D4C247886677E0DE4667C1879C2A92 /* FirebaseAuthVersion.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 438954B88A790ADEE370D7ED0BDEBE3A /* env.cc in Sources */ = {isa = PBXBuildFile; fileRef = 250424226E3E1252246D83E4302FCF23 /* env.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 43E1FAA95D071540F70FAFDC5C4CC382 /* FIRAuthKeychain.h in Headers */ = {isa = PBXBuildFile; fileRef = C1D412970289721316660D54C69470C1 /* FIRAuthKeychain.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 43ED2695655E0A26CA8B1A8F6909512A /* FPendingPut.m in Sources */ = {isa = PBXBuildFile; fileRef = 34FF34F16BEF644F7E4BB840CB508AD2 /* FPendingPut.m */; }; + 453547D27DE8FE05B1E58BA16E43DFE8 /* FEmptyNode.m in Sources */ = {isa = PBXBuildFile; fileRef = AFD8CDB02D4D4C89C49C96F058E1B224 /* FEmptyNode.m */; }; + 457FDEBB956179777CBAF1347EA4836E /* FParsedUrl.m in Sources */ = {isa = PBXBuildFile; fileRef = 4775A6201BD2BC8E8E2FA8486EF330FB /* FParsedUrl.m */; }; + 45EC8A519B567D6E0D643253BBC6BD8C /* FIRStorageUpdateMetadataTask.h in Headers */ = {isa = PBXBuildFile; fileRef = BB4A6AB1B3EAD07AD843777C90166F83 /* FIRStorageUpdateMetadataTask.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4624A630AA3033609770704E8BD14B8A /* FView.h in Headers */ = {isa = PBXBuildFile; fileRef = 9D6AD1B68D19CD2237E034D672CD3455 /* FView.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 46E2E6FD4716F8A87899ABEDB1D0FFAB /* FIRErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B86C1FEFEAA44BF8471DF6A3B328BB /* FIRErrors.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 473FDAF90CFC14D382A966C4AEAFB148 /* FIRAuthWebView.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3D972C91B6D9FB1DE234EB59AB07A6 /* FIRAuthWebView.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4786208953DE313FDF22E414A560099D /* FSnapshotUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = A04D5EAB5D26B05C5CD5EED00FE954F5 /* FSnapshotUtilities.m */; }; + 47CBCEF5F276212C0C9B11722D45C78C /* FViewProcessor.h in Headers */ = {isa = PBXBuildFile; fileRef = E0216286990A5FC34839E3F80B8D6C96 /* FViewProcessor.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 47F644862D2F3FA7ACAC9AC409E11C83 /* pb.h in Headers */ = {isa = PBXBuildFile; fileRef = 301054B3F03AB321796CB62FDD44BE25 /* pb.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 486CCCA59EF8A90677252B35E81D55A0 /* comparator.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BB01893708828A80056288891EE9E01 /* comparator.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 487D4FA6D383090AF1FDFA2788750733 /* FIRStorageMetadata.m in Sources */ = {isa = PBXBuildFile; fileRef = 789F71E8E85917ED0CBB539BF3DB75AE /* FIRStorageMetadata.m */; }; + 48C766964B4CE36CD80FF8D7220D1B8A /* FIRAuthBackend.m in Sources */ = {isa = PBXBuildFile; fileRef = C1A0FB94A0B45A747CBE8D23321B8BCD /* FIRAuthBackend.m */; }; + 48EA0FD567ED01C39C97DC756B22C8AB /* FRepo_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3595599A6D697943276F3488DD6BEC /* FRepo_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 49E0AB27080431FB15F998CA1BCA1576 /* FIRAuthDataResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 13B62195E3A11B0D93DB60EBB5ED122A /* FIRAuthDataResult.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4A046A1D4CA6086E42794466D8E23BFF /* FIRDataSnapshot.m in Sources */ = {isa = PBXBuildFile; fileRef = 12CCC1B4271DDA631C361A6A36F607BC /* FIRDataSnapshot.m */; }; + 4A5C18EEA9A51189379141AFDE4C24D0 /* FIRAuthAPNSToken.m in Sources */ = {isa = PBXBuildFile; fileRef = D11762CCA4EA49A55F93AF08FB928633 /* FIRAuthAPNSToken.m */; }; + 4AA67CFD56CDA29826E6FECC21760563 /* FTuplePathValue.m in Sources */ = {isa = PBXBuildFile; fileRef = D81F978D0BA4662DD96F6F62D35FC8C3 /* FTuplePathValue.m */; }; + 4AEBE32218F94AFB62AED4DD9161F927 /* FValidation.h in Headers */ = {isa = PBXBuildFile; fileRef = E4ECDD1348A475B5ADCE6B521AF2DAF0 /* FValidation.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4B181EF02099871204BA6BF5E3BC9C52 /* FPriorityIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = E4EAF32030EF5CA9819B3EE91BF69845 /* FPriorityIndex.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4B2D0C0BF003527375687E0912D8BA98 /* FIRMessagingTopicOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 9BFA0AB7799DA0A5FF85F62324964A2F /* FIRMessagingTopicOperation.m */; }; + 4B64E08275123F6FF3AD8FEB6E826A5C /* FIRUserMetadata_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 4617A321F3C66DFCDB857489511992AE /* FIRUserMetadata_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4B71158A817AF0F60DE979F2AC709276 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E17134467E8954E9AF37025460CAB049 /* Security.framework */; }; + 4BC6A1B6066445EB017E2DA76F14C2D4 /* FIRStorageGetDownloadURLTask_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 5C23BD54A2D7173A773BCF67F06B63BD /* FIRStorageGetDownloadURLTask_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4BDEE48FEDC02A8A6FAB51BFF149534F /* GtalkExtensions.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = FB7FAEB44184D619533442D7E1C2EACD /* GtalkExtensions.pbobjc.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4BFD85854D4CC225E5D0E0C02AB1F970 /* FIRComponentContainer.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E496823521868D352C97412E304C944 /* FIRComponentContainer.m */; }; + 4C5B18F99A500A35BBBBD1334A2B6B41 /* GTMSessionFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 7577A71A88803C69782A292FCE3A8583 /* GTMSessionFetcherService.m */; }; + 4D0F373D0B5CBD860671BF9E9A2AC8B5 /* Type.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = EF22EB80F2D3ECF9EA4920E3DCDDFC51 /* Type.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 4D1A1A40FD9B72988A1FF9AD957F6B29 /* Struct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = EBF70370314641E65536A91D17604E7F /* Struct.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 4D2A872B89ED6C1A04FA6EF3C7DA90D1 /* FTupleObjectNode.m in Sources */ = {isa = PBXBuildFile; fileRef = C52EC904B0F3150B87E3EA668BEAD512 /* FTupleObjectNode.m */; }; + 4DF2768338C463B587094F8994E9089E /* FEventRegistration.h in Headers */ = {isa = PBXBuildFile; fileRef = E7DD9769669DB7F9E67FC275C3FB7C4B /* FEventRegistration.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4E358E0171A6DB00E2E78F86BE035BD1 /* FIRDeleteAccountRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = E39B46C41B2E94BA9A549054158CE7D2 /* FIRDeleteAccountRequest.m */; }; + 4E35A890B3744A22CB3195E4038B2150 /* FIRStorageConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = 449CF3BAB6CA50258AE9DDCCF5354BB9 /* FIRStorageConstants.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4E4888066B96C7590EC2E190A05B0FD8 /* FTupleSetIdPath.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BF6BAA9454971A57DABB6CA9CD25AD5 /* FTupleSetIdPath.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4E5122842FC952CB1E9F3BC88B0F0C6C /* FIRAppAssociationRegistration.h in Headers */ = {isa = PBXBuildFile; fileRef = A485EC28C2BCF093F8C31F8A206D38E6 /* FIRAppAssociationRegistration.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 4E6490103AD4C01FEEDEB1492F50E7ED /* random.h in Headers */ = {isa = PBXBuildFile; fileRef = 721B542A1F80BE1951DE5AB8C5CECDF4 /* random.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4E6779841CEEC7E062C3DDBC2C1A8E30 /* FIRComponentContainer.h in Headers */ = {isa = PBXBuildFile; fileRef = E2EB03A9C23A3485A23624B691D9B7A8 /* FIRComponentContainer.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 4E6ADE78C8281AB1ABECC5104C3B47A6 /* FSnapshotUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = CB84AAF13B2D3F5576311B23B58E94EF /* FSnapshotUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4EFCA2B3A6F4C260B8507E5E3929DE24 /* FIRMessagingInternalUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B9FB583E7E3DD4C7B26A9FE34F5DF59 /* FIRMessagingInternalUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4F27D04843A818AB2497F7B5E9940FB7 /* FCancelEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = 618C547333D8EAF01B8180DECD81E059 /* FCancelEvent.m */; }; + 4F27DEC670F58C1CDE0DEF1A7980FF61 /* FIRStorageObservableTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 738805EF3840CA94F81C79BA9A95D52F /* FIRStorageObservableTask.m */; }; + 4F542E826FD21DDBA4C681804A65CD3A /* filename.cc in Sources */ = {isa = PBXBuildFile; fileRef = 76BF777E514F1D6AA78DE3FA6FE1E13B /* filename.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 4F5C0502F5B6F412856A310E9147EA5F /* FIRAuthURLPresenter.h in Headers */ = {isa = PBXBuildFile; fileRef = 61B27FDBC34602CF2A3DFD944ED2B245 /* FIRAuthURLPresenter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4F7E93244E6EBA9F51F04339DD737073 /* dumpfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 54B748CB1F4B495705943806D14E57CD /* dumpfile.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4FB6987074A7C231A430E1A9DC1F0073 /* FIRPhoneAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 052D3EAECFCF7B7A9741902E21858002 /* FIRPhoneAuthCredential.m */; }; + 4FB925DB731A1DE38CB4DBE7179E89D9 /* FChildEventRegistration.h in Headers */ = {isa = PBXBuildFile; fileRef = 044D7841EC141A247D182D1B31F071D8 /* FChildEventRegistration.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 501CECD12940FFABF8BABF5653093243 /* FIRMutableData_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = F13F2E644801D0E3C822FC88E1B1FA6E /* FIRMutableData_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 50249165DA81FE6C81E2442E760B9727 /* FIRAuthAPNSTokenType.h in Headers */ = {isa = PBXBuildFile; fileRef = 005F17A0CA6BD689AE60571DA2BAFA11 /* FIRAuthAPNSTokenType.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5062061C7B762AC028651A7F1F0E9897 /* FListenComplete.h in Headers */ = {isa = PBXBuildFile; fileRef = DEED9B0809AD0BCE53D0943BD7BCD19D /* FListenComplete.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 507DF3AE9C550952EEFA4145A520D8FC /* FIRMessagingPubSubRegistrar.m in Sources */ = {isa = PBXBuildFile; fileRef = B7090A47010657A1918B87BAE29D0A1E /* FIRMessagingPubSubRegistrar.m */; }; + 508089242A216167AACF79AD1749B6EE /* FIRMessagingVersionUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = B50EE45BEEE9696770C9F0E3526DABF0 /* FIRMessagingVersionUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 50A1ADE7CEE872200E1B26909524AE5C /* FIRMessagingConnection.h in Headers */ = {isa = PBXBuildFile; fileRef = 235678AD0689F0483082B3B7FEB46171 /* FIRMessagingConnection.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 50BD3989AE60FFA4765A541B33E12CEB /* FormTextViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F3D1610EF8189FF2768299FB5504646 /* FormTextViewCell.swift */; }; + 50E0465D8A40B80F2887CBEBD3A7AD5E /* FPersistentConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = D4DE91FD1133887F4AAC325B2A16F0FC /* FPersistentConnection.m */; }; + 50F013648DC688B8B20C32505EA6C382 /* bloom.cc in Sources */ = {isa = PBXBuildFile; fileRef = 71A5CCCB943C336F5BFE3C9B27E25543 /* bloom.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 5106A9BB8CFD5B5D0E2B82CBAC345D80 /* FIRVerifyCustomTokenResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = B68C0AB6F0930895E952BF5A780C56D6 /* FIRVerifyCustomTokenResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 515BED0BC89E9B645BB0729F1A47E689 /* FirebaseMessaging-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B6C2A21CF5F46F68A65914721B4BC48 /* FirebaseMessaging-dummy.m */; }; + 52071618C875E64E6D9194CE746A3C69 /* FAtomicNumber.m in Sources */ = {isa = PBXBuildFile; fileRef = AC38D0BF1D124FC816CFFBC68841C7F7 /* FAtomicNumber.m */; }; + 520A5B3D5988C02C62DD9F3267E32741 /* FIRSecureTokenResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3848F29E49C46F357D0BC9679EAEE3 /* FIRSecureTokenResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 521F7FDEAB38511C5575D288BB7CC0B1 /* FIRAuthDataResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A49F1C98CBAA4564CA3708149127C6D /* FIRAuthDataResult.m */; }; + 52697DFB887B66F1584354631B6AD292 /* FIRAuthDispatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 77F9D6EC5529498A65162396F20E0832 /* FIRAuthDispatcher.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 52B3F7169F4B7F43F6A51AF8A971F740 /* FQuerySpec.h in Headers */ = {isa = PBXBuildFile; fileRef = 0D611DA4A6D467F635AF0C5C09F9FB74 /* FQuerySpec.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 53247BF34F23D44161C4204A8F7C8170 /* FPathIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = 58487CE27CDAA3A239CAED5DA382A40F /* FPathIndex.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 539D30616085B7F81713D6E533E60A49 /* GTMSessionFetcherLogging.h in Headers */ = {isa = PBXBuildFile; fileRef = 789256212F2759B2374887DCC6A6854E /* GTMSessionFetcherLogging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 53A23AD6460539C93133E5936F8878D1 /* FTupleSetIdPath.m in Sources */ = {isa = PBXBuildFile; fileRef = B48C76A23EF0571C6D82D31226FE2B77 /* FTupleSetIdPath.m */; }; + 53F08143DEE1B6C401D309E74D58ED0D /* FTupleOnDisconnect.h in Headers */ = {isa = PBXBuildFile; fileRef = 7404327BB8BA8D0F2BE2231D7D1349BF /* FTupleOnDisconnect.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 542F9065606868FD1C4D3B037C23AAEA /* GPBCodedOutputStream_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 80F60B07C2849F8B4E6E25DE44C5FB6E /* GPBCodedOutputStream_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 55149D5C67CA2EAA3AFC17BFD0655A28 /* NSData+SRB64Additions.h in Headers */ = {isa = PBXBuildFile; fileRef = B950CCF786F09E70D271B41775C47615 /* NSData+SRB64Additions.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 553E38FF0ACED6BC66D13E2945569047 /* FIRAuthDataResult_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = AD06A572C80510926057D48A1FF3CFC4 /* FIRAuthDataResult_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5582C24E7FA2D33481052628B91FFFBA /* FDataEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = 171F6C7813B27B478AE78B6579E4FBAA /* FDataEvent.m */; }; + 5659D031556A9E3AB0B6362CEEAAFEB3 /* FIRVerifyPhoneNumberRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = AF170DAA3F83CF4EBDF6F1339EF00018 /* FIRVerifyPhoneNumberRequest.m */; }; + 56A8245C093F7D791D9E7F1B132FEE84 /* FIRStorageObservableTask_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = E0B1B26588D39F632E7FAE741113153C /* FIRStorageObservableTask_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 56CE3CA5B155BFDAAA493A3D4A3EF23E /* GULLoggerLevel.h in Headers */ = {isa = PBXBuildFile; fileRef = 44B9DDFF12FCDEFFDA1030DE1B15DA23 /* GULLoggerLevel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 56EF0203603BA1650103D79F0D2FC7E3 /* NSData+FIRBase64.m in Sources */ = {isa = PBXBuildFile; fileRef = 7DBC6776E71F32FE26F370F3CC2E5792 /* NSData+FIRBase64.m */; }; + 576B780EB0F264CCD3F1CE5ACA2BF735 /* FormCheckCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAB5351F6840056BB82AC5102A960BE9 /* FormCheckCell.swift */; }; + 57D471726EB811900977AB76D0707B5B /* thread_annotations.h in Headers */ = {isa = PBXBuildFile; fileRef = 93FE8C81279E09B8344D4D4F5873DEA8 /* thread_annotations.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 57D927E77D3F889440C8501AAE5DE1BF /* iterator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 273588F88459B6EE9873ADA94B13FC66 /* iterator.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 57F1E9867374A80EBFAFAC44909AC754 /* FIRDatabaseReference.h in Headers */ = {isa = PBXBuildFile; fileRef = F5A2BF62391ECF98F03EB919C5C2380A /* FIRDatabaseReference.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 580AF023192269BFA7E9C89BD127CA15 /* FTupleObjects.m in Sources */ = {isa = PBXBuildFile; fileRef = 8200BDBCECE4B63C77D401E6C30EF965 /* FTupleObjects.m */; }; + 583FE7D60284123D8C65C8AE24BEF1AC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 584755500362FD0430BE76FB456C7FE5 /* FIRGoogleAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 03AD6BA64F476C451207DEF30D1C0DF7 /* FIRGoogleAuthCredential.m */; }; + 5851C12C82D4C280F06DD5FBD8BB6FCA /* FirebaseAuth-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FBE764F8D555B5617404FEE2CB64111 /* FirebaseAuth-dummy.m */; }; + 5852CD41D79618A1A99D420BBADD0582 /* GULOriginalIMPConvenienceMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 3D4C5029B4F56F33C0AFF2C7BB347753 /* GULOriginalIMPConvenienceMacros.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 58B75A9A952041F4ED689E4E407F2C06 /* FRangeMerge.m in Sources */ = {isa = PBXBuildFile; fileRef = 17CD745C9A40F6E344672C2AB3522EE4 /* FRangeMerge.m */; }; + 58DF46A85BFCF7D10D1FD611592AD711 /* FIRStorageUploadTask_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = D5EB1CBA1D1666D7B3560FAA3427A1C9 /* FIRStorageUploadTask_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 591ACFC16CD41AB896025845CCED21B3 /* FIRTwitterAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 7195FC7DA43CAFF389557007B61500CF /* FIRTwitterAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 591C8DF910D247F9E9229069DC861077 /* FIRActionCodeSettings.m in Sources */ = {isa = PBXBuildFile; fileRef = A7F1204A860C29B4A4BAEF12AC3CA224 /* FIRActionCodeSettings.m */; }; + 59C56D1D7201D9B5B8CE9E54AF9B2E95 /* GULNetworkMessageCode.h in Headers */ = {isa = PBXBuildFile; fileRef = FB339759EDEDCBAB839541CCC515B825 /* GULNetworkMessageCode.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 59F14E693F57E7BBD18663D234CBF833 /* FSyncPoint.m in Sources */ = {isa = PBXBuildFile; fileRef = E8777028A6004E068FD4E41BDFD48861 /* FSyncPoint.m */; }; + 5A0505E2BCD1A56DDE9240ECBC8E5B6C /* table_cache.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D69CF64D7DD9D1CB88D623B60BFA93C /* table_cache.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5A722AD0805D4F276B9C095E0EC8D124 /* FIRAuthErrorUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 3202E21A3C70DC101F9BC193374415EC /* FIRAuthErrorUtils.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5B1DC8529230CE7C22BA6D8A25E6C00E /* slice.h in Headers */ = {isa = PBXBuildFile; fileRef = 72AA3FD7FCFBF9B31AE268CA36CDF564 /* slice.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5B38F49250D27082A85CB88879DA87EA /* FTupleStringNode.h in Headers */ = {isa = PBXBuildFile; fileRef = EF2565BF522E6ED879327B1704A108DC /* FTupleStringNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5B5196373311E7FE070DA0D6FCB350F4 /* GULNetworkURLSession.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F1A41B7E7B1BF73570D4029B7CB70B6 /* GULNetworkURLSession.m */; }; + 5BCA23A778D7A6821961EB7BB7F920BE /* FIRTwitterAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 9DBBB76901A980386DB2BECA4667AA5D /* FIRTwitterAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5C349011CBE212534C3F6F0F99FBC78D /* FIREmailLinkSignInResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 72B13FA9D89B5C3A0B31E47601B35B31 /* FIREmailLinkSignInResponse.m */; }; + 5C6C4CB13D6035CEE07E31F934D0941A /* FIRMutableData.h in Headers */ = {isa = PBXBuildFile; fileRef = DD8F80849FF142E6CEA8C80A9429B455 /* FIRMutableData.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5CC6E195CEB090320F1043908AB8230F /* FormButtonCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = AECBA6A0BBA8C75D909C3BBA5A05C859 /* FormButtonCell.swift */; }; + 5D3898F2B928E1836E8B005976695D62 /* testutil.cc in Sources */ = {isa = PBXBuildFile; fileRef = 2A66497EBD1AB3737D5005944AF2A938 /* testutil.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 5E0104BFDBD44C748BAA576F4F444BAA /* FIRServerValue.m in Sources */ = {isa = PBXBuildFile; fileRef = A3A6CAC7709D278E80B3D80F187CEE79 /* FIRServerValue.m */; }; + 5E2F59B3A8B8FDDF66FF0F68422A1E3F /* GULNetworkURLSession.h in Headers */ = {isa = PBXBuildFile; fileRef = F1605E61657A7435C9C2AB1893D5E9F9 /* GULNetworkURLSession.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 5E6FD62B18705C3005EE326D28E9EFBA /* FIRDataSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = A99F776AB4854965623E2157BE844140 /* FIRDataSnapshot.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5EAE46F6A7B0831FE652C16EE6BAB775 /* FUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = A3AF2B4F082D56E9F3B5C36EC9CA1ACD /* FUtilities.m */; }; + 5EE3238F838EA583FB7B86B771BDD2E5 /* GPBProtocolBuffers_RuntimeSupport.h in Headers */ = {isa = PBXBuildFile; fileRef = DE84738710FAC6778EC1FBE3B5235F5D /* GPBProtocolBuffers_RuntimeSupport.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5F5E3FE69B8ED5CEB2B462BA63EBBA60 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E17134467E8954E9AF37025460CAB049 /* Security.framework */; }; + 5FA7C8E2A1BCBB52B3E108EE54E362D4 /* GtalkExtensions.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 6F11B8D726B6EB35E25DBAFF2E410D30 /* GtalkExtensions.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 6038EAE5EB6503D4F653AAF9471C5420 /* FSparseSnapshotTree.m in Sources */ = {isa = PBXBuildFile; fileRef = BD91CFB92703A5598BBF2CC6E38F9678 /* FSparseSnapshotTree.m */; }; + 60497C5696879AE4F608DFED412C5623 /* FIRTransactionResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 56DBAB0E527B855D6B1FEA68A8CF3582 /* FIRTransactionResult.m */; }; + 60B8F4DA4C6208E62572814E08FB289E /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E17134467E8954E9AF37025460CAB049 /* Security.framework */; }; + 6126B1178651B0EF339AC7E877DE8A11 /* FIRMessagingClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 5DBC97B383D5D93C4468FCF29B800674 /* FIRMessagingClient.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6223F9434C725407774B4930C2660A26 /* db_iter.h in Headers */ = {isa = PBXBuildFile; fileRef = 42BCBB4A4FDF6D8CDE4DFB7454B6BFD5 /* db_iter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 628145EF2395C53BB600EA8641CE1C20 /* iterator_wrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = B71F9CA1A6DFC5C710C50B9AFA31CBAF /* iterator_wrapper.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 638C0C0DD7C4929D902A92E254DC9499 /* memtable.cc in Sources */ = {isa = PBXBuildFile; fileRef = 160AC27B2B81C1CFF9884A32DEDBD736 /* memtable.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 63C08B25B83392876349B76A01EF0DD0 /* FIRAuthBackend.h in Headers */ = {isa = PBXBuildFile; fileRef = D231D1C9A6DC029C392DA35062159AD0 /* FIRAuthBackend.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 63C19BC1145BB84720BEF7EE79153EC2 /* FIRLoggerLevel.h in Headers */ = {isa = PBXBuildFile; fileRef = 777D09D2C04A9EDDF146AD4F850B0308 /* FIRLoggerLevel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6433C81AF0C5DA546C3CB18178217D51 /* posix_logger.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A3870091C969EE33FC9862E0AC8182F /* posix_logger.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 64508C76C9A29C3339CB874458118BDF /* FLLRBValueNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 08D738374880F7FA49B1EAB508EDEBD0 /* FLLRBValueNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 64720DDC437A6AFF98E03E4171BD2DA0 /* version_edit.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CF857CEF2CDC86922BA2271E25A7A13 /* version_edit.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 64A0467CEE2AD508778F414973069ED9 /* FIRNoopAuthTokenProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = EA86C1C2E7F7812ADB29376757F6DD4F /* FIRNoopAuthTokenProvider.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 651797C6171EE641B79B4D1D62C6948D /* FTupleNodePath.h in Headers */ = {isa = PBXBuildFile; fileRef = DC4966A882229EFA017144185FF21757 /* FTupleNodePath.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 657959D98D454DE5B75535323418897A /* Pods-My Mind-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 750AE2BD4EAC19C11179AC6E5CE3BF7E /* Pods-My Mind-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 65C31895EDBF3B201F3502DC47C639C3 /* FTrackedQueryManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A4825168FBBF46A0CF64FF8808816E3 /* FTrackedQueryManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 65EF330A8AB7B7D638912E2E2BC1EAE7 /* FLeafNode.m in Sources */ = {isa = PBXBuildFile; fileRef = D1FBF0A9EE42AF399B2B94CD6809F898 /* FLeafNode.m */; }; + 67117B627E97D17BB8EE22297BE609C8 /* FIRAnalyticsConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = F315942AF6B5C93E6FB28E2F583FC8B4 /* FIRAnalyticsConfiguration.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 67896D50B905AD4D1CF1CDBB4C45B69E /* FormPickerCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F065833D4D711DB2314D643800DD031 /* FormPickerCell.swift */; }; + 6823BAB245286F703E96AEEF63B43FB9 /* FChange.m in Sources */ = {isa = PBXBuildFile; fileRef = DF89E6C6615E5188CAC12F41A08EA8E4 /* FChange.m */; }; + 6831D5B934B5F86075416045FAAAB367 /* FPruneForest.m in Sources */ = {isa = PBXBuildFile; fileRef = 11796741226434375F93ED3BA8C0A741 /* FPruneForest.m */; }; + 685770FAAC666DDED9C233D77A7207EB /* FIRIdentityToolkitRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 0ED14CD3D134195AD99E47BD299EBDF7 /* FIRIdentityToolkitRequest.m */; }; + 691FCECA0451BF9E483BE682A51F7509 /* FIRGameCenterAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 512270231AF1BD7162D2DF64A91E39D7 /* FIRGameCenterAuthProvider.m */; }; + 69FFEB2C81454309F26E72BD9A13C52B /* hash.h in Headers */ = {isa = PBXBuildFile; fileRef = 5CB11A8A37A78CD677212D20B4EC9A5E /* hash.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6A3F7C46330A4EA69D0CA257CB60EB00 /* FIRMessagingRmqManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CEEEDDBF0B7C02B72407C0E80B35688 /* FIRMessagingRmqManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6A6F222550CBE1E6762EB4510149335B /* FStringUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = AE210630843BC4F35C085C2F50BD731E /* FStringUtilities.m */; }; + 6AA49C7F2581024D3EFA2E1B9E9EB400 /* FTreeNode.m in Sources */ = {isa = PBXBuildFile; fileRef = D4B06DF0BDF7821D048B9478C5F9D97B /* FTreeNode.m */; }; + 6B804651E0974E119607E4AE34A941FC /* FIRGameCenterAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = C2B6EFFEA69D94C962C92D480A5F7B5D /* FIRGameCenterAuthCredential.m */; }; + 6C6AA17056A60A466B776DB74B5DAB3D /* FLimitedFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3DAED226313360A65EAC8D21A34E31EB /* FLimitedFilter.m */; }; + 6C6AA46BD8DD2F1898EA7CFCB187CF98 /* FIRSecureTokenRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = BCA9949E729F8FA89A2FBA1FC41A08C4 /* FIRSecureTokenRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6C7FA07C60CC029BD2F5B26EC7F2F5BC /* FIRResetPasswordRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = FA2D1B490973CDAE6A8E40524F7FB975 /* FIRResetPasswordRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6CE03A50870B92C6F8992DAF20A34B99 /* FIRGetProjectConfigRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 72DAEB8DAF3F23E6A8C884A9E87C387E /* FIRGetProjectConfigRequest.m */; }; + 6CF756C57C23BF6F5A1FAB3F1B431644 /* FIROptions.h in Headers */ = {isa = PBXBuildFile; fileRef = A7E45C4CB7E9A1B7DC4448F0725D4921 /* FIROptions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6D8156FE32B106DF6B8857CAAB6B2223 /* cache.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7AA64C916741F0BA7ADBC05AC52D974A /* cache.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 6D84BA31BCA85CED9BBE25DF9E0E7F62 /* GPBExtensionRegistry.h in Headers */ = {isa = PBXBuildFile; fileRef = E83395DDC37AB2B43925CB22AB834320 /* GPBExtensionRegistry.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6E81A7EC383CC06F435C7955BF35D8D7 /* FIRVerifyClientRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FE6FFD73A1F41902CEAA39F2D6CAD7A /* FIRVerifyClientRequest.m */; }; + 6EB593B56B0ECD3102EA3AC011BE3EFE /* GPBUnknownField.h in Headers */ = {isa = PBXBuildFile; fileRef = B6032ED1761DE16D733B707DC6D72F5B /* GPBUnknownField.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6EEBB3F1EA4A7A467A6576A4CCC55149 /* FIRMessagingCodedInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D65988F3A1356BEE3BC3D0369BBAAC9 /* FIRMessagingCodedInputStream.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6F412D7A91AD823FDA1C065278498790 /* FIRGoogleAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 95AAEB80477A015CAFD91C1AB9C14DA7 /* FIRGoogleAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6F42A6B98CED5A87976CB199EC3007FA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 6FCC648764C27AFDB436D809C75FA066 /* FIRDeleteAccountResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = DCFB485E7EE041483501574C5B2F7CCA /* FIRDeleteAccountResponse.m */; }; + 7090E26A73C33E7E67F24A2E2B7CDF96 /* FTreeSortedDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 60F0F5A859C55E91E94D4D5F10B28B92 /* FTreeSortedDictionary.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 70928302085AE04DB9746B001674CE27 /* GULLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 636106B60C9506E961ADC79797A5739D /* GULLogger.m */; }; + 70A01A282869906039CB23CF00ECD937 /* FIRSecureTokenService.h in Headers */ = {isa = PBXBuildFile; fileRef = 136CC9E6128297BD62D6F21F1284BF89 /* FIRSecureTokenService.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 70FFEA217864AEC22E6C5044CD8A056D /* GTMSessionFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 2D49C8229916022BD904F466DD4B1695 /* GTMSessionFetcherLogging.m */; }; + 713D2EA92B582AD4DCEBB17CCF150CEA /* FIRMessagingDataMessageManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 519AD2081997EB288B842570149B0B7F /* FIRMessagingDataMessageManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 71AF98FE4A9F2469CD72D0E52B094E6F /* FIROAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 3CFA6E1D288C15BD5851CFEDE6AEA633 /* FIROAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7220E34740A20FCEAE61B1495AB18900 /* FWebSocketConnection.h in Headers */ = {isa = PBXBuildFile; fileRef = 3A76E7B0DE462D4F237E12CB0F74930D /* FWebSocketConnection.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 72DA26C341C046F3DA66200B1B4C0754 /* FWriteTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 977804E7E131595293C9F752303CEC88 /* FWriteTree.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 735084A830606575362DE447148BF143 /* FAckUserWrite.h in Headers */ = {isa = PBXBuildFile; fileRef = CC590D92037B35FC414FF8BCEF4C66B9 /* FAckUserWrite.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 73A4176EE589467648540DEBF49464A5 /* FIRSignInWithGameCenterRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = C185A4DDD2586774727CB23BCBED0299 /* FIRSignInWithGameCenterRequest.m */; }; + 73D033AAF2CE93E62837589F0E1FF63B /* FIRMessagingDefines.h in Headers */ = {isa = PBXBuildFile; fileRef = A6181FF5A800FCCC67FBFE0B7BF53D27 /* FIRMessagingDefines.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 73FD120EAE9F35FEFB94B717EE5591E8 /* FIRMessagingTopicOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = B84AB522D96FDBEF56178B4E103D0722 /* FIRMessagingTopicOperation.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7469BBC99ABDE48CB24BD5CB637FCC27 /* FIRSignInWithGameCenterResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 6770B86455BBED608BD0F1FCAA2346F9 /* FIRSignInWithGameCenterResponse.m */; }; + 748BF578B84FBBA94B37372C12873CA1 /* GtalkCore.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C7934CC4C320D6B8EED446F41CB3070 /* GtalkCore.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 74A73562EB95A5EEFFFF917305018EBE /* filter_block.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E028BD0ED8BAF09AF89450487F80927 /* filter_block.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 74EE0DFE076866675923FA31C5EEFDA7 /* FIRAuthKeychain.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E58E6D786617300484ECDDFACB2FA6F /* FIRAuthKeychain.m */; }; + 75F0BAEEAD9FA0C4B6A66F321E0B7E12 /* FArraySortedDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = F03EAA2EC81A15074DB6D1EA122E97C0 /* FArraySortedDictionary.m */; }; + 763C2599457CD314F0C23C47F36A2416 /* FIRAuthSerialTaskQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 119A6FE215E962613478EEBFC1F4F505 /* FIRAuthSerialTaskQueue.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 765C0471539D9719322CF5A40F8E2E01 /* FIRSendVerificationCodeRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = FB1E9CF96D680EA21D837060EF23667F /* FIRSendVerificationCodeRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 768E4C922333EE473BCDB6A61A9A8A66 /* db_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = A5C0809DAC4098C4DCA572A7499E9116 /* db_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7696AE486EF953B157CA394CA58038F6 /* GULNSData+zlib.m in Sources */ = {isa = PBXBuildFile; fileRef = F09277F67D2CA69E933081A31E0BE2F1 /* GULNSData+zlib.m */; }; + 771DFEE8279979F5DD28AF0B96E58F4D /* FTrackedQuery.h in Headers */ = {isa = PBXBuildFile; fileRef = 2073FD9AA334017E0E90D8197D3A84B8 /* FTrackedQuery.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 77FB82CD991CECCD4CC9A4389500E93E /* FEventGenerator.h in Headers */ = {isa = PBXBuildFile; fileRef = B057F909F1A17282CBA960CE4A2237B2 /* FEventGenerator.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7826535FD4DABDA421D8C6E7CD42ECAC /* GULSwizzler.h in Headers */ = {isa = PBXBuildFile; fileRef = 9A425C87553240C22CA6ECCE49E65196 /* GULSwizzler.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 7833221C662C83CE83BEC6024C116D10 /* FIRAuthSettings.m in Sources */ = {isa = PBXBuildFile; fileRef = 8AE098A043EF747C4AB64731CEDC3FA3 /* FIRAuthSettings.m */; }; + 7869B64F2F6316126593CD189194BD7C /* GULUserDefaults.m in Sources */ = {isa = PBXBuildFile; fileRef = 6440D16966C799ADA6FF8B1D0F21716D /* GULUserDefaults.m */; }; + 79E6F10B00F9218719B94CE73F6EFD74 /* FIRAuthWebViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = B6C8EB92AE55113567DF336B2C0EA1AB /* FIRAuthWebViewController.m */; }; + 7A142B968132692D56E2EA79E38FBF1A /* FIRStorageDeleteTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 45163B0967987CC35BE8D9091891B40E /* FIRStorageDeleteTask.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7A66B535FB8849FA7756968A8D6365F4 /* FIRAdditionalUserInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = B7365E12A17D8AEA411AFD1AE22C6647 /* FIRAdditionalUserInfo.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7A999870D9DD45A47B8EBB3934B8A233 /* FPathIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = FC7C460601A2517E74B240EE306DF439 /* FPathIndex.m */; }; + 7A9F1AD0FFE9227575A38C84A461D201 /* GPBUnknownFieldSet_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 55151CA7726A3419117D3B576C43A54B /* GPBUnknownFieldSet_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7AFB98C382890FEB5AEBDCD32B333180 /* FSnapshotHolder.h in Headers */ = {isa = PBXBuildFile; fileRef = 309BB9290E966976A199C728D934130A /* FSnapshotHolder.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7B3A1CE76FFD6E2CE6F4173E9F0B69BF /* FIRPhoneAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = CF39E63BAD15EE14C47C6750CC780862 /* FIRPhoneAuthCredential.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7B9F461598C44240C924C220394DBA29 /* FIRCreateAuthURIRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = E5ECBBFA8BFE9B48F5ECAD6DBD5D940C /* FIRCreateAuthURIRequest.m */; }; + 7C085F2F10CD608EA786560E45EE24C1 /* NSError+FIRMessaging.m in Sources */ = {isa = PBXBuildFile; fileRef = 6C2D515DB16433C8F3E59AAF36EF38EE /* NSError+FIRMessaging.m */; }; + 7C9EBC2B228C85FDAC569E808C145AC7 /* GPBCodedOutputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 16ABBC1602669EF624F71C7D2874005A /* GPBCodedOutputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7CC1B63E46109E535FB4F13084CAAD77 /* GTMSessionFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A4C69A6E7DCD1DA0FE2647B81119490 /* GTMSessionFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7D2F7644BDE6BA8F764458C0C552CCCD /* FirebaseMessaging-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8F2B4DAA5BB46220C05E787322CAE960 /* FirebaseMessaging-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7D2FF6C5681390D838D3573E87D4B361 /* FIRSignUpNewUserResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B9420FD08C302FF4ABE9F9E8AB18A16 /* FIRSignUpNewUserResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7E4719BDDE80650C7A1E792DF2C011F4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 7EC3F0AA877A53269B037F1BE0209189 /* FSyncTree.h in Headers */ = {isa = PBXBuildFile; fileRef = C3276A2BFA726F605D0020C6E3F30F22 /* FSyncTree.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7ED9F2FE61D3658C2E275F0C27B3A1B8 /* FIRCreateAuthURIRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 402D85148074A575F2F4BE6D41FE80D8 /* FIRCreateAuthURIRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7F3966E4CADB8FDDCEB38E84FCBA9624 /* testutil.h in Headers */ = {isa = PBXBuildFile; fileRef = 551DE73F29DCBD088E26B78CC09409E8 /* testutil.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 80E37C99D8494655FC0ECEE03AE770CF /* status.cc in Sources */ = {isa = PBXBuildFile; fileRef = E6913AC5D85713434F74209FB9DF8190 /* status.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 8138F4D72CEA3E79F7A430C8BC9EC924 /* FirebaseMessaging.h in Headers */ = {isa = PBXBuildFile; fileRef = 4485AF69CA9E95F41797643FEB969885 /* FirebaseMessaging.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8141044D91C61B567A792FA1E8938B11 /* FIRAuthErrorUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E7C9E6358BF67C02F1D141654EA02672 /* FIRAuthErrorUtils.m */; }; + 8174236DC749231BF30A02C9AC3AC6B7 /* GULSwizzler.m in Sources */ = {isa = PBXBuildFile; fileRef = F305AC9FC0D8555AD1783A104FEDB22F /* GULSwizzler.m */; }; + 8179683A38863728D22BED491ACCE9EB /* GoogleUtilities-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AE61849A6A393E9FC1EB0A2778E14C73 /* GoogleUtilities-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 81EA084F84E2E5B4ABC637DB30572EE1 /* FIRFacebookAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = CE4660BA7D6E8CFDAD16757199161DB4 /* FIRFacebookAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 820E8B73383B6DF22E7D1CA538025161 /* FirebaseAuthVersion.m in Sources */ = {isa = PBXBuildFile; fileRef = 9DEB6F89764B79942EF4FF1368A9F6C8 /* FirebaseAuthVersion.m */; }; + 826D06D193CA64611D6D06C812D3D46D /* FRangedFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = B1FC0F5D6E265B194170509A9025EED7 /* FRangedFilter.m */; }; + 82BCAEF7C2862BA98A71099327735F46 /* FPruneForest.h in Headers */ = {isa = PBXBuildFile; fileRef = 8E6B71DD9A246127CC984BFD6DB3B66D /* FPruneForest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 840DE54F14AA85F6A6C4D8E1B50ED26C /* FIRGetAccountInfoResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 44750059DC524A1D74F3CE34D403991A /* FIRGetAccountInfoResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 841D495A62791DC4B0466079DC984B7D /* FIRStorageReference.m in Sources */ = {isa = PBXBuildFile; fileRef = AC39528D9EF5C627E843B230297D8360 /* FIRStorageReference.m */; }; + 844D85F12F42AE3E04D67D32DCA5CFE8 /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = CC6ADBF7520BE4C24E99069E832C1E44 /* Any.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 84724F50CD690FBE29DC07D60DA57CE3 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = 672F641C8ED1591333E51751747D9051 /* GPBDictionary.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 84913A4683DA41F54915D2F08B4F366C /* FIREmailPasswordAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 1261B3607B95AB5FCC0789BAC0335F4D /* FIREmailPasswordAuthCredential.m */; }; + 84F1BF568E29D9E470BDFB6F5293CE71 /* FIRAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = CD10E05003650C16485F6681FFCFB453 /* FIRAuthCredential.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 850F2E13D548D0AF42396FCD31A351F7 /* FIRTransactionResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 8F92B73F81BC9043DF09D74636383BD3 /* FIRTransactionResult.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 852964614DD810C12A603E75C40BA3B0 /* GPBBootstrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D10BD44F431CB676BA0F99531C372EC /* GPBBootstrap.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 85B5BFB63EB47EED1A89513B6D16B77D /* GPBExtensionRegistry.m in Sources */ = {isa = PBXBuildFile; fileRef = FC9BEE8EF9E33D02A8E5B842C4EC1747 /* GPBExtensionRegistry.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 85FBEBEB3DB2EAC5E24917BD74E59A0F /* FIRAnalyticsConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = E7A59D3F7A1A6EB8A8A65F5269D9F6EB /* FIRAnalyticsConfiguration.m */; }; + 8656E4214A0B1D14B8131B9719943DF8 /* FIRStorageReference_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 360F34FFDB1C719C8DE28092E5639368 /* FIRStorageReference_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 865C218C9BA8FC209F49CA669AD1B1A1 /* FListenProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = AA51B0829287BFC68D2DA3B4440E6AF6 /* FListenProvider.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 86AE3929EB07E9757E3B6A750C0E51DD /* FIRGetOOBConfirmationCodeResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = C5D45A7FC3F4035103ED107B1F6127F3 /* FIRGetOOBConfirmationCodeResponse.m */; }; + 86F2C692B0DA27165AF8B605060C7A56 /* FTreeSortedDictionaryEnumerator.m in Sources */ = {isa = PBXBuildFile; fileRef = 7419C5FA3F1E39B79BC98148F8B303C2 /* FTreeSortedDictionaryEnumerator.m */; }; + 873F96538D0A120CF789640F9FE17FB1 /* FTupleObjects.h in Headers */ = {isa = PBXBuildFile; fileRef = B5C3F4B78DF3673687E6F9E9D5672781 /* FTupleObjects.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 875AAF41A3BA5D50E41DA8B2CE16119F /* FDataEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = 7568B7BB638B453805A7B08112D98D8E /* FDataEvent.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 878AEA6C8AD7E00E72103A5E6936A453 /* FIREmailAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 060A5011E8273A2F4FB12E14AA12DD51 /* FIREmailAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 88739CEF4AE0A08CE3DFAF1BE8E250F3 /* FListenComplete.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F0FDD548581BEE2026C81C115C042B5 /* FListenComplete.m */; }; + 887D3EFAD17964D20F8A8FB8FFB43040 /* FIRUserInfoImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 40A760468EF4E6190C18CA4B004F5C0E /* FIRUserInfoImpl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 88B698FD87FCF4DA1BAF4ABC7AC85FFA /* FIRMessagingVersionUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 7C96AB097262F1C3DCC11C50D3E59544 /* FIRMessagingVersionUtilities.m */; }; + 88B6FAD0644DED6B950AFB1B76FA5018 /* FPath.m in Sources */ = {isa = PBXBuildFile; fileRef = EBACD6FF2BAF6C98C1E9D96D22E6E633 /* FPath.m */; }; + 8918C62D9BA2A846F28835E34CF13BCE /* FTupleOnDisconnect.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF3C805C4BA2351F7663FC5BBB51446 /* FTupleOnDisconnect.m */; }; + 8930870A3F0B1CA5E2B0A8AE0FC85E65 /* FormSectionDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491F309FF0747418811867CB4A81B0BC /* FormSectionDescriptor.swift */; }; + 895D35F4A615219F80A7944477D1DA86 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 8979C58492296D7F06A1AEAEFC8F399A /* FIRMessagingRmq2PersistentStore.m in Sources */ = {isa = PBXBuildFile; fileRef = 550F30B53D98C5B179E6C9B95DCBBD49 /* FIRMessagingRmq2PersistentStore.m */; }; + 89D795ED6041C05C9DDF850DD49F8917 /* GULReachabilityChecker.h in Headers */ = {isa = PBXBuildFile; fileRef = E0F0F5DF6F0408D75CDCE659553410AD /* GULReachabilityChecker.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 89E71F9B92E1779978E3E5E70FB06712 /* FIRUser.h in Headers */ = {isa = PBXBuildFile; fileRef = 44B502759D088A3DA6A61F8E45DABA0D /* FIRUser.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 89EBDC231BA2B1DF7AD7DFA458D17BC9 /* filename.h in Headers */ = {isa = PBXBuildFile; fileRef = BBA75DF8FF00F58C0B862CFBFDE225AE /* filename.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8A1743A0B92B4BC98B48E7B6BC53BE72 /* log_writer.h in Headers */ = {isa = PBXBuildFile; fileRef = 2C2266A871A0E4A996895C0A6B5F65CF /* log_writer.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8A4F7161E986EDB276A57244550E928B /* FLLRBNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F5AA5097DD6969A0A996849D3ADA0FE /* FLLRBNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8AE5B4E76F36101F229C99A8FE310AF6 /* c.h in Headers */ = {isa = PBXBuildFile; fileRef = 238B69F72D2635F7E099540FEBAE969A /* c.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8B43C59858DED237E3786E5F3AB70D6A /* FIRErrorCode.h in Headers */ = {isa = PBXBuildFile; fileRef = 508285CBB0038322C3CDFA2C14D67013 /* FIRErrorCode.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 8B4FEAEDB442AD4F795C07DC80BDCDAF /* FWebSocketConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = 95F2B1C34657348ECD42CC43E037DC68 /* FWebSocketConnection.m */; }; + 8BDCED39B9876A9F1EA296FB800F2CF6 /* FIRAuthTokenResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 70BF98E2DC5C000BD8610127B3AD8AF6 /* FIRAuthTokenResult.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8C3007FAE540957E0E0F64DF2AD19C6E /* FNodeFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = F8EEA04BA35D6AA6DDE2D44BA30C6527 /* FNodeFilter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8C3B89BC8A2DA18385A402DB2664EE76 /* FIRAuthRequestConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 5DC32D3EC7D2CD53597176FFB6E5F799 /* FIRAuthRequestConfiguration.m */; }; + 8C6BFF3CC31374AA158690844968F3E9 /* FKeyIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = 502015322F13E326A360FF358E29B946 /* FKeyIndex.m */; }; + 8C7F928C34AB0956E676286DA6C311C1 /* FIRSendVerificationCodeResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = FDA6193F787E16C51CE19542A9069DBE /* FIRSendVerificationCodeResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8CC773AB211833FD012BC0D0E35F7415 /* FTupleTransaction.m in Sources */ = {isa = PBXBuildFile; fileRef = DC9216026608FFA44A02C2E8BF9A9E3C /* FTupleTransaction.m */; }; + 8CE510C277C94E23FBE508EF8A8647E1 /* crc32c.h in Headers */ = {isa = PBXBuildFile; fileRef = 31997DF23B7B7028628BAB1A7A4AFD8B /* crc32c.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8D9DF1B959B1568D8BBED3D1CB537190 /* FTupleFirebase.h in Headers */ = {isa = PBXBuildFile; fileRef = E921EE2F6E50B2B950BD43A6A6862162 /* FTupleFirebase.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8E21CA3FA72F455B14BEA2C693801F30 /* merger.h in Headers */ = {isa = PBXBuildFile; fileRef = 2AD6C8F4DFB8B09F9C4C1273793725ED /* merger.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8EDBB7DBAA3BF2D76EBEF32F67A00D78 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB57BCF1E73C7B8A4B2CAE6F512FB8A5 /* SystemConfiguration.framework */; }; + 8EF46D58696F4E6DFFD3D1EEA14296DB /* GPBWireFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = A338397206C34CAF5CBB48E4D05DCD6D /* GPBWireFormat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8F1C879CDF4B7467D7A14BEFD9A9CC7B /* crc32c.cc in Sources */ = {isa = PBXBuildFile; fileRef = F6A56D57F7830EB35CBFC515C582CF0A /* crc32c.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 8F405808BD87E3BBE378B0603B4D40C3 /* table_builder.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E14FE7B650352A45172263EB07521FA /* table_builder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8F555CAD99E7161E53D7A26980C0D3FF /* NSData+FIRBase64.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BC11EBDA615AAA6167464EEE00C3EE1 /* NSData+FIRBase64.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8F75852BB36E50EC5729B5B80EC4CD57 /* log_reader.cc in Sources */ = {isa = PBXBuildFile; fileRef = A6CBDE68609CD2D3C103DAA433F2C60F /* log_reader.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 8F76064E137E3BA77FCA80B7D6158CD1 /* histogram.cc in Sources */ = {isa = PBXBuildFile; fileRef = 58F22BD1F34CA15EC75B42909369C0E6 /* histogram.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 8F88D609AAE1440DF35C6B69EE7DDD85 /* FIRSignUpNewUserRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 7BBCD51FAF30C35611BEB23B626C6624 /* FIRSignUpNewUserRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8F8C9875A9F9F8D337FF5199CAA68C72 /* format.h in Headers */ = {isa = PBXBuildFile; fileRef = 0D945B5FCAFD829D8E4CB0BC446F5263 /* format.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8FB1FF9F99D0CB549EEFF34119B70067 /* FIRResetPasswordRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = BCF80591D51DDED99DCFEB418DAF6C6D /* FIRResetPasswordRequest.m */; }; + 900C205CED5C47387337EDEA70EBA6CF /* FIRUserInfoImpl.m in Sources */ = {isa = PBXBuildFile; fileRef = D3FCE7821A5559920675860218C3E7B6 /* FIRUserInfoImpl.m */; }; + 904CB05DACC3D79481020A50AAE68E53 /* FClock.m in Sources */ = {isa = PBXBuildFile; fileRef = B3F673C51D33F552AA826578B448AF3C /* FClock.m */; }; + 90DF1C506A6C5A5FA346CCD9865D768F /* FIROptions.m in Sources */ = {isa = PBXBuildFile; fileRef = 13E143593E7232E1F8B12AC4FE62DA8A /* FIROptions.m */; }; + 91B3761046884D4CEFD906383EB65E6B /* FIRStorageMetadata_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 9213B9E77E41B0F09DE4A6DEF4605354 /* FIRStorageMetadata_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 92220B096BAC953985661BC5F2DFDD85 /* FPersistentConnection.h in Headers */ = {isa = PBXBuildFile; fileRef = E68A2AA637BDE4FEB94C7CBB17526C5A /* FPersistentConnection.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 924C93CD57FD4D8B0BB521D029C213C8 /* cache.h in Headers */ = {isa = PBXBuildFile; fileRef = D54AF9EA9805ABF27B6EE19DE73292C9 /* cache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 92B58251896AF2A43D3388B4A7A17375 /* FTupleNodePath.m in Sources */ = {isa = PBXBuildFile; fileRef = 65ACC8103EBC8FC94891C616DFB37168 /* FTupleNodePath.m */; }; + 92CBC09B402DA90BDF70F383755086EC /* FIRSetAccountInfoRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A73AA5071EC8EB467C178B670E2D98D /* FIRSetAccountInfoRequest.m */; }; + 92E42418FF51A6A36710FA1E194477CA /* FIRErrors.m in Sources */ = {isa = PBXBuildFile; fileRef = B17E60B74D249F60A7E8A809C20EFCBA /* FIRErrors.m */; }; + 930F2FF02203E6CB571BED9D9F09A1F6 /* arena.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7334FFB579A1884B99237373A09774DD /* arena.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 933173512B68474ABA0E4F17835A9DA0 /* FTree.h in Headers */ = {isa = PBXBuildFile; fileRef = CECD1A2BFBF0E479DFBB774F092537C4 /* FTree.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 93539082357CC56383E343DD7CAB9593 /* FConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = 4109A974CBD18486C940B1F1487720A0 /* FConnection.m */; }; + 935DD97ACE2BAB32DDF07A0EAD752744 /* FWriteRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = FE464DE5F2ADF86CCC4FBA2E5749B1F9 /* FWriteRecord.m */; }; + 9378AA360EB8BF7A318BF4D3DD1FD98A /* FIRUserMetadata.m in Sources */ = {isa = PBXBuildFile; fileRef = 68055C3921D68B4D2A9E01154969543C /* FIRUserMetadata.m */; }; + 9384AD4385F02852B227C892AC19E375 /* FWriteTreeRef.m in Sources */ = {isa = PBXBuildFile; fileRef = 4DE03466C662D0024DF6BEFBB58CB658 /* FWriteTreeRef.m */; }; + 93CC152EEB0129345190C43B718BF810 /* FIRVersion.m in Sources */ = {isa = PBXBuildFile; fileRef = 2DB687A0483C0EE960D37434597A35AE /* FIRVersion.m */; }; + 93D6683C3A685E2AEB12C507A89B39BD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + 93F2CC4E4B63982B1E8BE7F812B261F1 /* FIRAnalyticsConfiguration+Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 455B531E0B5384D77DBDDA413F3CDF03 /* FIRAnalyticsConfiguration+Internal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 942EBF353D5E23BD696F9F84B5A70FDF /* FPersistenceManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 94CB3AC364A3701DC592D22BDF8D4D64 /* FPersistenceManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 947145C319107C75FAA9C3EB5B270862 /* FOperationSource.h in Headers */ = {isa = PBXBuildFile; fileRef = AE72ED507BFAB70E74F0185212CFA468 /* FOperationSource.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 94CB139653C686BBA6278C82D68FC7E9 /* Struct.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = D897AF51D9D53A189E407BC729E743A8 /* Struct.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 951697EDC6A3E9876F3EDA4678EB737B /* FIRSecureTokenResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 66861CF6B01E5AA0D15E1B102B1ED8CC /* FIRSecureTokenResponse.m */; }; + 9573A39A5B2D8120844A1A22A909A7E9 /* FIRComponentType.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A28513C7E79F8D83ACCE3ADDEB0CA1B /* FIRComponentType.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 95CB107FD47710D82AADCF796739E487 /* FIRMessagingDataMessageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 58D5C0A45F0C7FAA8267304BFB70E2B2 /* FIRMessagingDataMessageManager.m */; }; + 96A46134A41459ECD851507FE82A2396 /* FTupleTransaction.h in Headers */ = {isa = PBXBuildFile; fileRef = 73E2B0654C8EA0F00AB43543CBD124F7 /* FTupleTransaction.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 96A71A9CF82ED4CBBAC6303434D5D498 /* FIRRetryHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = B1FF1C0990CE6DF70B31DBC7140BE404 /* FIRRetryHelper.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 96DED265BD66E66313D96701C5BE76DA /* FIRAuthGlobalWorkQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 3023906E936612450A901BB43816EB8C /* FIRAuthGlobalWorkQueue.m */; }; + 96F0D37AE2A4F7A32F02D12FE6E299D4 /* FIRDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = 0CD5B29065B8C08D5397404B28BD7CDE /* FIRDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 96FDB687B22BD267A70D769F7073DE52 /* FTupleUserCallback.h in Headers */ = {isa = PBXBuildFile; fileRef = E7FB12B47C9D60E0AF8953271C31107A /* FTupleUserCallback.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 97256A880C9E1703AE973ACB6C876D11 /* GPBExtensionInternals.h in Headers */ = {isa = PBXBuildFile; fileRef = 9EE4F1D9B84C172C41E721B213F1707A /* GPBExtensionInternals.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 975BDD38E28039F408D52877FC0B5C5E /* FIRSetAccountInfoRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 70B2BC7C8E160DF34E8B88E3EC14A5F4 /* FIRSetAccountInfoRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9764C1B0913596D2CAB3162CE8E3C80C /* repair.cc in Sources */ = {isa = PBXBuildFile; fileRef = A28ABD321652444E5617923C7C375319 /* repair.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + 977EA5854B5A4B76BC701A3A35BACBD8 /* FIRDatabaseQuery.m in Sources */ = {isa = PBXBuildFile; fileRef = 0B51883B5AC0F922A2308C19F60F9664 /* FIRDatabaseQuery.m */; }; + 97EA9C429A2CE5E073DBEB7C3C5BCF86 /* FTupleCallbackStatus.h in Headers */ = {isa = PBXBuildFile; fileRef = F58D16C5FBEE3D3C9EE7D4F75929C633 /* FTupleCallbackStatus.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9864F86F2DB43C52AC4459180299AD40 /* GPBArray.m in Sources */ = {isa = PBXBuildFile; fileRef = 4B850F7DC474EF9A15F3ACEAF70750DA /* GPBArray.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 989072EAAF89F56C19082F03F44BC651 /* GoogleUtilities-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FE4B7054E146828925FC005DB56E8904 /* GoogleUtilities-dummy.m */; }; + 99281102B79D0A64554BF80FEA49FDEF /* FIRStorageComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = E71A396EC91191A023047F9E295CDCC4 /* FIRStorageComponent.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 99654F2630D639F8BB9425F2954D1739 /* FTupleCallbackStatus.m in Sources */ = {isa = PBXBuildFile; fileRef = 39F2F32A7DA93B047FC2CD83E02E59B2 /* FTupleCallbackStatus.m */; }; + 9A441035833444784D7509CA2274A15D /* Pods-My MindUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2ADAA62C81FBD8B8F835FD758F63C282 /* Pods-My MindUITests-dummy.m */; }; + 9AE3332394CB4E7A85A09470B6274737 /* FIRDataSnapshot_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F156EFA0C6D1FF858F72E0773123B1F /* FIRDataSnapshot_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9C38E60FA057D6D1B48890C3B4DC09F4 /* FIRMMessageCode.h in Headers */ = {isa = PBXBuildFile; fileRef = 15918B10BD6CE7C57B16DB55766DE2AE /* FIRMMessageCode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9CA9D429B06966E8603F3FDBAB52E773 /* FIRMessagingPersistentSyncMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = CDF371265A9A6D8E73196A94E4D28CC6 /* FIRMessagingPersistentSyncMessage.m */; }; + 9CFEAE301C59570D6D3DA95230320489 /* builder.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BC27000ADAE777180D767021286CA2C /* builder.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9D03AA38BAF46392D554CE759E1F90A2 /* FTupleUserCallback.m in Sources */ = {isa = PBXBuildFile; fileRef = 69B1781DA481AC22CFA714AD4D223D72 /* FTupleUserCallback.m */; }; + 9D082A4BAD5FFDC3251EF756CA1D2416 /* env_posix_test_helper.h in Headers */ = {isa = PBXBuildFile; fileRef = 1C9262B336C315B62E2E2BBCB9ECB143 /* env_posix_test_helper.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9D1F78E0A3A1BFF5C718B1DFA231C34B /* GPBArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BA38BF03D131A8C606CB78AC6CB85DC /* GPBArray.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9D9834578E28BF7E6BEA2422E9549B2E /* FImmutableSortedDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BB0B1F9F39C57357D2350296EAA5E53 /* FImmutableSortedDictionary.m */; }; + 9DC8CFAA009F051AACF5CB1CAE2BFF4E /* Type.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = A88F71BC1A9F943C034BCC009810AD64 /* Type.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9DFA58FE5A84DF7925398E88CB2DD709 /* FEventRaiser.m in Sources */ = {isa = PBXBuildFile; fileRef = F9CF71EEB7AF86F89B8AE4EE689AC486 /* FEventRaiser.m */; }; + 9E03B75725537F8412899567BA9394E4 /* FirebaseCore-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D9FB7EE240FB526E2B6E1D0ACFAA87B0 /* FirebaseCore-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9E645C345766689851360BC3C0A36CBC /* FCompoundHash.h in Headers */ = {isa = PBXBuildFile; fileRef = 64D9C3082504A3C076123EC5A427666E /* FCompoundHash.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9E867CE47128CBA81E3C374B352E3324 /* FServerValues.h in Headers */ = {isa = PBXBuildFile; fileRef = 5C2A3940C1CF640AD9EB12D78F0AEAF4 /* FServerValues.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9EC35AE5E263F48B43222C73F9569F21 /* FArraySortedDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = D8D66411B1D52F4EEB26FA6AE6A04187 /* FArraySortedDictionary.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9EF75B2E4E2EDFE1D9446E65835535E4 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F891930020EE03609EADEDCA0FD6F6B /* CFNetwork.framework */; }; + 9F8F2160FBFD10AE2A50392D7790174A /* GULMutableDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = D3BF55E62435B01E8C350625673407B2 /* GULMutableDictionary.m */; }; + 9F93A98552CEFCF21E07766F5EAEA70C /* SwiftForms-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 87D05F4B7557FD9A9E830518CB5D0024 /* SwiftForms-dummy.m */; }; + 9F948E3271D72EC2693934AB4E5E36BA /* FIRMessaging.h in Headers */ = {isa = PBXBuildFile; fileRef = A5F1DF0DE04325F03FFC21877D9F2DD6 /* FIRMessaging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9FCC9812B2708EAA4AEE1F9832BBD40E /* FIRMessagingCheckinService.h in Headers */ = {isa = PBXBuildFile; fileRef = FC73B473572AD55A393CF3469D719B60 /* FIRMessagingCheckinService.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9FD03A6F2B880A75B4CD25D166571D98 /* FIRFacebookAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 37A41E82010FCD2D354DE448260E8240 /* FIRFacebookAuthCredential.m */; }; + A08534D62B21CF083053FF3C5EE924D3 /* FIRMessagingRegistrar.h in Headers */ = {isa = PBXBuildFile; fileRef = 9D1DF1BF918CF6CEECA759D75788A242 /* FIRMessagingRegistrar.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A0BD2298246D382B3E5968BD5C1EC331 /* FTupleTSN.h in Headers */ = {isa = PBXBuildFile; fileRef = 1534655F96C2C7D96E3632B7C1979994 /* FTupleTSN.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A0F2AA5DDBC3926C7E50469751856B38 /* FViewCache.m in Sources */ = {isa = PBXBuildFile; fileRef = CF3A590F142F7E04CFCCE40F7894F3ED /* FViewCache.m */; }; + A131243C5128195EE4686EBA911EC770 /* FIRAuthDispatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D9EAD1637B2E283AC5ACDA1E015C325 /* FIRAuthDispatcher.m */; }; + A15C9B6672D8D0F2E252C09899E096FB /* GPBRootObject.m in Sources */ = {isa = PBXBuildFile; fileRef = B8B02B5F674C3C2DB98EF004508CFCC3 /* GPBRootObject.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + A1EA5EFB715B6F66031D21C96A5235E6 /* FIRVerifyPhoneNumberResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 0192E00D386318F5FECB4BB5FC607F7D /* FIRVerifyPhoneNumberResponse.m */; }; + A20ACDAF3DC4F1E98BF027414AC64852 /* GTMSessionFetcher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A9CFB4A25C1A9163B43C9569A6776AF5 /* GTMSessionFetcher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A21506AC3CE435A3EAF0FB9DC704EB92 /* FIRAuthSettings.h in Headers */ = {isa = PBXBuildFile; fileRef = E8340D499EC8097E61282D5B6D61DAB0 /* FIRAuthSettings.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A21B7401B0E0A0135B948EDCE3282E0B /* SourceContext.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 71B41FCA331929B285069B056D11187C /* SourceContext.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A34E0C1DD34D7A2614616C7AD405E735 /* FIRStorageObservableTask.h in Headers */ = {isa = PBXBuildFile; fileRef = FDB044D43FDB91C9E18B19954C2084C4 /* FIRStorageObservableTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A3FFC56572F14E7EE1C87216816949D8 /* FIRFacebookAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F0A45134989F661BACC63DCA7091243 /* FIRFacebookAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A421534A2448E72CE68FC47F85063620 /* FAtomicNumber.h in Headers */ = {isa = PBXBuildFile; fileRef = F78F642663E7302B237D8578707BB7CA /* FAtomicNumber.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A4301C4471C45F2A9A4F6BF8C65E0139 /* GTMSessionUploadFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 54D2205BB0299DF468F8355C100D0647 /* GTMSessionUploadFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A446713CB33544D018DDBE488AC1D07B /* FIRVerifyAssertionRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E20EFABC4BDDD0348F7A103E0A8FDF7 /* FIRVerifyAssertionRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A49EE8F519A4DABE52EF46452FB7F803 /* FIRAuthAPNSTokenManager.h in Headers */ = {isa = PBXBuildFile; fileRef = CB6099DEF2E3EDF5BDE646A402A7223C /* FIRAuthAPNSTokenManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A4AE8E529212651C640D9649EAD0AB95 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + A5725DFB68A04C2F41E1F4C706BB9AA9 /* FieldMask.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 82DF20A0A666925390FA680456D04F84 /* FieldMask.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A5A407C2729A90B75C962AF9BD33E9EB /* FIRDatabaseReference.m in Sources */ = {isa = PBXBuildFile; fileRef = 03EDFA99E6ADFC8587F19A0FD5C27F2A /* FIRDatabaseReference.m */; }; + A5DF4177C85DB26614437E811E08FE87 /* FIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = DAB331FBC7C4E444D49D2095E2B10937 /* FIndex.m */; }; + A5EA29A17C261ED07A110CB9A173F935 /* GULMutableDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 209C44D7A6CAF9D909AE34A0B3351B8E /* GULMutableDictionary.h */; settings = {ATTRIBUTES = (Private, ); }; }; + A6FBD16911AB017EE6CEBDF5043B0039 /* FLeafNode.h in Headers */ = {isa = PBXBuildFile; fileRef = CD56393A1C061A90D9EADCAE84B22F19 /* FLeafNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A70170FC8C111DB64EE4B07287A49DA2 /* FIRStorageUploadTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 102344473F65983D56F8C4612A41F57E /* FIRStorageUploadTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A73A021178D0B3E28768A85ECDA4D236 /* FCachePolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 3463542860D4D784D0B8FE1164F16844 /* FCachePolicy.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A73F734767E6743486C676B21E73248F /* port.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AD51002F5F86EBA67F6340027B559A1 /* port.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A7FD3C6C20D1B714EECB1AB525B644CC /* FIRStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 3D44B58D46428E682FE8499CC2C0604A /* FIRStorage.m */; }; + A849D47CADC35E2A18350D030F91517C /* GPBDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 0547C44086388302572F121590BFF048 /* GPBDictionary.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A85D8986FAC7FA0189C8B305AFF68BE9 /* FIRSetAccountInfoResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 6506C0D8E4A809C7E2AA6AD0EC391E50 /* FIRSetAccountInfoResponse.m */; }; + A86906AF6244D8C1CE33A822BC26683A /* FIRMessagingSyncMessageManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E9FCF84F7BA642F2599D22BCF97995B1 /* FIRMessagingSyncMessageManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A9390FDBA96ACA53CE8F2868305C8EAE /* FIRStorageDownloadTask_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 3EBE5619F4ACC24E1B1CE208BACAECC8 /* FIRStorageDownloadTask_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A97D5FA330E8D8311C8DC1F83E488399 /* FIRAuthRPCRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = AC05B3DB4EDE20A5FD7CE64075AB866E /* FIRAuthRPCRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A9B7AC3DAF79567C8F883352BFED17D7 /* FNextPushId.h in Headers */ = {isa = PBXBuildFile; fileRef = 2C40238EAA192A9251A946077405ABC0 /* FNextPushId.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AA72A358E0E8274E8D3A7702789E4259 /* FIRStoragePath.h in Headers */ = {isa = PBXBuildFile; fileRef = 37516AA7CF7594EF2A97EECB3F648BC3 /* FIRStoragePath.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AA774751DE26F15002F827034BBBE630 /* FirebaseStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A0E3FCADDEE6AF41C98BE9C52E8C2D4 /* FirebaseStorage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AAA6A3680C85C31B477E4C906DE9815A /* nanopb-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FED3152358EC24AC1254184016912802 /* nanopb-dummy.m */; }; + AAB20FC52EF9A97F915B8AC9EAF2B5B8 /* FClock.h in Headers */ = {isa = PBXBuildFile; fileRef = E9F29370AA19CCEBB83FD2748FE606CE /* FClock.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AB3D618502A72118FD94B77559972F94 /* FormTitleCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BEA6BEF99A18E7226D403A8BC1F4837 /* FormTitleCell.swift */; }; + AB591B4E27F0CF1798470C369A571673 /* FTupleObjectNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E332EF6637191BA88B5B349CBC134581 /* FTupleObjectNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AB784186ECECAD178AD4C783CA5741A4 /* FChildEventRegistration.m in Sources */ = {isa = PBXBuildFile; fileRef = 658A768CC068B2D7E13BF84FFC821C7D /* FChildEventRegistration.m */; }; + AB8DDFE38D7B5293556C7A56CACB3CEB /* FirebaseDatabase-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 027F5F2720277F21E85206247776964D /* FirebaseDatabase-dummy.m */; }; + ABA504F9416B705404F4395F56FD924E /* FIRAuth.m in Sources */ = {isa = PBXBuildFile; fileRef = A1D37659A08CA55180F3AA24ED62C072 /* FIRAuth.m */; }; + ABAB683C7C96985D3D17CAC333385688 /* FImmutableTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 334A73053CB07EBAD403B0A20B0FB4D1 /* FImmutableTree.h */; settings = {ATTRIBUTES = (Project, ); }; }; + ABBB08E9C12864DD9EFBDD0A37E90A34 /* FIRStorageGetMetadataTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 87B8DEE29C9DF557484295F12A135E87 /* FIRStorageGetMetadataTask.h */; settings = {ATTRIBUTES = (Project, ); }; }; + ABBC5BE4B6A2CED9BFAC186DC0BE2906 /* options.cc in Sources */ = {isa = PBXBuildFile; fileRef = 814BDBAAB7D6AF52DD7C730CB57ED235 /* options.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + AC5D118A0E6B91C906A8703307E999ED /* FTupleBoolBlock.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A80624208D997D30C2C97FF658187DF /* FTupleBoolBlock.h */; settings = {ATTRIBUTES = (Project, ); }; }; + ACC05312D7A505AD2942AC3A9DE928E5 /* GPBUnknownField_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B5803208593B4D179BEC1EB11FFC53C /* GPBUnknownField_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ACFA8328FABDD65ED17C942F663AC616 /* Wrappers.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = ED57FFADAE2E118F4B39FED169254F9B /* Wrappers.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AD09EE334BCFD006DBAAAB20ABC6F409 /* FIRMessagingPubSub.h in Headers */ = {isa = PBXBuildFile; fileRef = 76E425DE58AFB1DFDD7497FB60D1E793 /* FIRMessagingPubSub.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AD37135DC0DB285AFC99A22A3F897490 /* FormSliderCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABED8087C7A90B3FD277BAE0632749F8 /* FormSliderCell.swift */; }; + AD63FBD4D1294275A34F7BCCA484DAFB /* FIRStorageDeleteTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 28202CE327903B58CDB7331A14E79DC1 /* FIRStorageDeleteTask.m */; }; + AD713AD4352D0437F392D8A81D71F4DA /* FCacheNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 203AD3FF7A567A2E94E4B935B88C0A08 /* FCacheNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + ADACD46FA2F947B04FB1B64459ABC9C6 /* FSRWebSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = 0C133B09CE3EB5E249AAC9A970FD6D8C /* FSRWebSocket.m */; }; + AE067235520EF8E2FA01D07CCE0B123F /* FIRMessagingCheckinService.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FBD462DDA28EDB862ADCA7FCC50527D /* FIRMessagingCheckinService.m */; }; + AEBA9FAD26195F4E46488F4A9D3B9A81 /* FIRDatabaseConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F023A3AA7B317ABDDFF07E64B3FFE45 /* FIRDatabaseConfig.m */; }; + AFAA7A560C7373F44A9AD71CA491F37A /* FTransformedEnumerator.h in Headers */ = {isa = PBXBuildFile; fileRef = 999ADEBF7B61A4065079C381CE6B7DE2 /* FTransformedEnumerator.h */; settings = {ATTRIBUTES = (Project, ); }; }; + AFAEE5182834B4C8EFA6D64690E031AF /* GULNetworkConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 24EAD08A106190E74699EE263115EA87 /* GULNetworkConstants.m */; }; + AFCA0EFE9E8B6485C7A8F7CA43D602BF /* FIRStorageUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 17B0C073D7E0610CB87572DA00D591D7 /* FIRStorageUtils.m */; }; + AFCE1D5598585C68B9343DB5D8EF6399 /* comparator.cc in Sources */ = {isa = PBXBuildFile; fileRef = B50A16C7653FEFB535C922A6E394F409 /* comparator.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + B010D7EA72F68E5C8800E592430EB6D6 /* FIRAuthAPNSTokenManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A971443D94F15814ACF2372DEC544C9E /* FIRAuthAPNSTokenManager.m */; }; + B08F493AB57C446D1EC511CEB2C7C7F4 /* GULReachabilityMessageCode.h in Headers */ = {isa = PBXBuildFile; fileRef = 195F2A114F33FC39E8EE0AF6ECE74737 /* GULReachabilityMessageCode.h */; settings = {ATTRIBUTES = (Private, ); }; }; + B0B91BFE07C9B52AEBDACBED9628E033 /* FIRDatabaseComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BDBF6A6577932307CBAE680E3C2D0DC /* FIRDatabaseComponent.m */; }; + B15FAD9698A196CC3BB3AF6C8667174F /* FIRStorageTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 682F99F9C42A5FE4D526C915C7792F54 /* FIRStorageTask.m */; }; + B15FC1F8F8DC423C1D1B589E60F544F1 /* FIRSecureTokenService.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E38B04C7F997C0C975D2B0D29941212 /* FIRSecureTokenService.m */; }; + B181110C59D8DD6EFE5BD1F6078FD500 /* FIRGetOOBConfirmationCodeRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 7DD22742CF31B2734B421A041B5F23FA /* FIRGetOOBConfirmationCodeRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B212A3AF5AE14BC07F01E56C6081367E /* FIRMessagingUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 143163CDF7251156D7FE094D45C15FEB /* FIRMessagingUtilities.m */; }; + B21554D5A36CBBD9B6CC65BF5A87DED0 /* GPBMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = 166AEA29274E16405F538B6E3FB9F341 /* GPBMessage.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + B24AE7B91624027EA6971C6EB6154423 /* FIRDatabaseConfig_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = D9356AFA47E58DAC25375A606AEBDD04 /* FIRDatabaseConfig_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B254C3FDDF65B8AF8E5E3B17630A4109 /* FIRUserMetadata.h in Headers */ = {isa = PBXBuildFile; fileRef = 17DE2AD6AD6B952E14BD83D4D76F3E5A /* FIRUserMetadata.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B29B2FF52E45F040E233DBE345D93C3C /* iterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F32152C8DD47543CFEEE86EC20A8D54 /* iterator.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B32809CB22D971969762CAE8E96DF24E /* FIRMessagingSecureSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = B60A88AD3A3288AB7892EBF19A5E3DD7 /* FIRMessagingSecureSocket.m */; }; + B39394809F93B95B0CE1A2827815FCD1 /* FIRGitHubAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = BC6957CC5CFB8C0C21FB9630CB797E96 /* FIRGitHubAuthProvider.m */; }; + B399205633C66F3A49FA4FEF210EF899 /* GULUserDefaults.h in Headers */ = {isa = PBXBuildFile; fileRef = A4A441974FF8146A16F5356A074A3BBA /* GULUserDefaults.h */; settings = {ATTRIBUTES = (Private, ); }; }; + B42296DE72D116C0C1A22BA451DC4E39 /* FMerge.h in Headers */ = {isa = PBXBuildFile; fileRef = 299DF18554F4A28DFE1C9CEF8D10FDD5 /* FMerge.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B42B2F1D39576EDD7807959618872CE6 /* FIRVerifyPhoneNumberResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = EAA423220A289264800007CD89C00078 /* FIRVerifyPhoneNumberResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B42C14815D5EAB949909816B361D918D /* FMerge.m in Sources */ = {isa = PBXBuildFile; fileRef = BE58957B596510DF2E8953AC74AD5FE3 /* FMerge.m */; }; + B430087BF184C63ABD230D79C25CD2AA /* FormSwitchCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26D74751413758177B3A96C50FF7FF7D /* FormSwitchCell.swift */; }; + B431A77F62F1714B3B3A47FF0BB3B237 /* FRepoManager.h in Headers */ = {isa = PBXBuildFile; fileRef = DBEBD39CF1E6349AD5DA85B84BC7DFCF /* FRepoManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B50F7E98D2795259EF39E7E44FECDA83 /* Any.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 086B92F32AC12F7847B682F04095440D /* Any.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B51FB50D2F16065E0790C48862B3F57C /* FIRAppAssociationRegistration.m in Sources */ = {isa = PBXBuildFile; fileRef = F1AE2FDC03291973313CBF81B1338212 /* FIRAppAssociationRegistration.m */; }; + B563D3BC17F883C4BE12BA863FCFD367 /* FIRVerifyClientRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = D89CBF341E031516C3B740A39C2A597D /* FIRVerifyClientRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B5AA7832115EB1F7CD229933A9EF6DEF /* FIRBundleUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = E9A0AA959E20E29F08FC62B2BC5D5DD9 /* FIRBundleUtil.h */; settings = {ATTRIBUTES = (Private, ); }; }; + B5CE7589714FE2CD21F1D0B1BDFDA65A /* table.cc in Sources */ = {isa = PBXBuildFile; fileRef = 33D03EFE889DEDA5D7BB31722B237A80 /* table.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + B5E3E3FA315D33B21B5F3344B6C824A0 /* FPath.h in Headers */ = {isa = PBXBuildFile; fileRef = 44338CA1F8AA10479C391E3E8D0E9C1C /* FPath.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B62A8D5961AD2F9A03B21D323C62ECCE /* GULNSData+zlib.h in Headers */ = {isa = PBXBuildFile; fileRef = 2EFCA2B98B8F29A0EC46C45E86B06459 /* GULNSData+zlib.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B68DE0A647FBC539D64F54CEEB48457E /* FIRStorageErrors.m in Sources */ = {isa = PBXBuildFile; fileRef = CE0A99214530B0FAF71E7F69ADE4F9B5 /* FIRStorageErrors.m */; }; + B6E33D8A116746907694A0611DF86F3C /* FIRSendVerificationCodeResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = BF57C0F85A406C3D449F4E1AF68D0A9B /* FIRSendVerificationCodeResponse.m */; }; + B75837C0F6C779AC4282214C006E2216 /* GULAppEnvironmentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 453054BE5330275352B536CFAF6B76CF /* GULAppEnvironmentUtil.m */; }; + B8581A8BE59EACD6AA0CCF0325A7A449 /* FIRStorageConstants_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 5383E534FCBF0988CDB5DE655E026D79 /* FIRStorageConstants_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B877236992FA436C2E0BD5B6D1FE24C2 /* NSDictionary+FIRMessaging.m in Sources */ = {isa = PBXBuildFile; fileRef = 35ACEC850EA6B8AF4B8B76044A429AA6 /* NSDictionary+FIRMessaging.m */; }; + B88F11FC4243CEB0EE2B1416FEE6706A /* FIRGetAccountInfoResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 26C18E86BC3C699C7D43F84F8E6ABBA6 /* FIRGetAccountInfoResponse.m */; }; + B8A03A7705827133E13713A22F2A0A31 /* FirebaseStorage-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D5CE9FDA9DE67B0F21F0E0F042EC9399 /* FirebaseStorage-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B97715B074DD015049F7C6056713E29B /* FIRDependency.h in Headers */ = {isa = PBXBuildFile; fileRef = 7BF676BAC287FD9AF2842E1602416108 /* FIRDependency.h */; settings = {ATTRIBUTES = (Private, ); }; }; + B9EAE81286BDB8C5C9FD40BA7568F1F6 /* FIRCreateAuthURIResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = FFAB81D84005BC13B7205C87F1074E07 /* FIRCreateAuthURIResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BA29BEDDAA424A73FEDA03DB0EBA8F35 /* FIRStorageGetDownloadURLTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 190C6A526425A5A9EF0976A2C466B402 /* FIRStorageGetDownloadURLTask.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BA43D9004D1FBF13D712CED11E18F955 /* FIRAuth_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = E1CECB23F7293747C87E09C0248F6AED /* FIRAuth_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BA9174F13BB2ED25C493244D3B03611C /* FIRAuthAppCredentialManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CF6C4A834EC0A2207726AB45C8E5DF0E /* FIRAuthAppCredentialManager.m */; }; + BAE01E725AF8874AE1DB20B03A6203A2 /* FIRVersion.h in Headers */ = {isa = PBXBuildFile; fileRef = 796A9E6A5DF0679ED69FE7F4CDC25199 /* FIRVersion.h */; settings = {ATTRIBUTES = (Private, ); }; }; + BB051BF78681E74C549656CBE3D890A8 /* FIRUser_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = CD321F3BDAC9E5C193BB7538DB15F36B /* FIRUser_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BB31B856BA4B23746DBCBB3AD1A60495 /* FIRIdentityToolkitRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = CB5E5EDC823A0512816F5F6A8AAE7BCD /* FIRIdentityToolkitRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BB50D1AEFD09F9A1DDA8B02A0FEB3060 /* FIRGitHubAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 08BE0BDCDEF190A30B893BEC5F1A9358 /* FIRGitHubAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BBD97223BD1446C5294CFD97217EB9C8 /* write_batch.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E04F48A3C2F6EC156E49CC1BD8AFA0D /* write_batch.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BBF82F880B8E1C735B7E428ED3663BCB /* FEventRaiser.h in Headers */ = {isa = PBXBuildFile; fileRef = F5F63D1EB7FA70A254BE597E678D416D /* FEventRaiser.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BCC43130C0575C0965175C4991E243E7 /* port_posix.cc in Sources */ = {isa = PBXBuildFile; fileRef = 178235193981793B5A1306D65CC58041 /* port_posix.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + BCDA8D479323B300327EB434562109DE /* FWriteTreeRef.h in Headers */ = {isa = PBXBuildFile; fileRef = FEC70A46FDF74AF507252CDF69F4337C /* FWriteTreeRef.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BD60DDDA106B830D0D232D3348316B40 /* FIREmailAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 5035A64EE2A9A3DB9A03376F395A3702 /* FIREmailAuthProvider.m */; }; + BD6D70EFF7DD0E5BB20BE976C6BBEDD9 /* SafariServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8CD5C008865F5A9168D53CDA45E6740F /* SafariServices.framework */; }; + BD773A6159443E6B37BE7F5BAA306EC5 /* FIRAuthTokenResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 8086976E909F242ED65F58A319245ADD /* FIRAuthTokenResult.m */; }; + BD9233CB33E367ACBEF919FAD239E6AB /* FIRAuthRPCResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = DFAA5FB160375FF5C55D7C4D8FEAA640 /* FIRAuthRPCResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BDBE450803852671A91A066EE21DF6D0 /* GPBDescriptor.m in Sources */ = {isa = PBXBuildFile; fileRef = A80F78145127A307E9C1096BA11DA24F /* GPBDescriptor.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + BDD9828847D4DD7EF971F67C68418B64 /* FIRServerValue.h in Headers */ = {isa = PBXBuildFile; fileRef = 786FC9011A3F7E09EB395D9E4BAC2FA2 /* FIRServerValue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BDDA69765D87A7963F202AE241B89763 /* filter_policy.h in Headers */ = {isa = PBXBuildFile; fileRef = A3BF85E75A6FABE9D104B8E0255D2E0F /* filter_policy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BE22C23DDEBA277761380609E3368B64 /* FIRAuthUserDefaultsStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = C5578903E5AF1A9CA32A01FFF0D569CA /* FIRAuthUserDefaultsStorage.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BE8A86EADE6F55060A34AC780AA02110 /* write_batch.cc in Sources */ = {isa = PBXBuildFile; fileRef = 5223757BD175F800FD48E7DE0E939530 /* write_batch.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + BEB10ABF326685345381D2EB834029DB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + BED2AE2940B5BDFEED8DC328B94EDBF8 /* FTuplePathValue.h in Headers */ = {isa = PBXBuildFile; fileRef = 2FF4A55D674F3F971478CE8C9D07E621 /* FTuplePathValue.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BFD1527384C8AB7685D3DADCC9ACEBF0 /* FIRVerifyClientResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 909BF2B1ECC1C9990B47F744DBFE4353 /* FIRVerifyClientResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BFD9303E479CEC6B0B47F68FD2B27D8A /* GULReachabilityChecker.m in Sources */ = {isa = PBXBuildFile; fileRef = D616343B4F9F391E6FEA8F0DECC1E7C2 /* GULReachabilityChecker.m */; }; + C09BD9A434F0B43F74D694B7F96E55A1 /* FImmutableSortedDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 0C7859524A87E234251F0B720F52F719 /* FImmutableSortedDictionary.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C0CA1713C205A48A4C2899559F1E7322 /* FIRVerifyPasswordResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 7635E3F9E1F28E2FD77AD02BFB30ED18 /* FIRVerifyPasswordResponse.m */; }; + C1484F17304997F3ED1FD80A60801310 /* FIRGetAccountInfoRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = F2FADE2C536AB93A60E734718FD411F7 /* FIRGetAccountInfoRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C1579705A30E8A4283F5EDC8FF17E722 /* FormBaseCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCB3CE399BE35A4E8F9B829CB8F18A16 /* FormBaseCell.swift */; }; + C158CEB5D86B674A8465E4E728AF8B07 /* FIRStorageConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 316D8A7A00F10D77D5E5B7F79B7770D2 /* FIRStorageConstants.m */; }; + C1891F0068E50A3CE1F4CA9773FC1106 /* FValidation.m in Sources */ = {isa = PBXBuildFile; fileRef = 1929AA13F6B9C086778B2797199BBB2B /* FValidation.m */; }; + C1C5D1578131CB36F40DA4CD491FDEEA /* FLevelDBStorageEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 1F867F22C2B7BAAA7F6FB2880B592586 /* FLevelDBStorageEngine.m */; }; + C300176A27337A7100CAEF0C46090DCE /* GtalkCore.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = A54BE9E44DCB1F38C08F562BD72CAE85 /* GtalkCore.pbobjc.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C356F7ED55C844AEA0454B1C20F115F8 /* Protobuf-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F3CD7429816330A075E23E1CD8A04B36 /* Protobuf-dummy.m */; }; + C37C956AFAF1B1D8067CFD3EBBA2B249 /* FIRVerifyAssertionResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E7DE789305AEF826F8350378348A196 /* FIRVerifyAssertionResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C40F384DBB2B9953A9563C0F62A061AC /* FStorageEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B1B2B22C6DC5738A70F2F6D590BEA8C /* FStorageEngine.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C414B72AA07E409F1966DCD4F1D0467B /* FTupleRemovedQueriesEvents.h in Headers */ = {isa = PBXBuildFile; fileRef = A47C3AB0A9B76782489F5945F55343BB /* FTupleRemovedQueriesEvents.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C46B7BDE25252D8EB990DEB9FE7CD98A /* pb_encode.c in Sources */ = {isa = PBXBuildFile; fileRef = DC7302524ADB8DC85494B6AAD3CBA1D8 /* pb_encode.c */; settings = {COMPILER_FLAGS = "-fno-objc-arc -fno-objc-arc"; }; }; + C48EB465AA17C95088814EFE0393D6BD /* log_writer.cc in Sources */ = {isa = PBXBuildFile; fileRef = AC67F7B153F19CD9D494C50213CC1B3E /* log_writer.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + C4CC507BAD9328C705A2DD380EF7A743 /* testharness.cc in Sources */ = {isa = PBXBuildFile; fileRef = 2873E606F0C6C216CEF364B6C5008F42 /* testharness.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + C4CFD31500D821D8CC4057DD4A6FCCE5 /* FTrackedQueryManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 0904C46A7FA089C66B87D70AF0688AA8 /* FTrackedQueryManager.m */; }; + C5E18F0229FECB6A224E9BB84B24D01B /* FIRStorageTokenAuthorizer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5535B79D79A1DB6E12BED6FEEA04B485 /* FIRStorageTokenAuthorizer.m */; }; + C6116CF8DF725EF3D2EF5D8C64793D94 /* FMaxNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 5DD690A210A0BA32F0BF15C1E07B4A65 /* FMaxNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C618198B2C60599D8145F46F099AA22C /* GTMSessionFetcher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 34E37E86AAAB7B5AB34F165B3C259058 /* GTMSessionFetcher-dummy.m */; }; + C61F7E477F6279C45916FF4B21980000 /* block_builder.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6A978CCB0F810856629565567CB0B1DC /* block_builder.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + C6566B15A07342D13697FF1A12CA5C13 /* FMaxNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 246FADA5C8D2648540D64611F12C83F1 /* FMaxNode.m */; }; + C66864565E46E811E7201FE5D59030FB /* FViewProcessorResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 880A5D3DF4E4D6D8C3FE7C96B0B2BCAA /* FViewProcessorResult.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C6692625E63BC08E12CD9A7D370FF3B1 /* FIRDeleteAccountResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E6EEACCBF201D7F886D030A77A7A82C /* FIRDeleteAccountResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C6AAA96E9F95646F5B19AA8CA8C82D96 /* pb_encode.h in Headers */ = {isa = PBXBuildFile; fileRef = A9A58585F2C08E9463E0F2DC3EC61173 /* pb_encode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C6AF34A3108D017F82436A59455898C2 /* FIRGameCenterAuthProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 74E0D6E907564B3A142EAA69A8541AD6 /* FIRGameCenterAuthProvider.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C7158D53D2369C16BE87D63F2DF69FA4 /* FIRStorageMetadata.h in Headers */ = {isa = PBXBuildFile; fileRef = CEA0478245F572D019A39A44DE52A3A4 /* FIRStorageMetadata.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C7283CB7A4B5D66F5A00DD9461455EA9 /* testharness.h in Headers */ = {isa = PBXBuildFile; fileRef = F22610E4772184F5CBC2C803828100CA /* testharness.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C73D787DF2524203C4A652518756B232 /* FEventEmitter.h in Headers */ = {isa = PBXBuildFile; fileRef = B5A15BC3357E674F08C9999C7D329D3D /* FEventEmitter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C7A1DE80ACB2BD2D4B21508AF225D665 /* FPriorityIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = DEE1195481C3E699963E947E9FDAD7EA /* FPriorityIndex.m */; }; + C7B13BA4CCC6367AC048F334FEC48E52 /* FIRAuthInternalErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 99AC8DEBC31A6F60675A164487CD70F0 /* FIRAuthInternalErrors.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C7E3BA8A222F6E68E31AC841439CAF79 /* FIndexedNode.h in Headers */ = {isa = PBXBuildFile; fileRef = DFF02281941C12B08E8712F2DE9DC391 /* FIndexedNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C8313C281C9825C9EABE1DBF7B3F2C2A /* Empty.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = BC564D3F08952BAF72AA3D8FA599A413 /* Empty.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C844AE38BDC6715DD6EE51E916387384 /* FIRStorageUploadTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 8583A2B8E76D50FAD075A623EF4D16DD /* FIRStorageUploadTask.m */; }; + C8A8AA89B97E1F1AFED2DF787DEF26D9 /* FCancelEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = 74E740E1ED09434A0A93BA9D4953AB65 /* FCancelEvent.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C8CB64DBC662A8F8B98E23357939C9A6 /* FEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = 7971586793756023D72E620D4BE9E456 /* FEvent.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C8DD81A987EDF071FB3CDBBC1F189B0A /* FIRAuthCredential_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = D9A33F10F6D5631362A4E2C21DEEAB0B /* FIRAuthCredential_Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C8EC2232444A2D67721770383755671C /* FIRAuthExceptionUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 300E08C04185ADA1E87FE6C0D81A10E8 /* FIRAuthExceptionUtils.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C90D9A2FF2967943932118B78E7A9CCC /* FIRMessagingContextManagerService.m in Sources */ = {isa = PBXBuildFile; fileRef = 262865D53F46E4528F6B67FF9DC6A479 /* FIRMessagingContextManagerService.m */; }; + C91E8F780C2E6979A0801F1B1073842D /* FRepoInfo.m in Sources */ = {isa = PBXBuildFile; fileRef = 127AF1BC36CC21E5614940AA4087D2E9 /* FRepoInfo.m */; }; + C9533158E00437EDEA876FC9E8D84752 /* FIRMessagingLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 34AE0C022045C233A6AA55DF5C66D612 /* FIRMessagingLogger.m */; }; + C98E0142CB91C34E929C9DE9FBF6D224 /* filter_policy.cc in Sources */ = {isa = PBXBuildFile; fileRef = 7861ACAB61D863B75747C507485CF5FF /* filter_policy.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + C9C0B4BB9BA06272DB368B8614330EBF /* FormErrorType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A1D1A56E980A843F4C35E043C9858B9 /* FormErrorType.swift */; }; + C9E1CE53DAC98165EABA11D880683996 /* FOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = EE07AE37AF13904CAE7EB4AFEA96A9DB /* FOperation.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C9F9E263A24E8AE7BF2935B7ABACC1A0 /* FormRowDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21519CE5EB78FDA959307B63623B7289 /* FormRowDescriptor.swift */; }; + CB527332638B18AED5B739BE840683F1 /* FIREmailLinkSignInResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D650E258391748C898E6F33D5F2942A /* FIREmailLinkSignInResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + CBD9D9FEF949FE5836428B658521B61F /* FIRBundleUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = FF3583499DA2598AA2E4C1B876EFC6DC /* FIRBundleUtil.m */; }; + CC1D74CF5040C22FCAE1EF11D747F41E /* FIRAdditionalUserInfo.m in Sources */ = {isa = PBXBuildFile; fileRef = CFA8257B2CAC756753E55E997D0374B3 /* FIRAdditionalUserInfo.m */; }; + CCA187E70B5B329E24221A04EAA3D921 /* memtable.h in Headers */ = {isa = PBXBuildFile; fileRef = 676357AD124D2145D88CF5C3AEDE005C /* memtable.h */; settings = {ATTRIBUTES = (Project, ); }; }; + CD3B6B02BA77A60B2D345BFDF78DF43E /* FIRMessaging.m in Sources */ = {isa = PBXBuildFile; fileRef = 19BFB803A0CA8832F957B481C492303E /* FIRMessaging.m */; }; + CD6C33BFBA4C3D155C2072F77FCD1FD2 /* FCompoundWrite.m in Sources */ = {isa = PBXBuildFile; fileRef = 31D63EE25A257F5309562EBE3F5BDD37 /* FCompoundWrite.m */; }; + CD88C338FCBD71DF4640CB6ABDD89991 /* FCompoundHash.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C0CE893E96EBB13E04CA4D4B62030BB /* FCompoundHash.m */; }; + CD8B4B5DE997B41ABF856CD0BE8F6E44 /* FEventGenerator.m in Sources */ = {isa = PBXBuildFile; fileRef = B323034EAD6CEDCD35A420C6F0EA58C4 /* FEventGenerator.m */; }; + CDA69EC5212E7212B91D944E86567F53 /* FIRMessagingClient.m in Sources */ = {isa = PBXBuildFile; fileRef = FDE8721AA1451531A2BE7D5A17E015FE /* FIRMessagingClient.m */; }; + CDBA72F70214E97B05B346571C061516 /* logging.h in Headers */ = {isa = PBXBuildFile; fileRef = EBAFE747641CFE19EA7DD3E3143DC52C /* logging.h */; settings = {ATTRIBUTES = (Project, ); }; }; + CE4956F0A78784911D47BCD2DAD84623 /* dumpfile.cc in Sources */ = {isa = PBXBuildFile; fileRef = 0F561C68BAE176C5D0E278CE58FDDCD5 /* dumpfile.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + CE6EA5939A431EAE565CEB678A197405 /* FIRMessagingLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 46079141822DE20B0FF0729023B40DB5 /* FIRMessagingLogger.h */; settings = {ATTRIBUTES = (Project, ); }; }; + CEC8D863FA449477FD7C4F059DCEF51C /* FTreeNode.h in Headers */ = {isa = PBXBuildFile; fileRef = F36514100428C5491F827F9CB81CEA6F /* FTreeNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + CF0D114993D521DB3B8DD3B313094F2D /* FImmutableTree.m in Sources */ = {isa = PBXBuildFile; fileRef = 7DC9FDF211772BFF5911D9544841884F /* FImmutableTree.m */; }; + CF5531D76E8EAB68B67F2DAD7DAB2ECC /* env.h in Headers */ = {isa = PBXBuildFile; fileRef = 44976CFF5764982B4FF99FC51761D657 /* env.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CF8A6FCAE3F7F5BF198B3F0B06884918 /* FNamedNode.m in Sources */ = {isa = PBXBuildFile; fileRef = D1BCA22721EC82476AD1ECBFFC47FDE4 /* FNamedNode.m */; }; + CFDA8C7A2776F27B257992ACFA1185DE /* GPBCodedInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 056AAEE5687F136583F2D9487DEEA595 /* GPBCodedInputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D069528278DA1D52E3EBE5F869D0C486 /* FIRAuthUserDefaultsStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = C7664078AAB63061F0485623401B4036 /* FIRAuthUserDefaultsStorage.m */; }; + D10ED50CAAF3832782ACF3AAD6D75E6C /* FEventEmitter.m in Sources */ = {isa = PBXBuildFile; fileRef = 1EEE2FAABA3D4CDED41BA149DDCAAC86 /* FEventEmitter.m */; }; + D11731E80E979B54DE4D0EAE75A0BB31 /* FPersistenceManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 23FC93A0EF861393C6EEE18DF78305C4 /* FPersistenceManager.m */; }; + D143A48E638AFDBD788EBFDC833E04BC /* pb_decode.h in Headers */ = {isa = PBXBuildFile; fileRef = F5CFDBA1A91011693D868DC825A161AB /* pb_decode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D148E6E258FC6F12CB003213A394CC27 /* mutexlock.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E06E73DF47291251ABD36E38BBA14B3 /* mutexlock.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D1C5A46153BF21B07533D5E47B7FC491 /* FIRGetOOBConfirmationCodeResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 1FA4FBB774B84B9517944CCF8010D41D /* FIRGetOOBConfirmationCodeResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D25EA3543993A4580FC33176E8012D79 /* FStringUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D95EAFED5C6BABDD29651946338BA3C /* FStringUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D2743BEAE5054ECA336FC2A9F7C7B4D0 /* FValueEventRegistration.h in Headers */ = {isa = PBXBuildFile; fileRef = E5C19961FA70611535C5C36236F23D9C /* FValueEventRegistration.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D27539497AD3B159A1D756D9EE24295C /* FSnapshotHolder.m in Sources */ = {isa = PBXBuildFile; fileRef = 50630886A093E6270164CC7ECE54E54E /* FSnapshotHolder.m */; }; + D2E54B77503C52E26575B9DE2827DF2A /* c.cc in Sources */ = {isa = PBXBuildFile; fileRef = D64CE5DB6A98F389176B81AB143A03A1 /* c.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + D3AA9A65A800E8DD3170DD6258E922F9 /* env_posix.cc in Sources */ = {isa = PBXBuildFile; fileRef = 2CE2AFE0717F5787756256BC9B37CCDE /* env_posix.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + D3C89629225077014D01F1F1337842F9 /* FIRGetProjectConfigRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C8725D11133377692FA563EF613C7C6 /* FIRGetProjectConfigRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D3DDF4ADB4EF49D92A32F6FC0E73C7CF /* FAuthTokenProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E52BD389E6CE1A1DA968B1065FE7CEA /* FAuthTokenProvider.m */; }; + D402A12D3ED43E23EFC437DDEE012F6D /* FIRUser.m in Sources */ = {isa = PBXBuildFile; fileRef = 82B3C6D58D32965D5CB48FD4B37BA1A4 /* FIRUser.m */; }; + D44C4FB4CA27374589D832296CDA9E24 /* write_batch_internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 7220181B4FADE1BE7B6FDD9CA2FF21E6 /* write_batch_internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D4AD505B3781844D264770E4100919DD /* GPBRootObject_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 93B79A48B8E85E3CEFE8C0D22E6F043F /* GPBRootObject_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D51F6B9C6F3F7F6BCEA88A7C45F34C44 /* FKeepSyncedEventRegistration.h in Headers */ = {isa = PBXBuildFile; fileRef = DC5BCCD19D83503611CAFE7CCBF2D059 /* FKeepSyncedEventRegistration.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D53F8A96A3A82548FA5B748DED22E71F /* FormDateCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AFE8F37C120A82C78B58A29BCB9E818 /* FormDateCell.swift */; }; + D552F099EE8DD72F421E7285F72EB7D3 /* FIRAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = EFE54910E41A84C06DFFFD3C00995957 /* FIRAuthProvider.m */; }; + D57E07440AC52FDA7F5AF53332978343 /* GPBWireFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = 949FB977FA39EFF38D2F6B5508DF4AAF /* GPBWireFormat.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + D5EE07D6222CD052D449B12A82AD2660 /* FIRStorageUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = C7B4E1AC707BFEC7671666CC0530312A /* FIRStorageUtils.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D63B77317FAD75B5F54E67E7E04FF9EA /* FirebaseCore.h in Headers */ = {isa = PBXBuildFile; fileRef = 28408A35C59B8DAEAB6216D22C3FB49D /* FirebaseCore.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D6A236A02392872BA73D7269B648406E /* FIndexedFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E84074B8CAC11CFC16E8F61FCDA55D0 /* FIndexedFilter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D6C4BDBDDC3A5DEB9FB340D9F4B6E0CC /* FNamedNode.h in Headers */ = {isa = PBXBuildFile; fileRef = E70889143006716935C52FEB99418BDE /* FNamedNode.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D6D8C68D73E2EB24ABDA9142B60AD773 /* FRepo.m in Sources */ = {isa = PBXBuildFile; fileRef = 2DDDD71E6DB015FCA8B621580ADC5452 /* FRepo.m */; }; + D7001F1A9D396BDC44E5A05ED159AFEE /* FIRGitHubAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 769FB4DFF434F108F981154B69D3C883 /* FIRGitHubAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D712BA1D63DCA52787FB6295E04FC41A /* FQueryParams.m in Sources */ = {isa = PBXBuildFile; fileRef = C1FAF04CD4B2CBB223911ECA4F6BD75B /* FQueryParams.m */; }; + D7891EA68730A4A28A184B6A99571723 /* NSData+SRB64Additions.m in Sources */ = {isa = PBXBuildFile; fileRef = AE8A0C83E51D1224B0CFB2B9112CD50F /* NSData+SRB64Additions.m */; }; + D8221A14E706A3DB0A85E793A99374E2 /* builder.cc in Sources */ = {isa = PBXBuildFile; fileRef = C2E41B74D9C1720A05CE0AB191067AFE /* builder.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + D85EF192B8C1D8E9B6A7E06815055652 /* FRangedFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = E2DC2EB959470FCEF39EC7C80F5316B0 /* FRangedFilter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D8FC1484177D763EA88D86B00BDB808F /* Pods-My Mind-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3DA0DF0B81ED2E59E65402AA12829CDE /* Pods-My Mind-dummy.m */; }; + D90EECF6F36681386D534D5FAB0C9F10 /* FWriteTree.m in Sources */ = {isa = PBXBuildFile; fileRef = 275E67D0B7860BEB886BA56746C86448 /* FWriteTree.m */; }; + DA1FF83D60E6D712581112569DD294A8 /* GULNetworkLoggerProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 4246B1BF52A26AE14B7A2194FA5E3F47 /* GULNetworkLoggerProtocol.h */; settings = {ATTRIBUTES = (Private, ); }; }; + DA30B636C4FE2B431A9D764A2ED0466C /* FIRAuthErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 95334361346B957D96FDAF00D5ACED6C /* FIRAuthErrors.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DAB46EECC9CD909B9D94A99C5199B404 /* FIRStorageGetDownloadURLTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 2546E3E1838E0C58EBD972F9CB875E1B /* FIRStorageGetDownloadURLTask.m */; }; + DAB5C35644D90288ED1E80678F3FACDF /* FIRRetryHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = B0B5A5553CFB4456F7BC8E2B97CC0644 /* FIRRetryHelper.m */; }; + DACBFF3914E67388390A40ABFBA75E9F /* GPBProtocolBuffers.h in Headers */ = {isa = PBXBuildFile; fileRef = 624733EE470333F41A1A1BCC618446EC /* GPBProtocolBuffers.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DAEF6555B3B845FF7E1B17D126042F58 /* table_builder.cc in Sources */ = {isa = PBXBuildFile; fileRef = EAEE4CEDCD6C42826ACDDFADE4DF0FB2 /* table_builder.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + DB7C28FA169A53CB692D201570BDB3A4 /* FViewCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 7F9F88FADC98B9224D1E76814149FA28 /* FViewCache.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DBA22EFE562C00D58CA8117752A4CCBE /* FIRAuthNotificationManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 1CA6D0718F1BE8F2CD2B515567E26AB1 /* FIRAuthNotificationManager.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DC25ED33ED42D631129F8AA17F3E1A29 /* FIRGameCenterAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 8C7AF4806829E1A7FBD4AC2CF543B2DA /* FIRGameCenterAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DC40B66CE40C4E3B04D2F68C8209D1B6 /* GULReachabilityChecker+Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 8D7BE7EA6367DA949086D526736A7DE0 /* GULReachabilityChecker+Internal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DC4AB5B5940C35B49EB39971AB70704A /* FIRMessagingCodedInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = CCD534072CDFAE76358EC05074E7A1FD /* FIRMessagingCodedInputStream.m */; }; + DC7AA6521AA6E9CC4AA32E2114E65896 /* GPBCodedInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 634AC4F4C75AE1D5C975FD26D60B8E3E /* GPBCodedInputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + DCCDE080BF1C3B4EF73A04E20D49E718 /* FIROAuthCredential.m in Sources */ = {isa = PBXBuildFile; fileRef = 6056409035CBAA33FC4C1E992C685A4D /* FIROAuthCredential.m */; }; + DD387E81AFD93294E3F4959E64B99520 /* FConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = 0981E2FBA71DA3248061103B90F82F5B /* FConstants.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DD8964C5E56F3CFBBF201C19257D69B0 /* FIRAppInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F38BB1D2C2DC6C63F1A53730F4F5F50 /* FIRAppInternal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + DDE08ACF73840138341000C61CA4490C /* db_iter.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6C021F5E4C2CF0638FF24E140E7DCA92 /* db_iter.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + DF15FDB3F4D296543616C1E6A56095AD /* FormOptionsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC93543560F23E0335E10D04FC89916A /* FormOptionsViewController.swift */; }; + DF4756064E353805E0B51B5505EC70E8 /* FIRStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FB98B53519A3F306A0403D5C63DEFAC /* FIRStorage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DF6A56F3870DE4F3EEA68AF1AB07AA70 /* FIRActionCodeSettings.h in Headers */ = {isa = PBXBuildFile; fileRef = D1D35C7CEFB980F5F15231F61E072857 /* FIRActionCodeSettings.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DFDCA2C1D1E4735F104BD9503325207A /* GPBWellKnownTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = 9AEDC13798C85C59C79C212EB9A65441 /* GPBWellKnownTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E0364B3BCCA113AE22C7DCE6C699E270 /* port_posix.h in Headers */ = {isa = PBXBuildFile; fileRef = F7526F869857A24835B865B3FC4871E3 /* port_posix.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E0BE0E6CF6153C214D47E6C2217B9781 /* FLLRBValueNode.m in Sources */ = {isa = PBXBuildFile; fileRef = 82FDABA5276C7AE2C5B8E81051C68E2F /* FLLRBValueNode.m */; }; + E0EFDB770FB7300A3E9F9F90EC4D84A8 /* FIREmailLinkSignInRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 82BF3B71827ABBD71A94D5711CFE9608 /* FIREmailLinkSignInRequest.m */; }; + E1331724A7D92526AA8714A62C353932 /* pb_decode.c in Sources */ = {isa = PBXBuildFile; fileRef = 1AAD408CF6F37412CD16C253807B02FF /* pb_decode.c */; settings = {COMPILER_FLAGS = "-fno-objc-arc -fno-objc-arc"; }; }; + E1358AA48B67E967CDC5DAFAA273C3AC /* FRepo.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B370A68E87D4F28213B16C705CC3A44 /* FRepo.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E1438306E11939418AD03177AABF914B /* Pods-My MindTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 027526482DD73377A6A7A78E8339F2A5 /* Pods-My MindTests-dummy.m */; }; + E1FB6E47F4DA786A554ECABEFF0C2C92 /* db.h in Headers */ = {isa = PBXBuildFile; fileRef = F7EADE67FC960214F7DED9045D807108 /* db.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E241F0D140E0679637775F22FF7DD50A /* Wrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BBC26AF6B9C5D76177286CF09E095BE /* Wrappers.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + E2A71207B5A59E4FA86C0457AE5B43E0 /* FIRFacebookAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = F130B0DE3FDFDE9134E3CF93A5B4075D /* FIRFacebookAuthProvider.m */; }; + E2B864CF5FCD00BBDB5A6B615BF2D2ED /* FIRMessagingRmqManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F0FFC65783EF4F9F0D9583E9873A1AD9 /* FIRMessagingRmqManager.m */; }; + E3B57C5EEEB965CFF615E2F7060931B1 /* FIRAuthUIDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = F6A0E3ACCDA034A63E32E2E773A849B9 /* FIRAuthUIDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E3EBD4580C136F8662DEF6C0AF183E92 /* GPBDescriptor.h in Headers */ = {isa = PBXBuildFile; fileRef = C3FFC4ACEC5591F801B1902AB763DA62 /* GPBDescriptor.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E44E5222DF7101874E3C9AAA08364171 /* Protobuf-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 35E440DDEB88ECB524E3C40C8A379E1E /* Protobuf-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E44EF4970A6E5604A2E961E572A607A2 /* FPendingPut.h in Headers */ = {isa = PBXBuildFile; fileRef = C6EA16B802C4C8FC4C6BE6B9A2CBCCC5 /* FPendingPut.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E481B67B47D0D361698D7C25E5F37CE0 /* format.cc in Sources */ = {isa = PBXBuildFile; fileRef = 976DAE361FF6DA77BD3EF2CEB5B24754 /* format.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + E49CD8F1F3A61D8519D13384789B2581 /* FOverwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = CB75ED76F6A5CB316ABCE459B35449B1 /* FOverwrite.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E519B657A4BE06FFB6AC67AC43275A8C /* FIRVerifyAssertionResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 82EF6EA3A6D823BECFDF2D38E49A1895 /* FIRVerifyAssertionResponse.m */; }; + E5712C3099F002299B386BD7333BD664 /* SwiftForms-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A899DB3CC1F64B5D6F8B8877B8D5B7D2 /* SwiftForms-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E5900F8440944CEC31ED3763D5DB95B9 /* FIRMessagingReceiver.m in Sources */ = {isa = PBXBuildFile; fileRef = 2A393A9D280CF827CED384D5807BDA33 /* FIRMessagingReceiver.m */; }; + E5C91F7822F2E9F9804F8F317750F22E /* FIRAuthWebViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 30C9C71BCCDD2CD24C276AE7ED003666 /* FIRAuthWebViewController.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E6091E62FEF3773979C6AD65A44D6F82 /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 21F133E7C0A2FCB0E03FE38C1D386479 /* Duration.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + E6107CF6B58A77B36C037AED8052064C /* FIRMessagingConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = A08220A6CDB071FCB4B1F7EC1186D5A5 /* FIRMessagingConstants.m */; }; + E643D91DB349AA0E8ADCD7135864FF4F /* FIRMessagingPacketQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = C2FF98AE061B3CCF1FD81B6324D7D16B /* FIRMessagingPacketQueue.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E6B0529A710641111B7037A5A537E08F /* leveldb-library-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 00773E4B291D7B6F765A193B71873384 /* leveldb-library-dummy.m */; }; + E6FA0DEE717893F584A33FE8D4D366D9 /* FCompoundWrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 9A0C73503D3C9E121AEAD3E5D9965CB2 /* FCompoundWrite.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E762BE2516FB3427F3E7C94A0F0385FC /* FirebaseMessaging.h in Headers */ = {isa = PBXBuildFile; fileRef = DB34977EAC5FC57813546A70B32C7B9D /* FirebaseMessaging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E7732A95963EEA06D112EC28CE34B1ED /* FIRAuthWebUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 50B1EEF969FB395B98F5ACBC29642FB0 /* FIRAuthWebUtils.m */; }; + E81BCE081CF5DFE385E67C8CAA7F34AB /* FUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = CEE1E52025454E30EC0E6663FF8E2467 /* FUtilities.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E8226DBEF9EB493C1BC1A6B06F2A195A /* FIRMessagingRemoteNotificationsProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = C9AEE3D9A205088F3D2E0972D99DE8D7 /* FIRMessagingRemoteNotificationsProxy.m */; }; + E8F98280A695BFA4DC61848984B6331D /* GPBDescriptor_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = A096BEDB7EDE65D27A114DBD7937A0BD /* GPBDescriptor_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E94FECF2AD90CCAA6A4E00868582FD37 /* FIRGoogleAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 90547EAE2B940B2E499C30B4B93D1996 /* FIRGoogleAuthProvider.m */; }; + E975D999A07849EFCEB864F5E8CCA78E /* FIRTransactionResult_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E35D7AE2EB7FA03E603D90E7EB4943F /* FIRTransactionResult_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + EA2E05FBD13050A1F79569643446DA92 /* FIRAuthOperationType.h in Headers */ = {isa = PBXBuildFile; fileRef = E3BF03E4739013E7453C5D34B1E4DB00 /* FIRAuthOperationType.h */; settings = {ATTRIBUTES = (Project, ); }; }; + EBA20935C28770BF8934A346F76C5EB7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + EC7D5D576BA9442D32662E04DC89C376 /* two_level_iterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 3F10F5BDFF54C0E2F5A47075F3A05D23 /* two_level_iterator.h */; settings = {ATTRIBUTES = (Project, ); }; }; + ED400B3FF772E27EAFDE40C8B63B9B2E /* FIRApp.h in Headers */ = {isa = PBXBuildFile; fileRef = AA832C3FE6C7B3EC74C14089A07B2D7D /* FIRApp.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ED5BE623D35FDF173B5ECDA62FF7107E /* FIRAuthAppDelegateProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = AA8F8C049192849495466614A330F2EF /* FIRAuthAppDelegateProxy.h */; settings = {ATTRIBUTES = (Project, ); }; }; + EDBB097C0CEB77890B6959D4F3030453 /* GPBArray_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = F3084FADD51BE52F8FAD4EDDF5886E44 /* GPBArray_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EE2B235989A82885B60FC78F9F360676 /* FIRResetPasswordResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = F85F3E47AD33DA9D446FBF975B322883 /* FIRResetPasswordResponse.m */; }; + EE512B0AE1A87FDDB404BACD12065820 /* FIRMessagingPendingTopicsList.m in Sources */ = {isa = PBXBuildFile; fileRef = 0BB05FBFFE9C45491F3750E50AD53A85 /* FIRMessagingPendingTopicsList.m */; }; + F14821044B905357952ED2C034E4EFE2 /* FIRStorageDownloadTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 211B6DE1BBF8897513531B6D7D842C3A /* FIRStorageDownloadTask.m */; }; + F23EC9ABF478F6040F1B87825D6EBFAA /* FIRDatabaseComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = BE0B0BCBB4CAA4C8D82EF4D06A6D1CA9 /* FIRDatabaseComponent.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F2ECE7A7EADE045435246A5E2E913095 /* FIRStorageTaskSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = E317B12D5F902A2C6E951A9FCCC59530 /* FIRStorageTaskSnapshot.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F3380784E1501976922E124A89DAD92E /* FIRMessagingPubSubRegistrar.h in Headers */ = {isa = PBXBuildFile; fileRef = DE26B28C737D0FE9E95269B09CF011BF /* FIRMessagingPubSubRegistrar.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F50BA6C5F68F87995ADA06093066BC83 /* block_builder.h in Headers */ = {isa = PBXBuildFile; fileRef = A75B42E8622D5215381457494A951D5F /* block_builder.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F54AC8827E2AC4FFE1CD250808FDAF0D /* FIRVerifyPasswordResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D2E468E56AC4645517F8EF8383EFA59 /* FIRVerifyPasswordResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F5B6A5BAB050DF49F8A8139F56CD22F2 /* FValueIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = EA129F6051473738DE8F6680613B7386 /* FValueIndex.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F7EB151471656A6A938C14F8D6E2A1C7 /* FIROAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 673AC49687E8659EB56A9747F2AD855A /* FIROAuthProvider.m */; }; + F8203C8632BDE999A4E00CB2889D8335 /* FirebaseStorage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 757D739372A973A1A6B387E52878A9B6 /* FirebaseStorage-dummy.m */; }; + F82397B7C59337533C88DDD77F92ACD7 /* FIRMessagingPacketQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 9E3E1944E3D50CC93173226B11C47ACC /* FIRMessagingPacketQueue.m */; }; + F82A5AC366CFE91701ACFD28EC220BCE /* merger.cc in Sources */ = {isa = PBXBuildFile; fileRef = A7AA5196BC9D9746048C578C41EB5941 /* merger.cc */; settings = {COMPILER_FLAGS = "-DOS_MACOSX -DLEVELDB_PLATFORM_POSIX -fno-objc-arc"; }; }; + F8AEC5CF8A3C66AA46D007EC1978499C /* histogram.h in Headers */ = {isa = PBXBuildFile; fileRef = D97D7500FF14C5EC413647CED0DE06EB /* histogram.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F8BC2ECF624CA7138AE7A07D218E6C1B /* FIROAuthCredential.h in Headers */ = {isa = PBXBuildFile; fileRef = 758F44968682287AD497896C6C56B2F6 /* FIROAuthCredential.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F8D3BA67EDCBDE29232A5ED3A6D500B6 /* FIRGetAccountInfoRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 01D86F9DE1F79FD6C75EEAAD33BE292E /* FIRGetAccountInfoRequest.m */; }; + F8E193666E5BFB1DE7DF4879D1B1E092 /* FIRVerifyPasswordRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = A3010B8604A66F46C262E7C7847DADA3 /* FIRVerifyPasswordRequest.m */; }; + F9280ED8A50744EBDC19248A06B631BE /* FIRVerifyAssertionRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 62AADFBC08D568729C990BADB7ECB893 /* FIRVerifyAssertionRequest.m */; }; + F9557F9BF6B95D2A3E544BA4C41327E4 /* FIRAuthDefaultUIDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 9C5043AB5D8305D0A639BECC966F573B /* FIRAuthDefaultUIDelegate.h */; settings = {ATTRIBUTES = (Project, ); }; }; + F9753EFE72DDA05B378A06869B06ACAB /* FAckUserWrite.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B7A4B008AB123043A89EBD792C8AF40 /* FAckUserWrite.m */; }; + F9B47D5D75BD7001B20EFFEBDC0B9405 /* GPBMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = BB096EC76A1266B8C0F8E2ACC1A31ED2 /* GPBMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F9C4D8D0356D72D09040AFB2EAC8D34F /* FIRAuthAppDelegateProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = E9445B15B9114E5F95CD4E870F39436A /* FIRAuthAppDelegateProxy.m */; }; + F9D00D0E8CDC4255CA25137F3B76264E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + FA32B2D2522593F2C5B102F0413A6689 /* FIRSignInWithGameCenterRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 65B16A3C4124590E56D417A1088A2B7A /* FIRSignInWithGameCenterRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FAF542DED3A09F832A9151FA54D9EED0 /* FIRMessagingConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = BE0BCF2C1C9FD3078B1F5A3C3EE7C25A /* FIRMessagingConstants.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FB21241BABCD81B33CCB0849CE0AB8F4 /* FIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = 9A55D1EDA7B8213E6AEBB17AE65D2954 /* FIndex.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FB399B131887623311B039D2B888BA2E /* FIRSignUpNewUserResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 4B2E73208606BF9C75DD9E3264B83E42 /* FIRSignUpNewUserResponse.m */; }; + FB5815E73AE7D2F30F2A1F6DA536F734 /* FIRConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = B0AD46A45553ED004551AE6C62A05B2C /* FIRConfiguration.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FB904116F1994ED9ECE269B4BE319C27 /* FIRSendVerificationCodeRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E91BBDEE4AE9CD077A210B6FD93D664 /* FIRSendVerificationCodeRequest.m */; }; + FBE5BE393815441AF36A8F9C8F262863 /* FIRDatabaseQuery_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7871920E4D29C4D70144578BF057710F /* FIRDatabaseQuery_Private.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FC409897309F8E012973C893AF773117 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */; }; + FC45C279B8E52737EB95338D19C80A4B /* FCachePolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8AC604D9BBD33F425A70127321354580 /* FCachePolicy.m */; }; + FC8F9A024980EE037EF01526DE755F73 /* FIRStorageUpdateMetadataTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 2FD045A1CC7371C425615013DF560B51 /* FIRStorageUpdateMetadataTask.m */; }; + FC9D70C36569D43D58C336C316C14DB0 /* FLimitedFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 47FA58B556C9302949CF390A13E37DF8 /* FLimitedFilter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FCB071251982ECB470039552530F1929 /* GULNetwork.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A41AF52719C366C4E6C2ADA6A8368CD /* GULNetwork.m */; }; + FD2D2A017203DD92A4E33539B8BBDEA6 /* FValueEventRegistration.m in Sources */ = {isa = PBXBuildFile; fileRef = C647DA2D0CD5FB0B7BF0E68188DC9A02 /* FValueEventRegistration.m */; }; + FD7F72040DB7EC368013484D68BCB390 /* FIRComponentRegistrant.h in Headers */ = {isa = PBXBuildFile; fileRef = 8354D5D2A1E3BE749C059D69DD9A80E4 /* FIRComponentRegistrant.h */; settings = {ATTRIBUTES = (Private, ); }; }; + FD88A998DAF3046F11F621ED4E5B85F7 /* GTMSessionFetcherService.h in Headers */ = {isa = PBXBuildFile; fileRef = F80EB3448A60D38ECC61534F768996CE /* GTMSessionFetcherService.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FDD9ADF8C9013FF0A79F04C417A3D474 /* FTree.m in Sources */ = {isa = PBXBuildFile; fileRef = 614B59B42151155D33BBF932D5542E46 /* FTree.m */; }; + FDF22C2100DFCFEB404085E621538E91 /* FIRMessagingDelayedMessageQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = A31F7EB02525A5A5990CCF17AFCBEEDF /* FIRMessagingDelayedMessageQueue.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FEBD7EB9CF0EF3CDFCF0459CBD5861EA /* FIRSetAccountInfoResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = AFB0AC6451A7F1334E2461C600716593 /* FIRSetAccountInfoResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FF37D53055EF084C1F52B2D829EBB720 /* FIRTwitterAuthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = DB021ACCB48A686C9395F474B83CDC23 /* FIRTwitterAuthProvider.m */; }; + FF627246354B21BD8FF0684F0B9355F8 /* FViewProcessorResult.m in Sources */ = {isa = PBXBuildFile; fileRef = B6553318BF52F3BEAC785032DE0A7878 /* FViewProcessorResult.m */; }; + FFB3372E37D70F2510BD949401462C3B /* FTupleRemovedQueriesEvents.m in Sources */ = {isa = PBXBuildFile; fileRef = 951C9C763F8BC13991737A8CD8FFF4AA /* FTupleRemovedQueriesEvents.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0254BA8A0A5A6E25F93FA0481D336BE4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0514F4F103BE5B9B50E766A321993C20; + remoteInfo = FirebaseCore; + }; + 07DB35DD87B60D92B772971B805E3593 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0514F4F103BE5B9B50E766A321993C20; + remoteInfo = FirebaseCore; + }; + 1D1A6C516B8735CFABACA3F9AFBFD852 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + 32DE737A738CB51799F86D98E6F4B5F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0514F4F103BE5B9B50E766A321993C20; + remoteInfo = FirebaseCore; + }; + 435CC24916E3408C00C8E0452BE92378 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + 4606C2E5A0E2A00E10E8CD332CFEFD29 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 263F7002FD4F2FB368F105A900F31A18; + remoteInfo = FirebaseStorage; + }; + 46800726BF8809483EB1EFF7DB5948EA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0514F4F103BE5B9B50E766A321993C20; + remoteInfo = FirebaseCore; + }; + 48B79CA3E37AA085E6280AF28B6908B8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1D9FB04B52C841F3FC0250CBC62A374F; + remoteInfo = GTMSessionFetcher; + }; + 506EFD2624A592FE9D141F58142722C0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + 509F57F7F365E2F9DE456FADFE3F6603 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = CFE9294A3948C71B6B365E1AE070CDA5; + remoteInfo = "Pods-My Mind"; + }; + 69E3D4B82ADB9777ECE78BE0A63D70E6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 93AB79BD5DB2C6B4F890C0F391AE1FBC; + remoteInfo = Protobuf; + }; + 7DA088ECDD2B33776686F56A593667FD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = CFE9294A3948C71B6B365E1AE070CDA5; + remoteInfo = "Pods-My Mind"; + }; + 849B13920E45C874D68FC5643BE7CA2F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = B01DE4F80FFD6ECD3AC72050910AF61D; + remoteInfo = SwiftForms; + }; + 8558F8BE6C58B2E54D57B5EA7350BDE7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0514F4F103BE5B9B50E766A321993C20; + remoteInfo = FirebaseCore; + }; + 85D8DF7EB572D40C2680BF9930748E9A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = FE47F11E708D633621DB136BD3CD0034; + remoteInfo = "leveldb-library"; + }; + A20E62201BBF39DA8ABBE0A91DE28F7C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + B218F71BCB3FC159BEA6E328B5A8E5F6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + B80AEEE4D10B31DDDEBDF136764269D7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1D9FB04B52C841F3FC0250CBC62A374F; + remoteInfo = GTMSessionFetcher; + }; + C642C6142D782A0453520E3BFE7D5D1F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8364BB258018143B83798DE31C13546D; + remoteInfo = nanopb; + }; + C8A47A2E4639CEF70BF7AB3DE0E4BC06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8630D8884A33BA1097586BCBB1114CA7; + remoteInfo = GoogleUtilities; + }; + D21F2F60CC3475DD221E35CF29CA182D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = B9B45D12C08E85F7863BC9EB04B3A850; + remoteInfo = FirebaseDatabase; + }; + D8812642019028E623ACE66D311D3E26 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 079E4F97855B7901F483AA030B2B7C5C; + remoteInfo = FirebaseAuth; + }; + F0E1BA2C273B26FEEDCD79E9EAF8F955 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = FE47F11E708D633621DB136BD3CD0034; + remoteInfo = "leveldb-library"; + }; + F128F2484F841C12F5C1EC4068D756FC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1D9FB04B52C841F3FC0250CBC62A374F; + remoteInfo = GTMSessionFetcher; + }; + FD55D6B51C431D8A664C1312CBA9344D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 93AB79BD5DB2C6B4F890C0F391AE1FBC; + remoteInfo = Protobuf; + }; + FF85B2D26CDE57EBE7AA71DC4E38EEB3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F7293FA58AFAF74ECAAB1C4796C45F5B; + remoteInfo = FirebaseMessaging; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 005F17A0CA6BD689AE60571DA2BAFA11 /* FIRAuthAPNSTokenType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAPNSTokenType.h; path = Firebase/Auth/Source/Public/FIRAuthAPNSTokenType.h; sourceTree = ""; }; + 00773E4B291D7B6F765A193B71873384 /* leveldb-library-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "leveldb-library-dummy.m"; sourceTree = ""; }; + 00A0CB9CA5B1E26BDE9D15F6F93F607F /* FIRDependency.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDependency.m; path = Firebase/Core/FIRDependency.m; sourceTree = ""; }; + 0192E00D386318F5FECB4BB5FC607F7D /* FIRVerifyPhoneNumberResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyPhoneNumberResponse.m; path = Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.m; sourceTree = ""; }; + 01A02543DE15ABC24361250045BD11C3 /* GTMSessionFetcher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-prefix.pch"; sourceTree = ""; }; + 01D86F9DE1F79FD6C75EEAAD33BE292E /* FIRGetAccountInfoRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetAccountInfoRequest.m; path = Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.m; sourceTree = ""; }; + 0239D1D4504BAE07E728075902DC1878 /* FIRAuth.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuth.h; path = Firebase/Auth/Source/Public/FIRAuth.h; sourceTree = ""; }; + 027526482DD73377A6A7A78E8339F2A5 /* Pods-My MindTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-My MindTests-dummy.m"; sourceTree = ""; }; + 027F5F2720277F21E85206247776964D /* FirebaseDatabase-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FirebaseDatabase-dummy.m"; sourceTree = ""; }; + 02867E76AFD212132A577D295F36FAFE /* FSparseSnapshotTree.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSparseSnapshotTree.h; path = Firebase/Database/Core/FSparseSnapshotTree.h; sourceTree = ""; }; + 02A902CB224C60C34D9D9D2D0E204BE4 /* APLevelDB.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = APLevelDB.mm; path = "Firebase/Database/third_party/Wrap-leveldb/APLevelDB.mm"; sourceTree = ""; }; + 03232B0207F9B72BCA1F06FB31EAF211 /* FIRComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRComponent.h; path = Firebase/Core/Private/FIRComponent.h; sourceTree = ""; }; + 03AD6BA64F476C451207DEF30D1C0DF7 /* FIRGoogleAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGoogleAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.m; sourceTree = ""; }; + 03EDFA99E6ADFC8587F19A0FD5C27F2A /* FIRDatabaseReference.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDatabaseReference.m; path = Firebase/Database/FIRDatabaseReference.m; sourceTree = ""; }; + 03FA546BF26C2C92243ACD81C404B4DF /* FirebaseCore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FirebaseCore.framework; path = FirebaseCore.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 044D7841EC141A247D182D1B31F071D8 /* FChildEventRegistration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FChildEventRegistration.h; path = Firebase/Database/Core/View/FChildEventRegistration.h; sourceTree = ""; }; + 04C06DA974FBB726CBB34C76008CBC29 /* nanopb.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = nanopb.modulemap; sourceTree = ""; }; + 052D3EAECFCF7B7A9741902E21858002 /* FIRPhoneAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRPhoneAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential.m; sourceTree = ""; }; + 0547C44086388302572F121590BFF048 /* GPBDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDictionary.h; path = objectivec/GPBDictionary.h; sourceTree = ""; }; + 056AAEE5687F136583F2D9487DEEA595 /* GPBCodedInputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedInputStream.h; path = objectivec/GPBCodedInputStream.h; sourceTree = ""; }; + 05DE1CCF193E0BF6A385C79D1F31920F /* Api.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Api.pbobjc.h; path = objectivec/google/protobuf/Api.pbobjc.h; sourceTree = ""; }; + 05E0E3991A44C3DB0537924A5B2482D6 /* FIRTwitterAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRTwitterAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.m; sourceTree = ""; }; + 060A5011E8273A2F4FB12E14AA12DD51 /* FIREmailAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIREmailAuthProvider.h; path = Firebase/Auth/Source/Public/FIREmailAuthProvider.h; sourceTree = ""; }; + 069EEE870762C0F433A706FFB665A283 /* options.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = options.h; path = include/leveldb/options.h; sourceTree = ""; }; + 07084E38FA564A667FC64E1BA854553D /* FImmutableSortedSet.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FImmutableSortedSet.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.m; sourceTree = ""; }; + 070A02016BB493B1197A81FFEACCC360 /* FIndexedFilter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIndexedFilter.m; path = Firebase/Database/Core/View/Filter/FIndexedFilter.m; sourceTree = ""; }; + 080DC43BFB3FA09A4DD2E260312C57F2 /* FKeepSyncedEventRegistration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FKeepSyncedEventRegistration.m; path = Firebase/Database/Core/View/FKeepSyncedEventRegistration.m; sourceTree = ""; }; + 086B92F32AC12F7847B682F04095440D /* Any.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = objectivec/google/protobuf/Any.pbobjc.h; sourceTree = ""; }; + 08BE0BDCDEF190A30B893BEC5F1A9358 /* FIRGitHubAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGitHubAuthProvider.h; path = Firebase/Auth/Source/Public/FIRGitHubAuthProvider.h; sourceTree = ""; }; + 08D738374880F7FA49B1EAB508EDEBD0 /* FLLRBValueNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLLRBValueNode.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.h; sourceTree = ""; }; + 0904C46A7FA089C66B87D70AF0688AA8 /* FTrackedQueryManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTrackedQueryManager.m; path = Firebase/Database/Persistence/FTrackedQueryManager.m; sourceTree = ""; }; + 0933AC24273A3B8D18961DB556CCFFED /* FIRDataEventType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDataEventType.h; path = Firebase/Database/Public/FIRDataEventType.h; sourceTree = ""; }; + 09395751F30ACA695886327117B5E571 /* FLLRBEmptyNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FLLRBEmptyNode.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.m; sourceTree = ""; }; + 0981E2FBA71DA3248061103B90F82F5B /* FConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FConstants.h; path = Firebase/Database/Constants/FConstants.h; sourceTree = ""; }; + 0A2649CC5725FA949A3D54FB633180B6 /* FIRMessaging_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessaging_Private.h; path = Firebase/Messaging/FIRMessaging_Private.h; sourceTree = ""; }; + 0B51883B5AC0F922A2308C19F60F9664 /* FIRDatabaseQuery.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDatabaseQuery.m; path = Firebase/Database/Api/FIRDatabaseQuery.m; sourceTree = ""; }; + 0B5803208593B4D179BEC1EB11FFC53C /* GPBUnknownField_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownField_PackagePrivate.h; path = objectivec/GPBUnknownField_PackagePrivate.h; sourceTree = ""; }; + 0BB05FBFFE9C45491F3750E50AD53A85 /* FIRMessagingPendingTopicsList.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingPendingTopicsList.m; path = Firebase/Messaging/FIRMessagingPendingTopicsList.m; sourceTree = ""; }; + 0BC11EBDA615AAA6167464EEE00C3EE1 /* NSData+FIRBase64.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+FIRBase64.h"; path = "Firebase/Auth/Source/NSData+FIRBase64.h"; sourceTree = ""; }; + 0C133B09CE3EB5E249AAC9A970FD6D8C /* FSRWebSocket.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSRWebSocket.m; path = Firebase/Database/third_party/SocketRocket/FSRWebSocket.m; sourceTree = ""; }; + 0C387A89EF9BCFB1D9AEC1628A6FFB57 /* FIRConfiguration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRConfiguration.m; path = Firebase/Core/FIRConfiguration.m; sourceTree = ""; }; + 0C5EAA248DD28CE7903CF85278DCF244 /* fbase64.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fbase64.h; path = Firebase/Database/third_party/SocketRocket/fbase64.h; sourceTree = ""; }; + 0C7859524A87E234251F0B720F52F719 /* FImmutableSortedDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FImmutableSortedDictionary.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.h; sourceTree = ""; }; + 0CA1BD6CB3A1AE01107FD8F8FDCA3D2E /* block.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = block.h; path = table/block.h; sourceTree = ""; }; + 0CD5B29065B8C08D5397404B28BD7CDE /* FIRDatabase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabase.h; path = Firebase/Database/Public/FIRDatabase.h; sourceTree = ""; }; + 0D611DA4A6D467F635AF0C5C09F9FB74 /* FQuerySpec.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FQuerySpec.h; path = Firebase/Database/Core/FQuerySpec.h; sourceTree = ""; }; + 0D945B5FCAFD829D8E4CB0BC446F5263 /* format.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = format.h; path = table/format.h; sourceTree = ""; }; + 0E028BD0ED8BAF09AF89450487F80927 /* filter_block.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = filter_block.h; path = table/filter_block.h; sourceTree = ""; }; + 0E35D7AE2EB7FA03E603D90E7EB4943F /* FIRTransactionResult_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRTransactionResult_Private.h; path = Firebase/Database/Api/Private/FIRTransactionResult_Private.h; sourceTree = ""; }; + 0E52BD389E6CE1A1DA968B1065FE7CEA /* FAuthTokenProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FAuthTokenProvider.m; path = Firebase/Database/Login/FAuthTokenProvider.m; sourceTree = ""; }; + 0E6EEACCBF201D7F886D030A77A7A82C /* FIRDeleteAccountResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDeleteAccountResponse.h; path = Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.h; sourceTree = ""; }; + 0E91BBDEE4AE9CD077A210B6FD93D664 /* FIRSendVerificationCodeRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSendVerificationCodeRequest.m; path = Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.m; sourceTree = ""; }; + 0E95E3219504D83CD57E912728E959D3 /* FormLabelCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormLabelCell.swift; path = SwiftForms/cells/FormLabelCell.swift; sourceTree = ""; }; + 0E9F7376073BEEE255DDF4BEB5C606F9 /* GoogleAppMeasurement.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GoogleAppMeasurement.framework; path = Frameworks/GoogleAppMeasurement.framework; sourceTree = ""; }; + 0ED14CD3D134195AD99E47BD299EBDF7 /* FIRIdentityToolkitRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRIdentityToolkitRequest.m; path = Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.m; sourceTree = ""; }; + 0EF8CB17A97DBCD11218204027BB21FD /* FIRStorageTaskSnapshot_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageTaskSnapshot_Private.h; path = Firebase/Storage/Private/FIRStorageTaskSnapshot_Private.h; sourceTree = ""; }; + 0F065833D4D711DB2314D643800DD031 /* FormPickerCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormPickerCell.swift; path = SwiftForms/cells/FormPickerCell.swift; sourceTree = ""; }; + 0F38BB1D2C2DC6C63F1A53730F4F5F50 /* FIRAppInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAppInternal.h; path = Firebase/Core/Private/FIRAppInternal.h; sourceTree = ""; }; + 0F561C68BAE176C5D0E278CE58FDDCD5 /* dumpfile.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = dumpfile.cc; path = db/dumpfile.cc; sourceTree = ""; }; + 0F8B1871C7FFB70E87F78EF2A17A58B4 /* Pods-My MindTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-My MindTests-acknowledgements.plist"; sourceTree = ""; }; + 102344473F65983D56F8C4612A41F57E /* FIRStorageUploadTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageUploadTask.h; path = Firebase/Storage/Public/FIRStorageUploadTask.h; sourceTree = ""; }; + 11018727FC836C957AB749559F7845ED /* hash.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = hash.cc; path = util/hash.cc; sourceTree = ""; }; + 11273FE951B7033B10D1561060CD8732 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 1175E03AEA34F51B8C8D46A8448670C0 /* GPBWellKnownTypes.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBWellKnownTypes.m; path = objectivec/GPBWellKnownTypes.m; sourceTree = ""; }; + 11796741226434375F93ED3BA8C0A741 /* FPruneForest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPruneForest.m; path = Firebase/Database/Persistence/FPruneForest.m; sourceTree = ""; }; + 119A6FE215E962613478EEBFC1F4F505 /* FIRAuthSerialTaskQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthSerialTaskQueue.h; path = Firebase/Auth/Source/FIRAuthSerialTaskQueue.h; sourceTree = ""; }; + 1261B3607B95AB5FCC0789BAC0335F4D /* FIREmailPasswordAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIREmailPasswordAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.m; sourceTree = ""; }; + 127AF1BC36CC21E5614940AA4087D2E9 /* FRepoInfo.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FRepoInfo.m; path = Firebase/Database/Core/FRepoInfo.m; sourceTree = ""; }; + 12A5C3A9A8DA7A2944A508E1378B93B1 /* FIRCreateAuthURIResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRCreateAuthURIResponse.m; path = Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.m; sourceTree = ""; }; + 12CCC1B4271DDA631C361A6A36F607BC /* FIRDataSnapshot.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDataSnapshot.m; path = Firebase/Database/Api/FIRDataSnapshot.m; sourceTree = ""; }; + 1336CDE7D47BE2947E359E422605C9A9 /* Protobuf-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Protobuf-prefix.pch"; sourceTree = ""; }; + 136CC9E6128297BD62D6F21F1284BF89 /* FIRSecureTokenService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSecureTokenService.h; path = Firebase/Auth/Source/FIRSecureTokenService.h; sourceTree = ""; }; + 1371CB007C4703ADBB046374DD799D44 /* FormSegmentedControlCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSegmentedControlCell.swift; path = SwiftForms/cells/FormSegmentedControlCell.swift; sourceTree = ""; }; + 13B62195E3A11B0D93DB60EBB5ED122A /* FIRAuthDataResult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthDataResult.h; path = Firebase/Auth/Source/Public/FIRAuthDataResult.h; sourceTree = ""; }; + 13E143593E7232E1F8B12AC4FE62DA8A /* FIROptions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIROptions.m; path = Firebase/Core/FIROptions.m; sourceTree = ""; }; + 13E8E20280A59FBF3E16ABB61C7F1857 /* GPBCodedInputStream_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedInputStream_PackagePrivate.h; path = objectivec/GPBCodedInputStream_PackagePrivate.h; sourceTree = ""; }; + 143163CDF7251156D7FE094D45C15FEB /* FIRMessagingUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingUtilities.m; path = Firebase/Messaging/FIRMessagingUtilities.m; sourceTree = ""; }; + 1458408B7F7426DFEC2029E33DB82575 /* FIRMutableData.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMutableData.m; path = Firebase/Database/Api/FIRMutableData.m; sourceTree = ""; }; + 14C8ECD8310E798246C725B33683BD31 /* Pods-My MindTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My MindTests.release.xcconfig"; sourceTree = ""; }; + 1534655F96C2C7D96E3632B7C1979994 /* FTupleTSN.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleTSN.h; path = Firebase/Database/Utilities/Tuples/FTupleTSN.h; sourceTree = ""; }; + 15436BAF73F24A26CBCCCE13B2C7A5D5 /* FCacheNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FCacheNode.m; path = Firebase/Database/Core/View/FCacheNode.m; sourceTree = ""; }; + 15918B10BD6CE7C57B16DB55766DE2AE /* FIRMMessageCode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMMessageCode.h; path = Firebase/Messaging/FIRMMessageCode.h; sourceTree = ""; }; + 160AC27B2B81C1CFF9884A32DEDBD736 /* memtable.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = memtable.cc; path = db/memtable.cc; sourceTree = ""; }; + 160B2A098D6BE7E4FB1B11DD186189BB /* FTreeSortedDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTreeSortedDictionary.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.m; sourceTree = ""; }; + 1645988A40396F6E30316B284BD585E5 /* FRepoManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FRepoManager.m; path = Firebase/Database/Core/FRepoManager.m; sourceTree = ""; }; + 166AEA29274E16405F538B6E3FB9F341 /* GPBMessage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBMessage.m; path = objectivec/GPBMessage.m; sourceTree = ""; }; + 167247C461FA542A015E0FDFE30C7A26 /* FirebaseAuth.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FirebaseAuth.modulemap; sourceTree = ""; }; + 16ABBC1602669EF624F71C7D2874005A /* GPBCodedOutputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedOutputStream.h; path = objectivec/GPBCodedOutputStream.h; sourceTree = ""; }; + 171F6C7813B27B478AE78B6579E4FBAA /* FDataEvent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FDataEvent.m; path = Firebase/Database/Core/View/FDataEvent.m; sourceTree = ""; }; + 178235193981793B5A1306D65CC58041 /* port_posix.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = port_posix.cc; path = port/port_posix.cc; sourceTree = ""; }; + 17B0C073D7E0610CB87572DA00D591D7 /* FIRStorageUtils.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageUtils.m; path = Firebase/Storage/FIRStorageUtils.m; sourceTree = ""; }; + 17CD745C9A40F6E344672C2AB3522EE4 /* FRangeMerge.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FRangeMerge.m; path = Firebase/Database/Core/FRangeMerge.m; sourceTree = ""; }; + 17DE2AD6AD6B952E14BD83D4D76F3E5A /* FIRUserMetadata.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUserMetadata.h; path = Firebase/Auth/Source/Public/FIRUserMetadata.h; sourceTree = ""; }; + 190C6A526425A5A9EF0976A2C466B402 /* FIRStorageGetDownloadURLTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageGetDownloadURLTask.h; path = Firebase/Storage/Private/FIRStorageGetDownloadURLTask.h; sourceTree = ""; }; + 1929AA13F6B9C086778B2797199BBB2B /* FValidation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FValidation.m; path = Firebase/Database/Utilities/FValidation.m; sourceTree = ""; }; + 195F2A114F33FC39E8EE0AF6ECE74737 /* GULReachabilityMessageCode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULReachabilityMessageCode.h; path = GoogleUtilities/Reachability/Private/GULReachabilityMessageCode.h; sourceTree = ""; }; + 19BFB803A0CA8832F957B481C492303E /* FIRMessaging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessaging.m; path = Firebase/Messaging/FIRMessaging.m; sourceTree = ""; }; + 19DE6E8E7B6B1372BCE4CC0AAB53C3AC /* FIRResetPasswordResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRResetPasswordResponse.h; path = Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.h; sourceTree = ""; }; + 1A49F1C98CBAA4564CA3708149127C6D /* FIRAuthDataResult.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthDataResult.m; path = Firebase/Auth/Source/FIRAuthDataResult.m; sourceTree = ""; }; + 1A4C69A6E7DCD1DA0FE2647B81119490 /* GTMSessionFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcher.h; path = Source/GTMSessionFetcher.h; sourceTree = ""; }; + 1A80624208D997D30C2C97FF658187DF /* FTupleBoolBlock.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleBoolBlock.h; path = Firebase/Database/Utilities/Tuples/FTupleBoolBlock.h; sourceTree = ""; }; + 1AAD408CF6F37412CD16C253807B02FF /* pb_decode.c */ = {isa = PBXFileReference; includeInIndex = 1; path = pb_decode.c; sourceTree = ""; }; + 1B1B2B22C6DC5738A70F2F6D590BEA8C /* FStorageEngine.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FStorageEngine.h; path = Firebase/Database/Persistence/FStorageEngine.h; sourceTree = ""; }; + 1B5BD339D6126E58145A91C670A79B57 /* FIRMessagingTopicsCommon.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingTopicsCommon.h; path = Firebase/Messaging/FIRMessagingTopicsCommon.h; sourceTree = ""; }; + 1B6C2A21CF5F46F68A65914721B4BC48 /* FirebaseMessaging-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FirebaseMessaging-dummy.m"; sourceTree = ""; }; + 1C9262B336C315B62E2E2BBCB9ECB143 /* env_posix_test_helper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = env_posix_test_helper.h; path = util/env_posix_test_helper.h; sourceTree = ""; }; + 1CA6D0718F1BE8F2CD2B515567E26AB1 /* FIRAuthNotificationManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthNotificationManager.h; path = Firebase/Auth/Source/FIRAuthNotificationManager.h; sourceTree = ""; }; + 1CD3422CDCBB98E652719FF98E60523E /* nanopb-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "nanopb-prefix.pch"; sourceTree = ""; }; + 1E8627B6D324325882201B629A767ED8 /* GoogleUtilities.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GoogleUtilities.xcconfig; sourceTree = ""; }; + 1EEE2FAABA3D4CDED41BA149DDCAAC86 /* FEventEmitter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FEventEmitter.m; path = Firebase/Database/Utilities/FEventEmitter.m; sourceTree = ""; }; + 1F32152C8DD47543CFEEE86EC20A8D54 /* iterator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = iterator.h; path = include/leveldb/iterator.h; sourceTree = ""; }; + 1F5AA5097DD6969A0A996849D3ADA0FE /* FLLRBNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLLRBNode.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBNode.h; sourceTree = ""; }; + 1F867F22C2B7BAAA7F6FB2880B592586 /* FLevelDBStorageEngine.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FLevelDBStorageEngine.m; path = Firebase/Database/Persistence/FLevelDBStorageEngine.m; sourceTree = ""; }; + 1F8914247BC8981046DD3254E6EED8BF /* GTMSessionFetcher.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GTMSessionFetcher.xcconfig; sourceTree = ""; }; + 1FA4FBB774B84B9517944CCF8010D41D /* FIRGetOOBConfirmationCodeResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetOOBConfirmationCodeResponse.h; path = Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.h; sourceTree = ""; }; + 1FB8225F6A8837C1B29AA8D1503478F1 /* FirebaseStorage.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FirebaseStorage.xcconfig; sourceTree = ""; }; + 203AD3FF7A567A2E94E4B935B88C0A08 /* FCacheNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCacheNode.h; path = Firebase/Database/Core/View/FCacheNode.h; sourceTree = ""; }; + 2073FD9AA334017E0E90D8197D3A84B8 /* FTrackedQuery.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTrackedQuery.h; path = Firebase/Database/Persistence/FTrackedQuery.h; sourceTree = ""; }; + 209C44D7A6CAF9D909AE34A0B3351B8E /* GULMutableDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULMutableDictionary.h; path = GoogleUtilities/Network/Private/GULMutableDictionary.h; sourceTree = ""; }; + 211B6DE1BBF8897513531B6D7D842C3A /* FIRStorageDownloadTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageDownloadTask.m; path = Firebase/Storage/FIRStorageDownloadTask.m; sourceTree = ""; }; + 2120AEB3891B803C5271166BBAB0F0A5 /* coding.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = coding.cc; path = util/coding.cc; sourceTree = ""; }; + 21519CE5EB78FDA959307B63623B7289 /* FormRowDescriptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormRowDescriptor.swift; path = SwiftForms/descriptors/FormRowDescriptor.swift; sourceTree = ""; }; + 21F133E7C0A2FCB0E03FE38C1D386479 /* Duration.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Duration.pbobjc.m; path = objectivec/google/protobuf/Duration.pbobjc.m; sourceTree = ""; }; + 235678AD0689F0483082B3B7FEB46171 /* FIRMessagingConnection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingConnection.h; path = Firebase/Messaging/FIRMessagingConnection.h; sourceTree = ""; }; + 238B69F72D2635F7E099540FEBAE969A /* c.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = c.h; path = include/leveldb/c.h; sourceTree = ""; }; + 23FC93A0EF861393C6EEE18DF78305C4 /* FPersistenceManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPersistenceManager.m; path = Firebase/Database/Persistence/FPersistenceManager.m; sourceTree = ""; }; + 246FADA5C8D2648540D64611F12C83F1 /* FMaxNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMaxNode.m; path = Firebase/Database/FMaxNode.m; sourceTree = ""; }; + 248D6396DD17D8431F0B3A31293DBA66 /* FIRGetOOBConfirmationCodeRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetOOBConfirmationCodeRequest.m; path = Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.m; sourceTree = ""; }; + 24C4C8F54426C9EFB4F6CEA3C77E8E45 /* FIRMessagingAnalytics.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingAnalytics.h; path = Firebase/Messaging/FIRMessagingAnalytics.h; sourceTree = ""; }; + 24EAD08A106190E74699EE263115EA87 /* GULNetworkConstants.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULNetworkConstants.m; path = GoogleUtilities/Network/GULNetworkConstants.m; sourceTree = ""; }; + 250424226E3E1252246D83E4302FCF23 /* env.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = env.cc; path = util/env.cc; sourceTree = ""; }; + 2546E3E1838E0C58EBD972F9CB875E1B /* FIRStorageGetDownloadURLTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageGetDownloadURLTask.m; path = Firebase/Storage/FIRStorageGetDownloadURLTask.m; sourceTree = ""; }; + 262865D53F46E4528F6B67FF9DC6A479 /* FIRMessagingContextManagerService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingContextManagerService.m; path = Firebase/Messaging/FIRMessagingContextManagerService.m; sourceTree = ""; }; + 26B8BFBA5B3F70CF09022BCF57C36C70 /* FormValueCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormValueCell.swift; path = SwiftForms/cells/base/FormValueCell.swift; sourceTree = ""; }; + 26C18E86BC3C699C7D43F84F8E6ABBA6 /* FIRGetAccountInfoResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetAccountInfoResponse.m; path = Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.m; sourceTree = ""; }; + 26D0C49266BF657CB1AF5A18E8F591DB /* FIRMessagingRemoteNotificationsProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingRemoteNotificationsProxy.h; path = Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.h; sourceTree = ""; }; + 26D74751413758177B3A96C50FF7FF7D /* FormSwitchCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSwitchCell.swift; path = SwiftForms/cells/FormSwitchCell.swift; sourceTree = ""; }; + 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 273588F88459B6EE9873ADA94B13FC66 /* iterator.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = iterator.cc; path = table/iterator.cc; sourceTree = ""; }; + 275E67D0B7860BEB886BA56746C86448 /* FWriteTree.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FWriteTree.m; path = Firebase/Database/Core/FWriteTree.m; sourceTree = ""; }; + 27D9867266FC937A80456C5B2C28AF13 /* FValueIndex.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FValueIndex.m; path = Firebase/Database/FValueIndex.m; sourceTree = ""; }; + 2810E3E1AC8BFA36AB5702CEF85BEE34 /* nanopb-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "nanopb-umbrella.h"; sourceTree = ""; }; + 28202CE327903B58CDB7331A14E79DC1 /* FIRStorageDeleteTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageDeleteTask.m; path = Firebase/Storage/FIRStorageDeleteTask.m; sourceTree = ""; }; + 28408A35C59B8DAEAB6216D22C3FB49D /* FirebaseCore.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseCore.h; path = Firebase/Core/Public/FirebaseCore.h; sourceTree = ""; }; + 2873E606F0C6C216CEF364B6C5008F42 /* testharness.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = testharness.cc; path = util/testharness.cc; sourceTree = ""; }; + 28C219F26C922F496FB2CDC879FA9079 /* FTransformedEnumerator.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTransformedEnumerator.m; path = Firebase/Database/FTransformedEnumerator.m; sourceTree = ""; }; + 29343B35E5F2B0EFA39F218482ACB0CB /* FIRPhoneAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRPhoneAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthProvider.m; sourceTree = ""; }; + 299DF18554F4A28DFE1C9CEF8D10FDD5 /* FMerge.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMerge.h; path = Firebase/Database/Core/Operation/FMerge.h; sourceTree = ""; }; + 2A393A9D280CF827CED384D5807BDA33 /* FIRMessagingReceiver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingReceiver.m; path = Firebase/Messaging/FIRMessagingReceiver.m; sourceTree = ""; }; + 2A48BB8A8D3B8F2F32F334BD438F45DA /* FIRAuthAppCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAppCredential.h; path = Firebase/Auth/Source/FIRAuthAppCredential.h; sourceTree = ""; }; + 2A66497EBD1AB3737D5005944AF2A938 /* testutil.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = testutil.cc; path = util/testutil.cc; sourceTree = ""; }; + 2AD6C8F4DFB8B09F9C4C1273793725ED /* merger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = merger.h; path = table/merger.h; sourceTree = ""; }; + 2ADAA62C81FBD8B8F835FD758F63C282 /* Pods-My MindUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-My MindUITests-dummy.m"; sourceTree = ""; }; + 2B45B623BB352D383633A4CF9C608127 /* FIRAuthInterop.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthInterop.h; path = Interop/Auth/Public/FIRAuthInterop.h; sourceTree = ""; }; + 2BC27000ADAE777180D767021286CA2C /* builder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = builder.h; path = db/builder.h; sourceTree = ""; }; + 2BEA6BEF99A18E7226D403A8BC1F4837 /* FormTitleCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormTitleCell.swift; path = SwiftForms/cells/base/FormTitleCell.swift; sourceTree = ""; }; + 2BF6BAA9454971A57DABB6CA9CD25AD5 /* FTupleSetIdPath.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleSetIdPath.h; path = Firebase/Database/Utilities/Tuples/FTupleSetIdPath.h; sourceTree = ""; }; + 2C2266A871A0E4A996895C0A6B5F65CF /* log_writer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = log_writer.h; path = db/log_writer.h; sourceTree = ""; }; + 2C40238EAA192A9251A946077405ABC0 /* FNextPushId.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FNextPushId.h; path = Firebase/Database/Utilities/FNextPushId.h; sourceTree = ""; }; + 2C6CDE0E1371445EF3780F7C3AF3CA55 /* FTupleStringNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleStringNode.m; path = Firebase/Database/Utilities/Tuples/FTupleStringNode.m; sourceTree = ""; }; + 2CE2AFE0717F5787756256BC9B37CCDE /* env_posix.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = env_posix.cc; path = util/env_posix.cc; sourceTree = ""; }; + 2CEEEDDBF0B7C02B72407C0E80B35688 /* FIRMessagingRmqManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingRmqManager.h; path = Firebase/Messaging/FIRMessagingRmqManager.h; sourceTree = ""; }; + 2CF857CEF2CDC86922BA2271E25A7A13 /* version_edit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = version_edit.h; path = db/version_edit.h; sourceTree = ""; }; + 2D49C8229916022BD904F466DD4B1695 /* GTMSessionFetcherLogging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherLogging.m; path = Source/GTMSessionFetcherLogging.m; sourceTree = ""; }; + 2D9B0086B87D0C228A92B242FCD33B3C /* FIRStoragePath.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStoragePath.m; path = Firebase/Storage/FIRStoragePath.m; sourceTree = ""; }; + 2DB687A0483C0EE960D37434597A35AE /* FIRVersion.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVersion.m; path = Firebase/Core/FIRVersion.m; sourceTree = ""; }; + 2DDDD71E6DB015FCA8B621580ADC5452 /* FRepo.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FRepo.m; path = Firebase/Database/Core/FRepo.m; sourceTree = ""; }; + 2E2BB3682A63E5E8457BE4392979C216 /* FListenProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FListenProvider.m; path = Firebase/Database/Core/FListenProvider.m; sourceTree = ""; }; + 2EC536F0C78D7F592760BB1B26CEE026 /* port_posix_sse.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = port_posix_sse.cc; path = port/port_posix_sse.cc; sourceTree = ""; }; + 2EFCA2B98B8F29A0EC46C45E86B06459 /* GULNSData+zlib.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "GULNSData+zlib.h"; path = "GoogleUtilities/NSData+zlib/GULNSData+zlib.h"; sourceTree = ""; }; + 2F023A3AA7B317ABDDFF07E64B3FFE45 /* FIRDatabaseConfig.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDatabaseConfig.m; path = Firebase/Database/Api/FIRDatabaseConfig.m; sourceTree = ""; }; + 2FD045A1CC7371C425615013DF560B51 /* FIRStorageUpdateMetadataTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageUpdateMetadataTask.m; path = Firebase/Storage/FIRStorageUpdateMetadataTask.m; sourceTree = ""; }; + 2FE952393E91F78CAE5094FFA1EBBA52 /* FIRPhoneAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRPhoneAuthProvider.h; path = Firebase/Auth/Source/Public/FIRPhoneAuthProvider.h; sourceTree = ""; }; + 2FF4A55D674F3F971478CE8C9D07E621 /* FTuplePathValue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTuplePathValue.h; path = Firebase/Database/Utilities/Tuples/FTuplePathValue.h; sourceTree = ""; }; + 300E08C04185ADA1E87FE6C0D81A10E8 /* FIRAuthExceptionUtils.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthExceptionUtils.h; path = Firebase/Auth/Source/FIRAuthExceptionUtils.h; sourceTree = ""; }; + 301054B3F03AB321796CB62FDD44BE25 /* pb.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = pb.h; sourceTree = ""; }; + 3023906E936612450A901BB43816EB8C /* FIRAuthGlobalWorkQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthGlobalWorkQueue.m; path = Firebase/Auth/Source/FIRAuthGlobalWorkQueue.m; sourceTree = ""; }; + 3081C96D7043D1BCEE537DC6020F9A52 /* Pods-My MindTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My MindTests-resources.sh"; sourceTree = ""; }; + 309BB9290E966976A199C728D934130A /* FSnapshotHolder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSnapshotHolder.h; path = Firebase/Database/Core/FSnapshotHolder.h; sourceTree = ""; }; + 30C9C71BCCDD2CD24C276AE7ED003666 /* FIRAuthWebViewController.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthWebViewController.h; path = Firebase/Auth/Source/FIRAuthWebViewController.h; sourceTree = ""; }; + 316D8A7A00F10D77D5E5B7F79B7770D2 /* FIRStorageConstants.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageConstants.m; path = Firebase/Storage/FIRStorageConstants.m; sourceTree = ""; }; + 31997DF23B7B7028628BAB1A7A4AFD8B /* crc32c.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = crc32c.h; path = util/crc32c.h; sourceTree = ""; }; + 31C4337E4E578887B076F5E47A449DCE /* Api.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Api.pbobjc.m; path = objectivec/google/protobuf/Api.pbobjc.m; sourceTree = ""; }; + 31D63EE25A257F5309562EBE3F5BDD37 /* FCompoundWrite.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FCompoundWrite.m; path = Firebase/Database/Snapshot/FCompoundWrite.m; sourceTree = ""; }; + 3202E21A3C70DC101F9BC193374415EC /* FIRAuthErrorUtils.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthErrorUtils.h; path = Firebase/Auth/Source/FIRAuthErrorUtils.h; sourceTree = ""; }; + 32549BEEF6A49D7F0A9E0210E5889C34 /* log_reader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = log_reader.h; path = db/log_reader.h; sourceTree = ""; }; + 33210CB84E7E2EA9F5357F167D658407 /* atomic_pointer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = atomic_pointer.h; path = port/atomic_pointer.h; sourceTree = ""; }; + 334A73053CB07EBAD403B0A20B0FB4D1 /* FImmutableTree.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FImmutableTree.h; path = Firebase/Database/Core/Utilities/FImmutableTree.h; sourceTree = ""; }; + 33559F44AC95540C2B694C8E23DE8148 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 33865930EE20D6BBB99E16994933D2BE /* FIRPhoneAuthCredential_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRPhoneAuthCredential_Internal.h; path = Firebase/Auth/Source/AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h; sourceTree = ""; }; + 338F8FAD90ACCD0679A61D9BF3376DAB /* FIRStorageErrors.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageErrors.h; path = Firebase/Storage/Private/FIRStorageErrors.h; sourceTree = ""; }; + 33D03EFE889DEDA5D7BB31722B237A80 /* table.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = table.cc; path = table/table.cc; sourceTree = ""; }; + 342B0B60E0420CB2ADAE937A53F52CEC /* FChange.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FChange.h; path = Firebase/Database/Core/View/FChange.h; sourceTree = ""; }; + 3463542860D4D784D0B8FE1164F16844 /* FCachePolicy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCachePolicy.h; path = Firebase/Database/Persistence/FCachePolicy.h; sourceTree = ""; }; + 34A437CCB33E71BF0316EE12908859A5 /* GPBRootObject.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRootObject.h; path = objectivec/GPBRootObject.h; sourceTree = ""; }; + 34AE0C022045C233A6AA55DF5C66D612 /* FIRMessagingLogger.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingLogger.m; path = Firebase/Messaging/FIRMessagingLogger.m; sourceTree = ""; }; + 34E37E86AAAB7B5AB34F165B3C259058 /* GTMSessionFetcher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GTMSessionFetcher-dummy.m"; sourceTree = ""; }; + 34FF34F16BEF644F7E4BB840CB508AD2 /* FPendingPut.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPendingPut.m; path = Firebase/Database/Persistence/FPendingPut.m; sourceTree = ""; }; + 35465F173726C8791C690CAA5F588804 /* FirebaseDatabase.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FirebaseDatabase.modulemap; sourceTree = ""; }; + 35ACEC850EA6B8AF4B8B76044A429AA6 /* NSDictionary+FIRMessaging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSDictionary+FIRMessaging.m"; path = "Firebase/Messaging/NSDictionary+FIRMessaging.m"; sourceTree = ""; }; + 35C0A0B5A99461EBCFD376962B2F5C0D /* FIRAuthTokenResult_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthTokenResult_Internal.h; path = Firebase/Auth/Source/FIRAuthTokenResult_Internal.h; sourceTree = ""; }; + 35E440DDEB88ECB524E3C40C8A379E1E /* Protobuf-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Protobuf-umbrella.h"; sourceTree = ""; }; + 360F34FFDB1C719C8DE28092E5639368 /* FIRStorageReference_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageReference_Private.h; path = Firebase/Storage/Private/FIRStorageReference_Private.h; sourceTree = ""; }; + 365E83317995CD7525ED8911984FA695 /* FIRVerifyCustomTokenRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyCustomTokenRequest.m; path = Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.m; sourceTree = ""; }; + 366FDECE49AF8E55FF1E41E5B8D8A099 /* FIRAuthAppCredentialManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAppCredentialManager.h; path = Firebase/Auth/Source/FIRAuthAppCredentialManager.h; sourceTree = ""; }; + 368E447E635FC44C3CA4A0F09D50292A /* FIRDatabaseQuery.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseQuery.h; path = Firebase/Database/Public/FIRDatabaseQuery.h; sourceTree = ""; }; + 368FFE6CB6D2F8002E6237D83CC0D3C3 /* Pods-My Mind.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-My Mind.modulemap"; sourceTree = ""; }; + 36D45A7FA49317344BF019A206D17B1E /* FIRCoreConfigurable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRCoreConfigurable.h; path = Firebase/Core/Private/FIRCoreConfigurable.h; sourceTree = ""; }; + 37516AA7CF7594EF2A97EECB3F648BC3 /* FIRStoragePath.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStoragePath.h; path = Firebase/Storage/Private/FIRStoragePath.h; sourceTree = ""; }; + 379E5B5FBE6395CCCDF717529007F6C8 /* FIRStorageTokenAuthorizer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageTokenAuthorizer.h; path = Firebase/Storage/Private/FIRStorageTokenAuthorizer.h; sourceTree = ""; }; + 37A41E82010FCD2D354DE448260E8240 /* FIRFacebookAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRFacebookAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.m; sourceTree = ""; }; + 38121C21810D6FCA9108041FC4F8FEDA /* FTupleTSN.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleTSN.m; path = Firebase/Database/Utilities/Tuples/FTupleTSN.m; sourceTree = ""; }; + 386373BFF6E630E359797C1A82AB1070 /* FIRAuthGlobalWorkQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthGlobalWorkQueue.h; path = Firebase/Auth/Source/FIRAuthGlobalWorkQueue.h; sourceTree = ""; }; + 389D2E096B89ACC945F9139E64B99063 /* FIRDeleteAccountRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDeleteAccountRequest.h; path = Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.h; sourceTree = ""; }; + 390DD1B08C74A9F68476B754216839F8 /* GPBUnknownFieldSet.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUnknownFieldSet.m; path = objectivec/GPBUnknownFieldSet.m; sourceTree = ""; }; + 39A633CD466937034BA28BBFAC639020 /* FRangeMerge.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRangeMerge.h; path = Firebase/Database/Core/FRangeMerge.h; sourceTree = ""; }; + 39F2F32A7DA93B047FC2CD83E02E59B2 /* FTupleCallbackStatus.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleCallbackStatus.m; path = Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.m; sourceTree = ""; }; + 3A76E7B0DE462D4F237E12CB0F74930D /* FWebSocketConnection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FWebSocketConnection.h; path = Firebase/Database/Realtime/FWebSocketConnection.h; sourceTree = ""; }; + 3AD4D1243F862167904648922BDAE04D /* FConnection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FConnection.h; path = Firebase/Database/Realtime/FConnection.h; sourceTree = ""; }; + 3B370A68E87D4F28213B16C705CC3A44 /* FRepo.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRepo.h; path = Firebase/Database/Core/FRepo.h; sourceTree = ""; }; + 3B7A4B008AB123043A89EBD792C8AF40 /* FAckUserWrite.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FAckUserWrite.m; path = Firebase/Database/Core/Operation/FAckUserWrite.m; sourceTree = ""; }; + 3BA38BF03D131A8C606CB78AC6CB85DC /* GPBArray.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBArray.h; path = objectivec/GPBArray.h; sourceTree = ""; }; + 3BB0171D3D054B9A887BDABC219FDED3 /* FSyncTree.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSyncTree.m; path = Firebase/Database/Core/FSyncTree.m; sourceTree = ""; }; + 3BB0B1F9F39C57357D2350296EAA5E53 /* FImmutableSortedDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FImmutableSortedDictionary.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedDictionary.m; sourceTree = ""; }; + 3BDBF6A6577932307CBAE680E3C2D0DC /* FIRDatabaseComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDatabaseComponent.m; path = Firebase/Database/Api/FIRDatabaseComponent.m; sourceTree = ""; }; + 3BE90917ABE234BE1286DC10A4D177F1 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 3C0CE893E96EBB13E04CA4D4B62030BB /* FCompoundHash.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FCompoundHash.m; path = Firebase/Database/Core/FCompoundHash.m; sourceTree = ""; }; + 3C94FF97478A1FE3BF81F60237C1B74C /* GTMSessionFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcher.m; path = Source/GTMSessionFetcher.m; sourceTree = ""; }; + 3C9B5809B81588128804C82CC7C0A448 /* FNextPushId.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FNextPushId.m; path = Firebase/Database/Utilities/FNextPushId.m; sourceTree = ""; }; + 3CFA6E1D288C15BD5851CFEDE6AEA633 /* FIROAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIROAuthProvider.h; path = Firebase/Auth/Source/Public/FIROAuthProvider.h; sourceTree = ""; }; + 3D1F68AB0DEB0CF2DB6829D440B69E95 /* FIRAnalyticsInterop.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAnalyticsInterop.h; path = Interop/Analytics/Public/FIRAnalyticsInterop.h; sourceTree = ""; }; + 3D44B58D46428E682FE8499CC2C0604A /* FIRStorage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorage.m; path = Firebase/Storage/FIRStorage.m; sourceTree = ""; }; + 3D4C5029B4F56F33C0AFF2C7BB347753 /* GULOriginalIMPConvenienceMacros.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULOriginalIMPConvenienceMacros.h; path = GoogleUtilities/MethodSwizzler/Private/GULOriginalIMPConvenienceMacros.h; sourceTree = ""; }; + 3DA0DF0B81ED2E59E65402AA12829CDE /* Pods-My Mind-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-My Mind-dummy.m"; sourceTree = ""; }; + 3DAED226313360A65EAC8D21A34E31EB /* FLimitedFilter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FLimitedFilter.m; path = Firebase/Database/Core/View/Filter/FLimitedFilter.m; sourceTree = ""; }; + 3E496823521868D352C97412E304C944 /* FIRComponentContainer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRComponentContainer.m; path = Firebase/Core/FIRComponentContainer.m; sourceTree = ""; }; + 3E58E6D786617300484ECDDFACB2FA6F /* FIRAuthKeychain.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthKeychain.m; path = Firebase/Auth/Source/FIRAuthKeychain.m; sourceTree = ""; }; + 3E7DE789305AEF826F8350378348A196 /* FIRVerifyAssertionResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyAssertionResponse.h; path = Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.h; sourceTree = ""; }; + 3EBE5619F4ACC24E1B1CE208BACAECC8 /* FIRStorageDownloadTask_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageDownloadTask_Private.h; path = Firebase/Storage/Private/FIRStorageDownloadTask_Private.h; sourceTree = ""; }; + 3F10F5BDFF54C0E2F5A47075F3A05D23 /* two_level_iterator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = two_level_iterator.h; path = table/two_level_iterator.h; sourceTree = ""; }; + 402D85148074A575F2F4BE6D41FE80D8 /* FIRCreateAuthURIRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRCreateAuthURIRequest.h; path = Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.h; sourceTree = ""; }; + 40A760468EF4E6190C18CA4B004F5C0E /* FIRUserInfoImpl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUserInfoImpl.h; path = Firebase/Auth/Source/FIRUserInfoImpl.h; sourceTree = ""; }; + 4109A974CBD18486C940B1F1487720A0 /* FConnection.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FConnection.m; path = Firebase/Database/Realtime/FConnection.m; sourceTree = ""; }; + 4246B1BF52A26AE14B7A2194FA5E3F47 /* GULNetworkLoggerProtocol.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULNetworkLoggerProtocol.h; path = GoogleUtilities/Network/Private/GULNetworkLoggerProtocol.h; sourceTree = ""; }; + 42561C54B242579DF60913AD632DCB9D /* Pods-My MindUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-My MindUITests-umbrella.h"; sourceTree = ""; }; + 42BC28884C5305F80E35B4E805480874 /* GTMSessionUploadFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionUploadFetcher.m; path = Source/GTMSessionUploadFetcher.m; sourceTree = ""; }; + 42BCBB4A4FDF6D8CDE4DFB7454B6BFD5 /* db_iter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = db_iter.h; path = db/db_iter.h; sourceTree = ""; }; + 4316D686D98DA93A0ADDA9AB857CCFEB /* FirebaseDatabase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseDatabase.h; path = Firebase/Database/Public/FirebaseDatabase.h; sourceTree = ""; }; + 43C51F661E1732A453C8FF3CC41FE99B /* FIRComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRComponent.m; path = Firebase/Core/FIRComponent.m; sourceTree = ""; }; + 43CFD5E85EB4EFD2F6AB4506880B8332 /* FEmptyNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEmptyNode.h; path = Firebase/Database/Snapshot/FEmptyNode.h; sourceTree = ""; }; + 44009DA6BD52A71E123946AA1B2A1CCC /* FIRAuthSerialTaskQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthSerialTaskQueue.m; path = Firebase/Auth/Source/FIRAuthSerialTaskQueue.m; sourceTree = ""; }; + 441DBA22AFAC3463555CEA3C57697304 /* Pods-My Mind.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My Mind.debug.xcconfig"; sourceTree = ""; }; + 44338CA1F8AA10479C391E3E8D0E9C1C /* FPath.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPath.h; path = Firebase/Database/Core/Utilities/FPath.h; sourceTree = ""; }; + 446370E4A06E1F0DF2205B16D666D0AD /* FIRAdditionalUserInfo_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAdditionalUserInfo_Internal.h; path = Firebase/Auth/Source/FIRAdditionalUserInfo_Internal.h; sourceTree = ""; }; + 44750059DC524A1D74F3CE34D403991A /* FIRGetAccountInfoResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetAccountInfoResponse.h; path = Firebase/Auth/Source/RPCs/FIRGetAccountInfoResponse.h; sourceTree = ""; }; + 4485AF69CA9E95F41797643FEB969885 /* FirebaseMessaging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseMessaging.h; path = Firebase/Messaging/FirebaseMessaging.h; sourceTree = ""; }; + 44976CFF5764982B4FF99FC51761D657 /* env.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = env.h; path = include/leveldb/env.h; sourceTree = ""; }; + 449CF3BAB6CA50258AE9DDCCF5354BB9 /* FIRStorageConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageConstants.h; path = Firebase/Storage/Public/FIRStorageConstants.h; sourceTree = ""; }; + 44B502759D088A3DA6A61F8E45DABA0D /* FIRUser.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUser.h; path = Firebase/Auth/Source/Public/FIRUser.h; sourceTree = ""; }; + 44B9DDFF12FCDEFFDA1030DE1B15DA23 /* GULLoggerLevel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULLoggerLevel.h; path = GoogleUtilities/Logger/Public/GULLoggerLevel.h; sourceTree = ""; }; + 45163B0967987CC35BE8D9091891B40E /* FIRStorageDeleteTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageDeleteTask.h; path = Firebase/Storage/Private/FIRStorageDeleteTask.h; sourceTree = ""; }; + 453054BE5330275352B536CFAF6B76CF /* GULAppEnvironmentUtil.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULAppEnvironmentUtil.m; path = GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.m; sourceTree = ""; }; + 455B531E0B5384D77DBDDA413F3CDF03 /* FIRAnalyticsConfiguration+Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "FIRAnalyticsConfiguration+Internal.h"; path = "Firebase/Core/Private/FIRAnalyticsConfiguration+Internal.h"; sourceTree = ""; }; + 45A06472A76E939B327F33F87CB8F5AA /* SwiftForms.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftForms.xcconfig; sourceTree = ""; }; + 46079141822DE20B0FF0729023B40DB5 /* FIRMessagingLogger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingLogger.h; path = Firebase/Messaging/FIRMessagingLogger.h; sourceTree = ""; }; + 4617A321F3C66DFCDB857489511992AE /* FIRUserMetadata_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUserMetadata_Internal.h; path = Firebase/Auth/Source/FIRUserMetadata_Internal.h; sourceTree = ""; }; + 471881B25F65AC42DDD5CF446E5F8504 /* FParsedUrl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FParsedUrl.h; path = Firebase/Database/Utilities/FParsedUrl.h; sourceTree = ""; }; + 4775A6201BD2BC8E8E2FA8486EF330FB /* FParsedUrl.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FParsedUrl.m; path = Firebase/Database/Utilities/FParsedUrl.m; sourceTree = ""; }; + 47A0DD80F32294AC8CB5952EC5A56807 /* SwiftForms.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftForms.framework; path = SwiftForms.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 47E32935FDCB1ACFE19F4A621AA5D7AF /* FTupleBoolBlock.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleBoolBlock.m; path = Firebase/Database/Utilities/Tuples/FTupleBoolBlock.m; sourceTree = ""; }; + 47FA58B556C9302949CF390A13E37DF8 /* FLimitedFilter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLimitedFilter.h; path = Firebase/Database/Core/View/Filter/FLimitedFilter.h; sourceTree = ""; }; + 4843041F19E32C7DB2152854218E02B7 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 484F43D7839874BA43FC7287627443B2 /* port_example.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = port_example.h; path = port/port_example.h; sourceTree = ""; }; + 4879E1F0A6D1768BFA268E9A80030B20 /* FIRSecureTokenRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSecureTokenRequest.m; path = Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.m; sourceTree = ""; }; + 48B55CE7E259B813481B4F6DC1EDA605 /* logging.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = logging.cc; path = util/logging.cc; sourceTree = ""; }; + 48F3B5DB6993BBECE9BD46E853AB5B02 /* GULAppEnvironmentUtil.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULAppEnvironmentUtil.h; path = GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h; sourceTree = ""; }; + 491F309FF0747418811867CB4A81B0BC /* FormSectionDescriptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSectionDescriptor.swift; path = SwiftForms/descriptors/FormSectionDescriptor.swift; sourceTree = ""; }; + 4A0E3FCADDEE6AF41C98BE9C52E8C2D4 /* FirebaseStorage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseStorage.h; path = Firebase/Storage/Public/FirebaseStorage.h; sourceTree = ""; }; + 4A3870091C969EE33FC9862E0AC8182F /* posix_logger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = posix_logger.h; path = util/posix_logger.h; sourceTree = ""; }; + 4A4825168FBBF46A0CF64FF8808816E3 /* FTrackedQueryManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTrackedQueryManager.h; path = Firebase/Database/Persistence/FTrackedQueryManager.h; sourceTree = ""; }; + 4AE4970E0E898EB674A647B25B6DBD64 /* FQueryParams.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FQueryParams.h; path = Firebase/Database/Core/FQueryParams.h; sourceTree = ""; }; + 4AEF839E0EBB783AE6036DF684293321 /* FChildChangeAccumulator.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FChildChangeAccumulator.m; path = Firebase/Database/Core/View/Filter/FChildChangeAccumulator.m; sourceTree = ""; }; + 4AFE8F37C120A82C78B58A29BCB9E818 /* FormDateCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormDateCell.swift; path = SwiftForms/cells/FormDateCell.swift; sourceTree = ""; }; + 4B2E73208606BF9C75DD9E3264B83E42 /* FIRSignUpNewUserResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSignUpNewUserResponse.m; path = Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.m; sourceTree = ""; }; + 4B3CE5E9EDAE6CD0767391FA890B04E0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 4B62BAF73F96F237E93C91E8FDE1A124 /* FLevelDBStorageEngine.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLevelDBStorageEngine.h; path = Firebase/Database/Persistence/FLevelDBStorageEngine.h; sourceTree = ""; }; + 4B850F7DC474EF9A15F3ACEAF70750DA /* GPBArray.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBArray.m; path = objectivec/GPBArray.m; sourceTree = ""; }; + 4B91F276ACCA0FA41F13EAFA194E3FDE /* leveldb-library-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "leveldb-library-prefix.pch"; sourceTree = ""; }; + 4B9FB583E7E3DD4C7B26A9FE34F5DF59 /* FIRMessagingInternalUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingInternalUtilities.h; path = Firebase/Messaging/InternalHeaders/FIRMessagingInternalUtilities.h; sourceTree = ""; }; + 4C7934CC4C320D6B8EED446F41CB3070 /* GtalkCore.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GtalkCore.pbobjc.m; path = Firebase/Messaging/Protos/GtalkCore.pbobjc.m; sourceTree = ""; }; + 4D1382328266FF86D9122C8BBD6C0C3E /* GoogleUtilities.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = GoogleUtilities.modulemap; sourceTree = ""; }; + 4DE03466C662D0024DF6BEFBB58CB658 /* FWriteTreeRef.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FWriteTreeRef.m; path = Firebase/Database/Core/FWriteTreeRef.m; sourceTree = ""; }; + 4E20EFABC4BDDD0348F7A103E0A8FDF7 /* FIRVerifyAssertionRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyAssertionRequest.h; path = Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.h; sourceTree = ""; }; + 4E26ACE066B49256AB80223CB1785409 /* GPBUtilities_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUtilities_PackagePrivate.h; path = objectivec/GPBUtilities_PackagePrivate.h; sourceTree = ""; }; + 4E654E9A462330D3F03252E972E0DD93 /* FServerValues.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FServerValues.m; path = Firebase/Database/Core/FServerValues.m; sourceTree = ""; }; + 4EB8204C84A0257A6B1C9421827E0260 /* Protobuf.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Protobuf.framework; path = Protobuf.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4F0A45134989F661BACC63DCA7091243 /* FIRFacebookAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRFacebookAuthProvider.h; path = Firebase/Auth/Source/Public/FIRFacebookAuthProvider.h; sourceTree = ""; }; + 4F0FDD548581BEE2026C81C115C042B5 /* FListenComplete.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FListenComplete.m; path = Firebase/Database/FListenComplete.m; sourceTree = ""; }; + 4F3D1610EF8189FF2768299FB5504646 /* FormTextViewCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormTextViewCell.swift; path = SwiftForms/cells/FormTextViewCell.swift; sourceTree = ""; }; + 4FB98B53519A3F306A0403D5C63DEFAC /* FIRStorage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorage.h; path = Firebase/Storage/Public/FIRStorage.h; sourceTree = ""; }; + 4FE6FFD73A1F41902CEAA39F2D6CAD7A /* FIRVerifyClientRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyClientRequest.m; path = Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.m; sourceTree = ""; }; + 501C43E7B305FE3D8E1CDC5276D26E98 /* Empty.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Empty.pbobjc.m; path = objectivec/google/protobuf/Empty.pbobjc.m; sourceTree = ""; }; + 502015322F13E326A360FF358E29B946 /* FKeyIndex.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FKeyIndex.m; path = Firebase/Database/FKeyIndex.m; sourceTree = ""; }; + 5035A64EE2A9A3DB9A03376F395A3702 /* FIREmailAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIREmailAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailAuthProvider.m; sourceTree = ""; }; + 504066F2745B7E4AD642CAD54BDE53EC /* Pods-My Mind-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My Mind-frameworks.sh"; sourceTree = ""; }; + 50630886A093E6270164CC7ECE54E54E /* FSnapshotHolder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSnapshotHolder.m; path = Firebase/Database/Core/FSnapshotHolder.m; sourceTree = ""; }; + 508285CBB0038322C3CDFA2C14D67013 /* FIRErrorCode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRErrorCode.h; path = Firebase/Core/Private/FIRErrorCode.h; sourceTree = ""; }; + 50B1EEF969FB395B98F5ACBC29642FB0 /* FIRAuthWebUtils.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthWebUtils.m; path = Firebase/Auth/Source/FIRAuthWebUtils.m; sourceTree = ""; }; + 50D59C3FF3C181DB023918A1E27B460A /* Pods-My MindUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My MindUITests.release.xcconfig"; sourceTree = ""; }; + 50D69B40CB7B6EE788D4ED8121EE5627 /* FIRAuthAPNSToken.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAPNSToken.h; path = Firebase/Auth/Source/FIRAuthAPNSToken.h; sourceTree = ""; }; + 50E2D1A1F604F7B2D4C65D599DB5CFF4 /* leveldb.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = leveldb.framework; path = "leveldb-library.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 512270231AF1BD7162D2DF64A91E39D7 /* FIRGameCenterAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGameCenterAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthProvider.m; sourceTree = ""; }; + 519AD2081997EB288B842570149B0B7F /* FIRMessagingDataMessageManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingDataMessageManager.h; path = Firebase/Messaging/FIRMessagingDataMessageManager.h; sourceTree = ""; }; + 51B29CF73AD215059BC28D3753ECE814 /* FIRMessagingUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingUtilities.h; path = Firebase/Messaging/FIRMessagingUtilities.h; sourceTree = ""; }; + 5223757BD175F800FD48E7DE0E939530 /* write_batch.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = write_batch.cc; path = db/write_batch.cc; sourceTree = ""; }; + 52989DBD560D819C3DAE5CD912033DD8 /* FView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FView.m; path = Firebase/Database/Core/View/FView.m; sourceTree = ""; }; + 52DDE7C94F2CFD1F4B7D89EAD53BDA16 /* dbformat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = dbformat.h; path = db/dbformat.h; sourceTree = ""; }; + 52DFF27FBBEDFDB18FA44BEAD7283C38 /* FIRVerifyPhoneNumberRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyPhoneNumberRequest.h; path = Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.h; sourceTree = ""; }; + 52E24DBE1C27A0E703963706FF750477 /* FirebaseCoreDiagnostics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseCoreDiagnostics.framework; path = Frameworks/FirebaseCoreDiagnostics.framework; sourceTree = ""; }; + 532A60C333164404D23A05ACB55C6E71 /* leveldb-library.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "leveldb-library.xcconfig"; sourceTree = ""; }; + 5383E534FCBF0988CDB5DE655E026D79 /* FIRStorageConstants_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageConstants_Private.h; path = Firebase/Storage/Private/FIRStorageConstants_Private.h; sourceTree = ""; }; + 54A71EF90151DC4A91CDE20EBE275C1C /* GPBCodedOutputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBCodedOutputStream.m; path = objectivec/GPBCodedOutputStream.m; sourceTree = ""; }; + 54B748CB1F4B495705943806D14E57CD /* dumpfile.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = dumpfile.h; path = include/leveldb/dumpfile.h; sourceTree = ""; }; + 54D2205BB0299DF468F8355C100D0647 /* GTMSessionUploadFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionUploadFetcher.h; path = Source/GTMSessionUploadFetcher.h; sourceTree = ""; }; + 54DB67BBBF0DFC563CE6CFB817F5D9A7 /* FIRAnalyticsConnector.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FIRAnalyticsConnector.framework; path = Frameworks/FIRAnalyticsConnector.framework; sourceTree = ""; }; + 550F30B53D98C5B179E6C9B95DCBBD49 /* FIRMessagingRmq2PersistentStore.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingRmq2PersistentStore.m; path = Firebase/Messaging/FIRMessagingRmq2PersistentStore.m; sourceTree = ""; }; + 55151CA7726A3419117D3B576C43A54B /* GPBUnknownFieldSet_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownFieldSet_PackagePrivate.h; path = objectivec/GPBUnknownFieldSet_PackagePrivate.h; sourceTree = ""; }; + 551DE73F29DCBD088E26B78CC09409E8 /* testutil.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = testutil.h; path = util/testutil.h; sourceTree = ""; }; + 5535B79D79A1DB6E12BED6FEEA04B485 /* FIRStorageTokenAuthorizer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageTokenAuthorizer.m; path = Firebase/Storage/FIRStorageTokenAuthorizer.m; sourceTree = ""; }; + 5546B6C998BFFC4D1BE353AACAB4656B /* FIRAuthNotificationManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthNotificationManager.m; path = Firebase/Auth/Source/FIRAuthNotificationManager.m; sourceTree = ""; }; + 55F0AD247ED58C88A9CA3DFACE27D5B4 /* FIRInteropParameterNames.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRInteropParameterNames.h; path = Interop/Analytics/Public/FIRInteropParameterNames.h; sourceTree = ""; }; + 56DBAB0E527B855D6B1FEA68A8CF3582 /* FIRTransactionResult.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRTransactionResult.m; path = Firebase/Database/Api/FIRTransactionResult.m; sourceTree = ""; }; + 580D3A9DD3E77BC53E3D35F0023DDE1E /* FIRMessagingPubSub.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingPubSub.m; path = Firebase/Messaging/FIRMessagingPubSub.m; sourceTree = ""; }; + 58487CE27CDAA3A239CAED5DA382A40F /* FPathIndex.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPathIndex.h; path = Firebase/Database/FPathIndex.h; sourceTree = ""; }; + 58D5C0A45F0C7FAA8267304BFB70E2B2 /* FIRMessagingDataMessageManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingDataMessageManager.m; path = Firebase/Messaging/FIRMessagingDataMessageManager.m; sourceTree = ""; }; + 58DAD62A1384B6C2202497AAECD4FEF9 /* FIRAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthCredential.m; path = Firebase/Auth/Source/FIRAuthCredential.m; sourceTree = ""; }; + 58F22BD1F34CA15EC75B42909369C0E6 /* histogram.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = histogram.cc; path = util/histogram.cc; sourceTree = ""; }; + 5A1D1A56E980A843F4C35E043C9858B9 /* FormErrorType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormErrorType.swift; path = SwiftForms/FormErrorType.swift; sourceTree = ""; }; + 5A78F386367CAE629EB35C78D895997D /* APLevelDB.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = APLevelDB.h; path = "Firebase/Database/third_party/Wrap-leveldb/APLevelDB.h"; sourceTree = ""; }; + 5B8615B87DA0E29530C8BE4B47E2D4FE /* FormViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormViewController.swift; path = SwiftForms/controllers/FormViewController.swift; sourceTree = ""; }; + 5BB790ABECC5AB46EEC32C04E1E3DE9D /* FIRMessagingRegistrar.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingRegistrar.m; path = Firebase/Messaging/FIRMessagingRegistrar.m; sourceTree = ""; }; + 5C1FEDE4CE6EE40E810E2832FFCC90B6 /* Pods-My MindTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-My MindTests.modulemap"; sourceTree = ""; }; + 5C23BD54A2D7173A773BCF67F06B63BD /* FIRStorageGetDownloadURLTask_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageGetDownloadURLTask_Private.h; path = Firebase/Storage/Private/FIRStorageGetDownloadURLTask_Private.h; sourceTree = ""; }; + 5C2A3940C1CF640AD9EB12D78F0AEAF4 /* FServerValues.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FServerValues.h; path = Firebase/Database/Core/FServerValues.h; sourceTree = ""; }; + 5CB11A8A37A78CD677212D20B4EC9A5E /* hash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash.h; path = util/hash.h; sourceTree = ""; }; + 5D2E468E56AC4645517F8EF8383EFA59 /* FIRVerifyPasswordResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyPasswordResponse.h; path = Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.h; sourceTree = ""; }; + 5D650E258391748C898E6F33D5F2942A /* FIREmailLinkSignInResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIREmailLinkSignInResponse.h; path = Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.h; sourceTree = ""; }; + 5D65988F3A1356BEE3BC3D0369BBAAC9 /* FIRMessagingCodedInputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingCodedInputStream.h; path = Firebase/Messaging/FIRMessagingCodedInputStream.h; sourceTree = ""; }; + 5D9EAD1637B2E283AC5ACDA1E015C325 /* FIRAuthDispatcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthDispatcher.m; path = Firebase/Auth/Source/FIRAuthDispatcher.m; sourceTree = ""; }; + 5DBC97B383D5D93C4468FCF29B800674 /* FIRMessagingClient.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingClient.h; path = Firebase/Messaging/FIRMessagingClient.h; sourceTree = ""; }; + 5DC32D3EC7D2CD53597176FFB6E5F799 /* FIRAuthRequestConfiguration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthRequestConfiguration.m; path = Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.m; sourceTree = ""; }; + 5DD690A210A0BA32F0BF15C1E07B4A65 /* FMaxNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMaxNode.h; path = Firebase/Database/FMaxNode.h; sourceTree = ""; }; + 5E738E7BF1FBC0B364B61BD03515B68F /* fbase64.c */ = {isa = PBXFileReference; includeInIndex = 1; name = fbase64.c; path = Firebase/Database/third_party/SocketRocket/fbase64.c; sourceTree = ""; }; + 5E7945D06F7A9490E3DFDF843C010E48 /* FIRAuthWebUtils.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthWebUtils.h; path = Firebase/Auth/Source/FIRAuthWebUtils.h; sourceTree = ""; }; + 5F1A41B7E7B1BF73570D4029B7CB70B6 /* GULNetworkURLSession.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULNetworkURLSession.m; path = GoogleUtilities/Network/GULNetworkURLSession.m; sourceTree = ""; }; + 5F891930020EE03609EADEDCA0FD6F6B /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 5FB080F12F054F57F892AECEA7DFEE41 /* GPBDictionary_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDictionary_PackagePrivate.h; path = objectivec/GPBDictionary_PackagePrivate.h; sourceTree = ""; }; + 6056409035CBAA33FC4C1E992C685A4D /* FIROAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIROAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.m; sourceTree = ""; }; + 60DDA174CF0B3BB875E4D2CAF65B71EE /* FNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FNode.h; path = Firebase/Database/Snapshot/FNode.h; sourceTree = ""; }; + 60F0F5A859C55E91E94D4D5F10B28B92 /* FTreeSortedDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTreeSortedDictionary.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionary.h; sourceTree = ""; }; + 614B59B42151155D33BBF932D5542E46 /* FTree.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTree.m; path = Firebase/Database/Core/Utilities/FTree.m; sourceTree = ""; }; + 618C547333D8EAF01B8180DECD81E059 /* FCancelEvent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FCancelEvent.m; path = Firebase/Database/Core/View/FCancelEvent.m; sourceTree = ""; }; + 61B27FDBC34602CF2A3DFD944ED2B245 /* FIRAuthURLPresenter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthURLPresenter.h; path = Firebase/Auth/Source/FIRAuthURLPresenter.h; sourceTree = ""; }; + 624733EE470333F41A1A1BCC618446EC /* GPBProtocolBuffers.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBProtocolBuffers.h; path = objectivec/GPBProtocolBuffers.h; sourceTree = ""; }; + 62AADFBC08D568729C990BADB7ECB893 /* FIRVerifyAssertionRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyAssertionRequest.m; path = Firebase/Auth/Source/RPCs/FIRVerifyAssertionRequest.m; sourceTree = ""; }; + 62B3DC5F0A104BF4ACF3B85C55D99BC4 /* log_format.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = log_format.h; path = db/log_format.h; sourceTree = ""; }; + 634AC4F4C75AE1D5C975FD26D60B8E3E /* GPBCodedInputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBCodedInputStream.m; path = objectivec/GPBCodedInputStream.m; sourceTree = ""; }; + 636106B60C9506E961ADC79797A5739D /* GULLogger.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULLogger.m; path = GoogleUtilities/Logger/GULLogger.m; sourceTree = ""; }; + 6440D16966C799ADA6FF8B1D0F21716D /* GULUserDefaults.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULUserDefaults.m; path = GoogleUtilities/UserDefaults/GULUserDefaults.m; sourceTree = ""; }; + 64D9C3082504A3C076123EC5A427666E /* FCompoundHash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCompoundHash.h; path = Firebase/Database/Core/FCompoundHash.h; sourceTree = ""; }; + 64EB27157BEA9B6EBFBC9D30A55480BE /* FIRGetProjectConfigResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetProjectConfigResponse.h; path = Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.h; sourceTree = ""; }; + 6506C0D8E4A809C7E2AA6AD0EC391E50 /* FIRSetAccountInfoResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSetAccountInfoResponse.m; path = Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.m; sourceTree = ""; }; + 65353A37CF47A6651F323694730E2BC7 /* FIRMessagingDelayedMessageQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingDelayedMessageQueue.m; path = Firebase/Messaging/FIRMessagingDelayedMessageQueue.m; sourceTree = ""; }; + 656C3EA7E5E83D408C6465B56BA18268 /* FirebaseCore.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FirebaseCore.modulemap; sourceTree = ""; }; + 658A768CC068B2D7E13BF84FFC821C7D /* FChildEventRegistration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FChildEventRegistration.m; path = Firebase/Database/Core/View/FChildEventRegistration.m; sourceTree = ""; }; + 65ACC8103EBC8FC94891C616DFB37168 /* FTupleNodePath.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleNodePath.m; path = Firebase/Database/Utilities/Tuples/FTupleNodePath.m; sourceTree = ""; }; + 65B16A3C4124590E56D417A1088A2B7A /* FIRSignInWithGameCenterRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSignInWithGameCenterRequest.h; path = Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.h; sourceTree = ""; }; + 66861CF6B01E5AA0D15E1B102B1ED8CC /* FIRSecureTokenResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSecureTokenResponse.m; path = Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.m; sourceTree = ""; }; + 672F641C8ED1591333E51751747D9051 /* GPBDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBDictionary.m; path = objectivec/GPBDictionary.m; sourceTree = ""; }; + 673AC49687E8659EB56A9747F2AD855A /* FIROAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIROAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthProvider.m; sourceTree = ""; }; + 676357AD124D2145D88CF5C3AEDE005C /* memtable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = memtable.h; path = db/memtable.h; sourceTree = ""; }; + 6770B86455BBED608BD0F1FCAA2346F9 /* FIRSignInWithGameCenterResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSignInWithGameCenterResponse.m; path = Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.m; sourceTree = ""; }; + 68055C3921D68B4D2A9E01154969543C /* FIRUserMetadata.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRUserMetadata.m; path = Firebase/Auth/Source/FIRUserMetadata.m; sourceTree = ""; }; + 682F99F9C42A5FE4D526C915C7792F54 /* FIRStorageTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageTask.m; path = Firebase/Storage/FIRStorageTask.m; sourceTree = ""; }; + 682FB182ED2813B933EC052FF4298A6F /* FirebaseCore-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FirebaseCore-dummy.m"; sourceTree = ""; }; + 68676BA36D0C984D720E7033B11A06E5 /* two_level_iterator.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = two_level_iterator.cc; path = table/two_level_iterator.cc; sourceTree = ""; }; + 68AB70689ECD68BDF9F973D46450CA1F /* FIRVerifyCustomTokenResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyCustomTokenResponse.m; path = Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.m; sourceTree = ""; }; + 68EDBB86127032AD3CCD427465F5057A /* FIndexedNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIndexedNode.m; path = Firebase/Database/Snapshot/FIndexedNode.m; sourceTree = ""; }; + 693C9B5BD6AC380C76B3E002A24AC9F5 /* FAuthTokenProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FAuthTokenProvider.h; path = Firebase/Database/Login/FAuthTokenProvider.h; sourceTree = ""; }; + 69B1781DA481AC22CFA714AD4D223D72 /* FTupleUserCallback.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleUserCallback.m; path = Firebase/Database/Utilities/Tuples/FTupleUserCallback.m; sourceTree = ""; }; + 6A978CCB0F810856629565567CB0B1DC /* block_builder.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = block_builder.cc; path = table/block_builder.cc; sourceTree = ""; }; + 6AD51002F5F86EBA67F6340027B559A1 /* port.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = port.h; path = port/port.h; sourceTree = ""; }; + 6B9420FD08C302FF4ABE9F9E8AB18A16 /* FIRSignUpNewUserResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSignUpNewUserResponse.h; path = Firebase/Auth/Source/RPCs/FIRSignUpNewUserResponse.h; sourceTree = ""; }; + 6BA5FFAECDA46681242C8C8C12B8DF75 /* FKeyIndex.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FKeyIndex.h; path = Firebase/Database/FKeyIndex.h; sourceTree = ""; }; + 6C021F5E4C2CF0638FF24E140E7DCA92 /* db_iter.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = db_iter.cc; path = db/db_iter.cc; sourceTree = ""; }; + 6C2D515DB16433C8F3E59AAF36EF38EE /* NSError+FIRMessaging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSError+FIRMessaging.m"; path = "Firebase/Messaging/NSError+FIRMessaging.m"; sourceTree = ""; }; + 6CBEB890F1BD0F79AC3D8CE936C581EE /* FIRGoogleAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGoogleAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthCredential.h; sourceTree = ""; }; + 6D031DF463461821CD42F1C393E912D7 /* GPBMessage_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBMessage_PackagePrivate.h; path = objectivec/GPBMessage_PackagePrivate.h; sourceTree = ""; }; + 6D95EAFED5C6BABDD29651946338BA3C /* FStringUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FStringUtilities.h; path = Firebase/Database/Utilities/FStringUtilities.h; sourceTree = ""; }; + 6E31586DA53A4DBE99F094125C8BEF15 /* GoogleUtilities.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GoogleUtilities.framework; path = GoogleUtilities.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6F11B8D726B6EB35E25DBAFF2E410D30 /* GtalkExtensions.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GtalkExtensions.pbobjc.m; path = Firebase/Messaging/Protos/GtalkExtensions.pbobjc.m; sourceTree = ""; }; + 70B2BC7C8E160DF34E8B88E3EC14A5F4 /* FIRSetAccountInfoRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSetAccountInfoRequest.h; path = Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.h; sourceTree = ""; }; + 70BF98E2DC5C000BD8610127B3AD8AF6 /* FIRAuthTokenResult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthTokenResult.h; path = Firebase/Auth/Source/Public/FIRAuthTokenResult.h; sourceTree = ""; }; + 7195FC7DA43CAFF389557007B61500CF /* FIRTwitterAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRTwitterAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthCredential.h; sourceTree = ""; }; + 71A5CCCB943C336F5BFE3C9B27E25543 /* bloom.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = bloom.cc; path = util/bloom.cc; sourceTree = ""; }; + 71B41FCA331929B285069B056D11187C /* SourceContext.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SourceContext.pbobjc.h; path = objectivec/google/protobuf/SourceContext.pbobjc.h; sourceTree = ""; }; + 721B542A1F80BE1951DE5AB8C5CECDF4 /* random.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = random.h; path = util/random.h; sourceTree = ""; }; + 7220181B4FADE1BE7B6FDD9CA2FF21E6 /* write_batch_internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = write_batch_internal.h; path = db/write_batch_internal.h; sourceTree = ""; }; + 72AA3FD7FCFBF9B31AE268CA36CDF564 /* slice.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = slice.h; path = include/leveldb/slice.h; sourceTree = ""; }; + 72B13FA9D89B5C3A0B31E47601B35B31 /* FIREmailLinkSignInResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIREmailLinkSignInResponse.m; path = Firebase/Auth/Source/RPCs/FIREmailLinkSignInResponse.m; sourceTree = ""; }; + 72DAEB8DAF3F23E6A8C884A9E87C387E /* FIRGetProjectConfigRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetProjectConfigRequest.m; path = Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.m; sourceTree = ""; }; + 7334FFB579A1884B99237373A09774DD /* arena.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = arena.cc; path = util/arena.cc; sourceTree = ""; }; + 736C022A06E3955768DC6544360A723E /* FIRMessagingSecureSocket.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingSecureSocket.h; path = Firebase/Messaging/FIRMessagingSecureSocket.h; sourceTree = ""; }; + 738805EF3840CA94F81C79BA9A95D52F /* FIRStorageObservableTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageObservableTask.m; path = Firebase/Storage/FIRStorageObservableTask.m; sourceTree = ""; }; + 73E2B0654C8EA0F00AB43543CBD124F7 /* FTupleTransaction.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleTransaction.h; path = Firebase/Database/Utilities/Tuples/FTupleTransaction.h; sourceTree = ""; }; + 7404327BB8BA8D0F2BE2231D7D1349BF /* FTupleOnDisconnect.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleOnDisconnect.h; path = Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.h; sourceTree = ""; }; + 7419C5FA3F1E39B79BC98148F8B303C2 /* FTreeSortedDictionaryEnumerator.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTreeSortedDictionaryEnumerator.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.m; sourceTree = ""; }; + 743A102405B7E18D6CA2D8402079C09D /* Pods-My MindTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-My MindTests-acknowledgements.markdown"; sourceTree = ""; }; + 74E0D6E907564B3A142EAA69A8541AD6 /* FIRGameCenterAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGameCenterAuthProvider.h; path = Firebase/Auth/Source/Public/FIRGameCenterAuthProvider.h; sourceTree = ""; }; + 74E740E1ED09434A0A93BA9D4953AB65 /* FCancelEvent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCancelEvent.h; path = Firebase/Database/Core/View/FCancelEvent.h; sourceTree = ""; }; + 750AE2BD4EAC19C11179AC6E5CE3BF7E /* Pods-My Mind-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-My Mind-umbrella.h"; sourceTree = ""; }; + 7568B7BB638B453805A7B08112D98D8E /* FDataEvent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FDataEvent.h; path = Firebase/Database/Core/View/FDataEvent.h; sourceTree = ""; }; + 7577A71A88803C69782A292FCE3A8583 /* GTMSessionFetcherService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherService.m; path = Source/GTMSessionFetcherService.m; sourceTree = ""; }; + 757B37187411893E58EA0016D7EA32AD /* FViewProcessor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FViewProcessor.m; path = Firebase/Database/FViewProcessor.m; sourceTree = ""; }; + 757D739372A973A1A6B387E52878A9B6 /* FirebaseStorage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FirebaseStorage-dummy.m"; sourceTree = ""; }; + 758F44968682287AD497896C6C56B2F6 /* FIROAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIROAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/OAuth/FIROAuthCredential.h; sourceTree = ""; }; + 75F85C975C09185C0E84A04DA191DF1A /* block.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = block.cc; path = table/block.cc; sourceTree = ""; }; + 7635E3F9E1F28E2FD77AD02BFB30ED18 /* FIRVerifyPasswordResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyPasswordResponse.m; path = Firebase/Auth/Source/RPCs/FIRVerifyPasswordResponse.m; sourceTree = ""; }; + 769FB4DFF434F108F981154B69D3C883 /* FIRGitHubAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGitHubAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.h; sourceTree = ""; }; + 76BF777E514F1D6AA78DE3FA6FE1E13B /* filename.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = filename.cc; path = db/filename.cc; sourceTree = ""; }; + 76E425DE58AFB1DFDD7497FB60D1E793 /* FIRMessagingPubSub.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingPubSub.h; path = Firebase/Messaging/FIRMessagingPubSub.h; sourceTree = ""; }; + 777D09D2C04A9EDDF146AD4F850B0308 /* FIRLoggerLevel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRLoggerLevel.h; path = Firebase/Core/Public/FIRLoggerLevel.h; sourceTree = ""; }; + 77F9D6EC5529498A65162396F20E0832 /* FIRAuthDispatcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthDispatcher.h; path = Firebase/Auth/Source/FIRAuthDispatcher.h; sourceTree = ""; }; + 78440266C0C83884693EF81EF27A2251 /* FTreeSortedDictionaryEnumerator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTreeSortedDictionaryEnumerator.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FTreeSortedDictionaryEnumerator.h; sourceTree = ""; }; + 7861ACAB61D863B75747C507485CF5FF /* filter_policy.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = filter_policy.cc; path = util/filter_policy.cc; sourceTree = ""; }; + 786FC9011A3F7E09EB395D9E4BAC2FA2 /* FIRServerValue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRServerValue.h; path = Firebase/Database/Public/FIRServerValue.h; sourceTree = ""; }; + 7871920E4D29C4D70144578BF057710F /* FIRDatabaseQuery_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseQuery_Private.h; path = Firebase/Database/Api/Private/FIRDatabaseQuery_Private.h; sourceTree = ""; }; + 789256212F2759B2374887DCC6A6854E /* GTMSessionFetcherLogging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherLogging.h; path = Source/GTMSessionFetcherLogging.h; sourceTree = ""; }; + 789F71E8E85917ED0CBB539BF3DB75AE /* FIRStorageMetadata.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageMetadata.m; path = Firebase/Storage/FIRStorageMetadata.m; sourceTree = ""; }; + 796A9E6A5DF0679ED69FE7F4CDC25199 /* FIRVersion.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVersion.h; path = Firebase/Core/Private/FIRVersion.h; sourceTree = ""; }; + 7971586793756023D72E620D4BE9E456 /* FEvent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEvent.h; path = Firebase/Database/Core/View/FEvent.h; sourceTree = ""; }; + 7A28513C7E79F8D83ACCE3ADDEB0CA1B /* FIRComponentType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRComponentType.h; path = Firebase/Core/Private/FIRComponentType.h; sourceTree = ""; }; + 7AA64C916741F0BA7ADBC05AC52D974A /* cache.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = cache.cc; path = util/cache.cc; sourceTree = ""; }; + 7AD846363197EE2C3BD4CA30EC8D8C44 /* FQuerySpec.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FQuerySpec.m; path = Firebase/Database/Core/FQuerySpec.m; sourceTree = ""; }; + 7ADD427EA772DEE9928CC4A60652E1F1 /* Pods-My MindTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My MindTests-frameworks.sh"; sourceTree = ""; }; + 7AF6DE6416DB4C133F69C73FA0A99C96 /* FIRAuthExceptionUtils.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthExceptionUtils.m; path = Firebase/Auth/Source/FIRAuthExceptionUtils.m; sourceTree = ""; }; + 7B5056278F8531591B36DB9DB2654F5D /* FormTextFieldCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormTextFieldCell.swift; path = SwiftForms/cells/FormTextFieldCell.swift; sourceTree = ""; }; + 7BBCD51FAF30C35611BEB23B626C6624 /* FIRSignUpNewUserRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSignUpNewUserRequest.h; path = Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.h; sourceTree = ""; }; + 7BF676BAC287FD9AF2842E1602416108 /* FIRDependency.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDependency.h; path = Firebase/Core/Private/FIRDependency.h; sourceTree = ""; }; + 7C28C0FC58ECA858722F32BCA5B0E6A6 /* GTMSessionFetcher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = GTMSessionFetcher.modulemap; sourceTree = ""; }; + 7C67A508BEE66D05F3D060B80EB08B92 /* FIRDatabaseReference_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseReference_Private.h; path = Firebase/Database/Api/Private/FIRDatabaseReference_Private.h; sourceTree = ""; }; + 7C8725D11133377692FA563EF613C7C6 /* FIRGetProjectConfigRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetProjectConfigRequest.h; path = Firebase/Auth/Source/RPCs/FIRGetProjectConfigRequest.h; sourceTree = ""; }; + 7C96AB097262F1C3DCC11C50D3E59544 /* FIRMessagingVersionUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingVersionUtilities.m; path = Firebase/Messaging/FIRMessagingVersionUtilities.m; sourceTree = ""; }; + 7D10BD44F431CB676BA0F99531C372EC /* GPBBootstrap.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBBootstrap.h; path = objectivec/GPBBootstrap.h; sourceTree = ""; }; + 7D37B39157C7D0EC71A0F813C9CFC9AA /* Pods_My_Mind.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_My_Mind.framework; path = "Pods-My Mind.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 7D69CF64D7DD9D1CB88D623B60BFA93C /* table_cache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = table_cache.h; path = db/table_cache.h; sourceTree = ""; }; + 7D7C14FEC5F42750CFF7801E2502AA30 /* FormSelector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSelector.swift; path = SwiftForms/controllers/FormSelector.swift; sourceTree = ""; }; + 7D8E3F4071E80D79F82FA3705A1B7D05 /* FIREmailPasswordAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIREmailPasswordAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h; sourceTree = ""; }; + 7DBC6776E71F32FE26F370F3CC2E5792 /* NSData+FIRBase64.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+FIRBase64.m"; path = "Firebase/Auth/Source/NSData+FIRBase64.m"; sourceTree = ""; }; + 7DC9FDF211772BFF5911D9544841884F /* FImmutableTree.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FImmutableTree.m; path = Firebase/Database/Core/Utilities/FImmutableTree.m; sourceTree = ""; }; + 7DD22742CF31B2734B421A041B5F23FA /* FIRGetOOBConfirmationCodeRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetOOBConfirmationCodeRequest.h; path = Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeRequest.h; sourceTree = ""; }; + 7E04F48A3C2F6EC156E49CC1BD8AFA0D /* write_batch.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = write_batch.h; path = include/leveldb/write_batch.h; sourceTree = ""; }; + 7E14FE7B650352A45172263EB07521FA /* table_builder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = table_builder.h; path = include/leveldb/table_builder.h; sourceTree = ""; }; + 7E38B04C7F997C0C975D2B0D29941212 /* FIRSecureTokenService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSecureTokenService.m; path = Firebase/Auth/Source/FIRSecureTokenService.m; sourceTree = ""; }; + 7F9F88FADC98B9224D1E76814149FA28 /* FViewCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FViewCache.h; path = Firebase/Database/Core/View/FViewCache.h; sourceTree = ""; }; + 7FBE764F8D555B5617404FEE2CB64111 /* FirebaseAuth-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FirebaseAuth-dummy.m"; sourceTree = ""; }; + 7FBFC1F7E73045485048A8A2FE6C9932 /* GoogleUtilities-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleUtilities-prefix.pch"; sourceTree = ""; }; + 8045F511732AF21BD969650BBDB79264 /* FIRMessagingAnalytics.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingAnalytics.m; path = Firebase/Messaging/FIRMessagingAnalytics.m; sourceTree = ""; }; + 8086976E909F242ED65F58A319245ADD /* FIRAuthTokenResult.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthTokenResult.m; path = Firebase/Auth/Source/FIRAuthTokenResult.m; sourceTree = ""; }; + 80F60B07C2849F8B4E6E25DE44C5FB6E /* GPBCodedOutputStream_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedOutputStream_PackagePrivate.h; path = objectivec/GPBCodedOutputStream_PackagePrivate.h; sourceTree = ""; }; + 814BDBAAB7D6AF52DD7C730CB57ED235 /* options.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = options.cc; path = util/options.cc; sourceTree = ""; }; + 81E8A3CD852063E84294E4611723E4AE /* FirebaseMessaging.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FirebaseMessaging.framework; path = FirebaseMessaging.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8200BDBCECE4B63C77D401E6C30EF965 /* FTupleObjects.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleObjects.m; path = Firebase/Database/Utilities/Tuples/FTupleObjects.m; sourceTree = ""; }; + 82B3C6D58D32965D5CB48FD4B37BA1A4 /* FIRUser.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRUser.m; path = Firebase/Auth/Source/FIRUser.m; sourceTree = ""; }; + 82BF3B71827ABBD71A94D5711CFE9608 /* FIREmailLinkSignInRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIREmailLinkSignInRequest.m; path = Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.m; sourceTree = ""; }; + 82C76459EDA44C637947DB893A87631C /* Firebase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Firebase.h; path = CoreOnly/Sources/Firebase.h; sourceTree = ""; }; + 82DF20A0A666925390FA680456D04F84 /* FieldMask.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FieldMask.pbobjc.h; path = objectivec/google/protobuf/FieldMask.pbobjc.h; sourceTree = ""; }; + 82EF6EA3A6D823BECFDF2D38E49A1895 /* FIRVerifyAssertionResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyAssertionResponse.m; path = Firebase/Auth/Source/RPCs/FIRVerifyAssertionResponse.m; sourceTree = ""; }; + 82FDABA5276C7AE2C5B8E81051C68E2F /* FLLRBValueNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FLLRBValueNode.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBValueNode.m; sourceTree = ""; }; + 8354D5D2A1E3BE749C059D69DD9A80E4 /* FIRComponentRegistrant.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRComponentRegistrant.h; path = Firebase/Core/Private/FIRComponentRegistrant.h; sourceTree = ""; }; + 83AA3E602C3A2961790AEAADF22D1659 /* FIRGetProjectConfigResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetProjectConfigResponse.m; path = Firebase/Auth/Source/RPCs/FIRGetProjectConfigResponse.m; sourceTree = ""; }; + 8583A2B8E76D50FAD075A623EF4D16DD /* FIRStorageUploadTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageUploadTask.m; path = Firebase/Storage/FIRStorageUploadTask.m; sourceTree = ""; }; + 8762AF452D56EBD17C7FA8105C46E226 /* GULNetwork.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULNetwork.h; path = GoogleUtilities/Network/Private/GULNetwork.h; sourceTree = ""; }; + 87B8DEE29C9DF557484295F12A135E87 /* FIRStorageGetMetadataTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageGetMetadataTask.h; path = Firebase/Storage/Private/FIRStorageGetMetadataTask.h; sourceTree = ""; }; + 87D05F4B7557FD9A9E830518CB5D0024 /* SwiftForms-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftForms-dummy.m"; sourceTree = ""; }; + 880603C3679A606EFFF7E1252ED39621 /* FIRStorageTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageTask.h; path = Firebase/Storage/Public/FIRStorageTask.h; sourceTree = ""; }; + 880A5D3DF4E4D6D8C3FE7C96B0B2BCAA /* FViewProcessorResult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FViewProcessorResult.h; path = Firebase/Database/FViewProcessorResult.h; sourceTree = ""; }; + 89F5B99A9E0786C553D21D862D2B5827 /* FieldMask.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FieldMask.pbobjc.m; path = objectivec/google/protobuf/FieldMask.pbobjc.m; sourceTree = ""; }; + 8AC604D9BBD33F425A70127321354580 /* FCachePolicy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FCachePolicy.m; path = Firebase/Database/Persistence/FCachePolicy.m; sourceTree = ""; }; + 8AE098A043EF747C4AB64731CEDC3FA3 /* FIRAuthSettings.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthSettings.m; path = Firebase/Auth/Source/FIRAuthSettings.m; sourceTree = ""; }; + 8BBC26AF6B9C5D76177286CF09E095BE /* Wrappers.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Wrappers.pbobjc.m; path = objectivec/google/protobuf/Wrappers.pbobjc.m; sourceTree = ""; }; + 8C7AF4806829E1A7FBD4AC2CF543B2DA /* FIRGameCenterAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGameCenterAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.h; sourceTree = ""; }; + 8C931CB859E88BFAED40B1C16793FB9A /* FTrackedQuery.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTrackedQuery.m; path = Firebase/Database/Persistence/FTrackedQuery.m; sourceTree = ""; }; + 8CB4ECDE1DB0FA76A4986D8BD55DE75B /* Protobuf.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Protobuf.modulemap; sourceTree = ""; }; + 8CD5C008865F5A9168D53CDA45E6740F /* SafariServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SafariServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/SafariServices.framework; sourceTree = DEVELOPER_DIR; }; + 8D26ADA472AEBC9DE9C44BEB18259C0E /* FTypedefs_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTypedefs_Private.h; path = Firebase/Database/Api/Private/FTypedefs_Private.h; sourceTree = ""; }; + 8D7BE7EA6367DA949086D526736A7DE0 /* GULReachabilityChecker+Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "GULReachabilityChecker+Internal.h"; path = "GoogleUtilities/Reachability/GULReachabilityChecker+Internal.h"; sourceTree = ""; }; + 8DDFE81B108DE6221D7C65724942FB0F /* FTupleFirebase.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleFirebase.m; path = Firebase/Database/Utilities/Tuples/FTupleFirebase.m; sourceTree = ""; }; + 8E6B71DD9A246127CC984BFD6DB3B66D /* FPruneForest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPruneForest.h; path = Firebase/Database/Persistence/FPruneForest.h; sourceTree = ""; }; + 8F2B4DAA5BB46220C05E787322CAE960 /* FirebaseMessaging-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FirebaseMessaging-umbrella.h"; sourceTree = ""; }; + 8F92B73F81BC9043DF09D74636383BD3 /* FIRTransactionResult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRTransactionResult.h; path = Firebase/Database/Public/FIRTransactionResult.h; sourceTree = ""; }; + 8FA1D93D5FF3EDB8C2273A0FC52FDD92 /* NSError+FIRMessaging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+FIRMessaging.h"; path = "Firebase/Messaging/NSError+FIRMessaging.h"; sourceTree = ""; }; + 90299D1FF6A39A99EC23E75E3780825A /* Pods-My MindUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-My MindUITests-acknowledgements.plist"; sourceTree = ""; }; + 904EFB6F9F30701EA342E10A83813F45 /* FIRStorageTaskSnapshot.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageTaskSnapshot.m; path = Firebase/Storage/FIRStorageTaskSnapshot.m; sourceTree = ""; }; + 90547EAE2B940B2E499C30B4B93D1996 /* FIRGoogleAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGoogleAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/Google/FIRGoogleAuthProvider.m; sourceTree = ""; }; + 909BF2B1ECC1C9990B47F744DBFE4353 /* FIRVerifyClientResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyClientResponse.h; path = Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.h; sourceTree = ""; }; + 90CAF6C078AC9FA0DDDF5AF785F595F4 /* FIRMessagingContextManagerService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingContextManagerService.h; path = Firebase/Messaging/FIRMessagingContextManagerService.h; sourceTree = ""; }; + 919BAE70A809B028A03EE6536029F65C /* FSRWebSocket.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSRWebSocket.h; path = Firebase/Database/third_party/SocketRocket/FSRWebSocket.h; sourceTree = ""; }; + 9213B9E77E41B0F09DE4A6DEF4605354 /* FIRStorageMetadata_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageMetadata_Private.h; path = Firebase/Storage/Private/FIRStorageMetadata_Private.h; sourceTree = ""; }; + 92DCCD218678B124254F507D53D566A5 /* FIRMessagingSyncMessageManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingSyncMessageManager.m; path = Firebase/Messaging/FIRMessagingSyncMessageManager.m; sourceTree = ""; }; + 935886C7F3E7579A7743B85BFAB68601 /* version_edit.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = version_edit.cc; path = db/version_edit.cc; sourceTree = ""; }; + 938DFBB9348CD99AFF254CF39CF17698 /* GULAppDelegateSwizzler.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULAppDelegateSwizzler.m; path = GoogleUtilities/AppDelegateSwizzler/GULAppDelegateSwizzler.m; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 93B79A48B8E85E3CEFE8C0D22E6F043F /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRootObject_PackagePrivate.h; path = objectivec/GPBRootObject_PackagePrivate.h; sourceTree = ""; }; + 93FE8C81279E09B8344D4D4F5873DEA8 /* thread_annotations.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = thread_annotations.h; path = port/thread_annotations.h; sourceTree = ""; }; + 94934014090548D4B93291C3A35A43BA /* version_set.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = version_set.cc; path = db/version_set.cc; sourceTree = ""; }; + 949FB977FA39EFF38D2F6B5508DF4AAF /* GPBWireFormat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBWireFormat.m; path = objectivec/GPBWireFormat.m; sourceTree = ""; }; + 94CB3AC364A3701DC592D22BDF8D4D64 /* FPersistenceManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPersistenceManager.h; path = Firebase/Database/Persistence/FPersistenceManager.h; sourceTree = ""; }; + 951C9C763F8BC13991737A8CD8FFF4AA /* FTupleRemovedQueriesEvents.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleRemovedQueriesEvents.m; path = Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.m; sourceTree = ""; }; + 95334361346B957D96FDAF00D5ACED6C /* FIRAuthErrors.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthErrors.h; path = Firebase/Auth/Source/Public/FIRAuthErrors.h; sourceTree = ""; }; + 95AAEB80477A015CAFD91C1AB9C14DA7 /* FIRGoogleAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGoogleAuthProvider.h; path = Firebase/Auth/Source/Public/FIRGoogleAuthProvider.h; sourceTree = ""; }; + 95C32177E2BED1782D2001DFA1FF0550 /* Pods-My MindTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-My MindTests-umbrella.h"; sourceTree = ""; }; + 95C84D68BD7EE91EDBA35DD0F59B13E2 /* GPBUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUtilities.m; path = objectivec/GPBUtilities.m; sourceTree = ""; }; + 95F2B1C34657348ECD42CC43E037DC68 /* FWebSocketConnection.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FWebSocketConnection.m; path = Firebase/Database/Realtime/FWebSocketConnection.m; sourceTree = ""; }; + 968C73940E1B097EF26967FA1146655A /* Timestamp.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Timestamp.pbobjc.m; path = objectivec/google/protobuf/Timestamp.pbobjc.m; sourceTree = ""; }; + 976DAE361FF6DA77BD3EF2CEB5B24754 /* format.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = format.cc; path = table/format.cc; sourceTree = ""; }; + 977804E7E131595293C9F752303CEC88 /* FWriteTree.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FWriteTree.h; path = Firebase/Database/Core/FWriteTree.h; sourceTree = ""; }; + 999ADEBF7B61A4065079C381CE6B7DE2 /* FTransformedEnumerator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTransformedEnumerator.h; path = Firebase/Database/FTransformedEnumerator.h; sourceTree = ""; }; + 99AC8DEBC31A6F60675A164487CD70F0 /* FIRAuthInternalErrors.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthInternalErrors.h; path = Firebase/Auth/Source/FIRAuthInternalErrors.h; sourceTree = ""; }; + 9A0C73503D3C9E121AEAD3E5D9965CB2 /* FCompoundWrite.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCompoundWrite.h; path = Firebase/Database/Snapshot/FCompoundWrite.h; sourceTree = ""; }; + 9A3FD15082F1A9ABE77ED609F0DFF1CB /* GPBUnknownField.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUnknownField.m; path = objectivec/GPBUnknownField.m; sourceTree = ""; }; + 9A41AF52719C366C4E6C2ADA6A8368CD /* GULNetwork.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULNetwork.m; path = GoogleUtilities/Network/GULNetwork.m; sourceTree = ""; }; + 9A425C87553240C22CA6ECCE49E65196 /* GULSwizzler.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULSwizzler.h; path = GoogleUtilities/MethodSwizzler/Private/GULSwizzler.h; sourceTree = ""; }; + 9A55D1EDA7B8213E6AEBB17AE65D2954 /* FIndex.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIndex.h; path = Firebase/Database/FIndex.h; sourceTree = ""; }; + 9A73AA5071EC8EB467C178B670E2D98D /* FIRSetAccountInfoRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSetAccountInfoRequest.m; path = Firebase/Auth/Source/RPCs/FIRSetAccountInfoRequest.m; sourceTree = ""; }; + 9AEDC13798C85C59C79C212EB9A65441 /* GPBWellKnownTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBWellKnownTypes.h; path = objectivec/GPBWellKnownTypes.h; sourceTree = ""; }; + 9BB01893708828A80056288891EE9E01 /* comparator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = comparator.h; path = include/leveldb/comparator.h; sourceTree = ""; }; + 9BF758753C1447148E55B242D5A8D189 /* GTMSessionFetcher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GTMSessionFetcher.framework; path = GTMSessionFetcher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9BFA0AB7799DA0A5FF85F62324964A2F /* FIRMessagingTopicOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingTopicOperation.m; path = Firebase/Messaging/FIRMessagingTopicOperation.m; sourceTree = ""; }; + 9C5043AB5D8305D0A639BECC966F573B /* FIRAuthDefaultUIDelegate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthDefaultUIDelegate.h; path = Firebase/Auth/Source/FIRAuthDefaultUIDelegate.h; sourceTree = ""; }; + 9D1DF1BF918CF6CEECA759D75788A242 /* FIRMessagingRegistrar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingRegistrar.h; path = Firebase/Messaging/FIRMessagingRegistrar.h; sourceTree = ""; }; + 9D6AD1B68D19CD2237E034D672CD3455 /* FView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FView.h; path = Firebase/Database/Core/View/FView.h; sourceTree = ""; }; + 9DBBB76901A980386DB2BECA4667AA5D /* FIRTwitterAuthProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRTwitterAuthProvider.h; path = Firebase/Auth/Source/Public/FIRTwitterAuthProvider.h; sourceTree = ""; }; + 9DBFB549CA0840AFD4B56E933019DF0A /* GULAppDelegateSwizzler_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULAppDelegateSwizzler_Private.h; path = GoogleUtilities/AppDelegateSwizzler/Internal/GULAppDelegateSwizzler_Private.h; sourceTree = ""; }; + 9DEB6F89764B79942EF4FF1368A9F6C8 /* FirebaseAuthVersion.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FirebaseAuthVersion.m; path = Firebase/Auth/Source/FirebaseAuthVersion.m; sourceTree = ""; }; + 9E06E73DF47291251ABD36E38BBA14B3 /* mutexlock.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = mutexlock.h; path = util/mutexlock.h; sourceTree = ""; }; + 9E31C3BDBFCEDEA18A1165D42EB6C7D4 /* FormDescriptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormDescriptor.swift; path = SwiftForms/descriptors/FormDescriptor.swift; sourceTree = ""; }; + 9E3E1944E3D50CC93173226B11C47ACC /* FIRMessagingPacketQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingPacketQueue.m; path = Firebase/Messaging/FIRMessagingPacketQueue.m; sourceTree = ""; }; + 9E84074B8CAC11CFC16E8F61FCDA55D0 /* FIndexedFilter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIndexedFilter.h; path = Firebase/Database/Core/View/Filter/FIndexedFilter.h; sourceTree = ""; }; + 9EE4F1D9B84C172C41E721B213F1707A /* GPBExtensionInternals.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBExtensionInternals.h; path = objectivec/GPBExtensionInternals.h; sourceTree = ""; }; + 9F156EFA0C6D1FF858F72E0773123B1F /* FIRDataSnapshot_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDataSnapshot_Private.h; path = Firebase/Database/Api/Private/FIRDataSnapshot_Private.h; sourceTree = ""; }; + 9F79D0ADD782AC78C79D540D0AB8B9EB /* SourceContext.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SourceContext.pbobjc.m; path = objectivec/google/protobuf/SourceContext.pbobjc.m; sourceTree = ""; }; + 9F8AF4D22A979411839BEBC0704E14EC /* FirebaseInstanceID.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseInstanceID.framework; path = Frameworks/FirebaseInstanceID.framework; sourceTree = ""; }; + 9FBD462DDA28EDB862ADCA7FCC50527D /* FIRMessagingCheckinService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingCheckinService.m; path = Firebase/Messaging/FIRMessagingCheckinService.m; sourceTree = ""; }; + A04D5EAB5D26B05C5CD5EED00FE954F5 /* FSnapshotUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSnapshotUtilities.m; path = Firebase/Database/Snapshot/FSnapshotUtilities.m; sourceTree = ""; }; + A08220A6CDB071FCB4B1F7EC1186D5A5 /* FIRMessagingConstants.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingConstants.m; path = Firebase/Messaging/FIRMessagingConstants.m; sourceTree = ""; }; + A096BEDB7EDE65D27A114DBD7937A0BD /* GPBDescriptor_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDescriptor_PackagePrivate.h; path = objectivec/GPBDescriptor_PackagePrivate.h; sourceTree = ""; }; + A0FC5CBCA095CB6ADDF78AB6763964C3 /* status.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = status.h; path = include/leveldb/status.h; sourceTree = ""; }; + A1136B2404BFAF4882B76A1FB3876A79 /* Pods-My Mind-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-My Mind-acknowledgements.markdown"; sourceTree = ""; }; + A1B86C1FEFEAA44BF8471DF6A3B328BB /* FIRErrors.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRErrors.h; path = Firebase/Core/Private/FIRErrors.h; sourceTree = ""; }; + A1D37659A08CA55180F3AA24ED62C072 /* FIRAuth.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuth.m; path = Firebase/Auth/Source/FIRAuth.m; sourceTree = ""; }; + A28ABD321652444E5617923C7C375319 /* repair.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = repair.cc; path = db/repair.cc; sourceTree = ""; }; + A3010B8604A66F46C262E7C7847DADA3 /* FIRVerifyPasswordRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyPasswordRequest.m; path = Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.m; sourceTree = ""; }; + A31F7EB02525A5A5990CCF17AFCBEEDF /* FIRMessagingDelayedMessageQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingDelayedMessageQueue.h; path = Firebase/Messaging/FIRMessagingDelayedMessageQueue.h; sourceTree = ""; }; + A338397206C34CAF5CBB48E4D05DCD6D /* GPBWireFormat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBWireFormat.h; path = objectivec/GPBWireFormat.h; sourceTree = ""; }; + A383681CA86AE1040605A9AA1AE4E78D /* FIRNoopAuthTokenProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRNoopAuthTokenProvider.m; path = Firebase/Database/Login/FIRNoopAuthTokenProvider.m; sourceTree = ""; }; + A386A5F444120EBDA11F9BF76D51E331 /* FIRLogger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRLogger.h; path = Firebase/Core/Private/FIRLogger.h; sourceTree = ""; }; + A3A6CAC7709D278E80B3D80F187CEE79 /* FIRServerValue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRServerValue.m; path = Firebase/Database/Api/FIRServerValue.m; sourceTree = ""; }; + A3AF2B4F082D56E9F3B5C36EC9CA1ACD /* FUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FUtilities.m; path = Firebase/Database/Utilities/FUtilities.m; sourceTree = ""; }; + A3BF85E75A6FABE9D104B8E0255D2E0F /* filter_policy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = filter_policy.h; path = include/leveldb/filter_policy.h; sourceTree = ""; }; + A47C3AB0A9B76782489F5945F55343BB /* FTupleRemovedQueriesEvents.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleRemovedQueriesEvents.h; path = Firebase/Database/Utilities/Tuples/FTupleRemovedQueriesEvents.h; sourceTree = ""; }; + A485EC28C2BCF093F8C31F8A206D38E6 /* FIRAppAssociationRegistration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAppAssociationRegistration.h; path = Firebase/Core/Private/FIRAppAssociationRegistration.h; sourceTree = ""; }; + A4A441974FF8146A16F5356A074A3BBA /* GULUserDefaults.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULUserDefaults.h; path = GoogleUtilities/UserDefaults/Private/GULUserDefaults.h; sourceTree = ""; }; + A54BE9E44DCB1F38C08F562BD72CAE85 /* GtalkCore.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GtalkCore.pbobjc.h; path = Firebase/Messaging/Protos/GtalkCore.pbobjc.h; sourceTree = ""; }; + A5C0809DAC4098C4DCA572A7499E9116 /* db_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = db_impl.h; path = db/db_impl.h; sourceTree = ""; }; + A5D054DB817811112B3951BAA5516B85 /* FormSelectorCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSelectorCell.swift; path = SwiftForms/cells/FormSelectorCell.swift; sourceTree = ""; }; + A5F1DF0DE04325F03FFC21877D9F2DD6 /* FIRMessaging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessaging.h; path = Firebase/Messaging/Public/FIRMessaging.h; sourceTree = ""; }; + A60901D38929C0E04817F7B345B30999 /* db_impl.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = db_impl.cc; path = db/db_impl.cc; sourceTree = ""; }; + A6181FF5A800FCCC67FBFE0B7BF53D27 /* FIRMessagingDefines.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingDefines.h; path = Firebase/Messaging/FIRMessagingDefines.h; sourceTree = ""; }; + A69039FCDFBA2D22C1736491CC27B108 /* FChildChangeAccumulator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FChildChangeAccumulator.h; path = Firebase/Database/Core/View/Filter/FChildChangeAccumulator.h; sourceTree = ""; }; + A6CBDE68609CD2D3C103DAA433F2C60F /* log_reader.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = log_reader.cc; path = db/log_reader.cc; sourceTree = ""; }; + A70BEAFA51CAAA238419AD526C3A2A20 /* GULNetworkConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULNetworkConstants.h; path = GoogleUtilities/Network/Private/GULNetworkConstants.h; sourceTree = ""; }; + A75B42E8622D5215381457494A951D5F /* block_builder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = block_builder.h; path = table/block_builder.h; sourceTree = ""; }; + A7AA5196BC9D9746048C578C41EB5941 /* merger.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = merger.cc; path = table/merger.cc; sourceTree = ""; }; + A7C4DF6F92826595F2A84D72365B5505 /* FIRMessagingPersistentSyncMessage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingPersistentSyncMessage.h; path = Firebase/Messaging/FIRMessagingPersistentSyncMessage.h; sourceTree = ""; }; + A7E45C4CB7E9A1B7DC4448F0725D4921 /* FIROptions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIROptions.h; path = Firebase/Core/Public/FIROptions.h; sourceTree = ""; }; + A7F1204A860C29B4A4BAEF12AC3CA224 /* FIRActionCodeSettings.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRActionCodeSettings.m; path = Firebase/Auth/Source/FIRActionCodeSettings.m; sourceTree = ""; }; + A80F78145127A307E9C1096BA11DA24F /* GPBDescriptor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBDescriptor.m; path = objectivec/GPBDescriptor.m; sourceTree = ""; }; + A82B173D007A576E78AC1896EC794E94 /* FIRGitHubAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGitHubAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthCredential.m; sourceTree = ""; }; + A8679585BD7F5289E37359EA461A0848 /* FWriteRecord.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FWriteRecord.h; path = Firebase/Database/Core/FWriteRecord.h; sourceTree = ""; }; + A88F71BC1A9F943C034BCC009810AD64 /* Type.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Type.pbobjc.h; path = objectivec/google/protobuf/Type.pbobjc.h; sourceTree = ""; }; + A899DB3CC1F64B5D6F8B8877B8D5B7D2 /* SwiftForms-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftForms-umbrella.h"; sourceTree = ""; }; + A950F6251ACB2BC29B9B91DFD2DE3CFD /* FIRMessagingRmq2PersistentStore.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingRmq2PersistentStore.h; path = Firebase/Messaging/FIRMessagingRmq2PersistentStore.h; sourceTree = ""; }; + A971443D94F15814ACF2372DEC544C9E /* FIRAuthAPNSTokenManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthAPNSTokenManager.m; path = Firebase/Auth/Source/FIRAuthAPNSTokenManager.m; sourceTree = ""; }; + A99F776AB4854965623E2157BE844140 /* FIRDataSnapshot.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDataSnapshot.h; path = Firebase/Database/Public/FIRDataSnapshot.h; sourceTree = ""; }; + A9A58585F2C08E9463E0F2DC3EC61173 /* pb_encode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = pb_encode.h; sourceTree = ""; }; + A9CFB4A25C1A9163B43C9569A6776AF5 /* GTMSessionFetcher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-umbrella.h"; sourceTree = ""; }; + A9D4C247886677E0DE4667C1879C2A92 /* FirebaseAuthVersion.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseAuthVersion.h; path = Firebase/Auth/Source/Public/FirebaseAuthVersion.h; sourceTree = ""; }; + AA2224EC04EF8A8CF027796F264D4AF6 /* SwiftForms.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftForms.modulemap; sourceTree = ""; }; + AA4C3D674727250939C11F0687171F23 /* FIRSignInWithGameCenterResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSignInWithGameCenterResponse.h; path = Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterResponse.h; sourceTree = ""; }; + AA51B0829287BFC68D2DA3B4440E6AF6 /* FListenProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FListenProvider.h; path = Firebase/Database/Core/FListenProvider.h; sourceTree = ""; }; + AA832C3FE6C7B3EC74C14089A07B2D7D /* FIRApp.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRApp.h; path = Firebase/Core/Public/FIRApp.h; sourceTree = ""; }; + AA8F8C049192849495466614A330F2EF /* FIRAuthAppDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAppDelegateProxy.h; path = Firebase/Auth/Source/FIRAuthAppDelegateProxy.h; sourceTree = ""; }; + AAD8583A56D06F8B53175D035AF9D864 /* pb_common.c */ = {isa = PBXFileReference; includeInIndex = 1; path = pb_common.c; sourceTree = ""; }; + AB16085037ACA0EF2DB981B3C7993C4E /* table_cache.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = table_cache.cc; path = db/table_cache.cc; sourceTree = ""; }; + ABED8087C7A90B3FD277BAE0632749F8 /* FormSliderCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormSliderCell.swift; path = SwiftForms/cells/FormSliderCell.swift; sourceTree = ""; }; + AC05B3DB4EDE20A5FD7CE64075AB866E /* FIRAuthRPCRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthRPCRequest.h; path = Firebase/Auth/Source/RPCs/FIRAuthRPCRequest.h; sourceTree = ""; }; + AC29AD359CB65A16BC601242EC2BC78F /* Pods-My MindTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My MindTests.debug.xcconfig"; sourceTree = ""; }; + AC38D0BF1D124FC816CFFBC68841C7F7 /* FAtomicNumber.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FAtomicNumber.m; path = Firebase/Database/Utilities/FAtomicNumber.m; sourceTree = ""; }; + AC39528D9EF5C627E843B230297D8360 /* FIRStorageReference.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageReference.m; path = Firebase/Storage/FIRStorageReference.m; sourceTree = ""; }; + AC67F7B153F19CD9D494C50213CC1B3E /* log_writer.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = log_writer.cc; path = db/log_writer.cc; sourceTree = ""; }; + ACA1566B042023738C7E7216DCC158C5 /* leveldb-library.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "leveldb-library.modulemap"; sourceTree = ""; }; + ACB3D17DA57ABABF8DEFB9172C36AF43 /* GULAppDelegateSwizzler.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULAppDelegateSwizzler.h; path = GoogleUtilities/AppDelegateSwizzler/Private/GULAppDelegateSwizzler.h; sourceTree = ""; }; + AD06A572C80510926057D48A1FF3CFC4 /* FIRAuthDataResult_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthDataResult_Internal.h; path = Firebase/Auth/Source/FIRAuthDataResult_Internal.h; sourceTree = ""; }; + AD7412CA4B83C16AF5D10344627F2226 /* FIROptionsInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIROptionsInternal.h; path = Firebase/Core/Private/FIROptionsInternal.h; sourceTree = ""; }; + ADFB0C91FF0A24C4F22AC190030E4908 /* FIRMessagingPendingTopicsList.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingPendingTopicsList.h; path = Firebase/Messaging/FIRMessagingPendingTopicsList.h; sourceTree = ""; }; + AE210630843BC4F35C085C2F50BD731E /* FStringUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FStringUtilities.m; path = Firebase/Database/Utilities/FStringUtilities.m; sourceTree = ""; }; + AE61849A6A393E9FC1EB0A2778E14C73 /* GoogleUtilities-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleUtilities-umbrella.h"; sourceTree = ""; }; + AE72ED507BFAB70E74F0185212CFA468 /* FOperationSource.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FOperationSource.h; path = Firebase/Database/Core/Operation/FOperationSource.h; sourceTree = ""; }; + AE8A0C83E51D1224B0CFB2B9112CD50F /* NSData+SRB64Additions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+SRB64Additions.m"; path = "Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.m"; sourceTree = ""; }; + AECBA6A0BBA8C75D909C3BBA5A05C859 /* FormButtonCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormButtonCell.swift; path = SwiftForms/cells/FormButtonCell.swift; sourceTree = ""; }; + AEDB6F9859D5D740703FECC548FF4DB1 /* Duration.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Duration.pbobjc.h; path = objectivec/google/protobuf/Duration.pbobjc.h; sourceTree = ""; }; + AF170DAA3F83CF4EBDF6F1339EF00018 /* FIRVerifyPhoneNumberRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyPhoneNumberRequest.m; path = Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberRequest.m; sourceTree = ""; }; + AFB0AC6451A7F1334E2461C600716593 /* FIRSetAccountInfoResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSetAccountInfoResponse.h; path = Firebase/Auth/Source/RPCs/FIRSetAccountInfoResponse.h; sourceTree = ""; }; + AFD8CDB02D4D4C89C49C96F058E1B224 /* FEmptyNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FEmptyNode.m; path = Firebase/Database/Snapshot/FEmptyNode.m; sourceTree = ""; }; + AFF0724B2C7C2E8E26274EEB21F79C60 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B042774A378BD6A6A47CAF43D174D354 /* FirebaseCore.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FirebaseCore.xcconfig; sourceTree = ""; }; + B057F909F1A17282CBA960CE4A2237B2 /* FEventGenerator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEventGenerator.h; path = Firebase/Database/FEventGenerator.h; sourceTree = ""; }; + B0AD46A45553ED004551AE6C62A05B2C /* FIRConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRConfiguration.h; path = Firebase/Core/Public/FIRConfiguration.h; sourceTree = ""; }; + B0B5A5553CFB4456F7BC8E2B97CC0644 /* FIRRetryHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRRetryHelper.m; path = Firebase/Database/Core/Utilities/FIRRetryHelper.m; sourceTree = ""; }; + B17E60B74D249F60A7E8A809C20EFCBA /* FIRErrors.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRErrors.m; path = Firebase/Core/FIRErrors.m; sourceTree = ""; }; + B1E8384121EEC4BAB5A9C4A3B415D4E5 /* Pods-My MindUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-My MindUITests.modulemap"; sourceTree = ""; }; + B1FC0F5D6E265B194170509A9025EED7 /* FRangedFilter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FRangedFilter.m; path = Firebase/Database/FRangedFilter.m; sourceTree = ""; }; + B1FF1C0990CE6DF70B31DBC7140BE404 /* FIRRetryHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRRetryHelper.h; path = Firebase/Database/Core/Utilities/FIRRetryHelper.h; sourceTree = ""; }; + B2A3E3AFFA8F8C86271BA4D6C7F4C875 /* FIRDatabase.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDatabase.m; path = Firebase/Database/Api/FIRDatabase.m; sourceTree = ""; }; + B30A46EF299C9AE94179DFBE2C0A1583 /* FirebaseAnalytics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseAnalytics.framework; path = Frameworks/FirebaseAnalytics.framework; sourceTree = ""; }; + B323034EAD6CEDCD35A420C6F0EA58C4 /* FEventGenerator.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FEventGenerator.m; path = Firebase/Database/FEventGenerator.m; sourceTree = ""; }; + B3F673C51D33F552AA826578B448AF3C /* FClock.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FClock.m; path = Firebase/Database/FClock.m; sourceTree = ""; }; + B4288F3CD86EF1B904C5B60FF214940B /* Timestamp.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Timestamp.pbobjc.h; path = objectivec/google/protobuf/Timestamp.pbobjc.h; sourceTree = ""; }; + B462ABAEB07A7435FB7510B120702773 /* FConstants.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FConstants.m; path = Firebase/Database/Constants/FConstants.m; sourceTree = ""; }; + B48C76A23EF0571C6D82D31226FE2B77 /* FTupleSetIdPath.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleSetIdPath.m; path = Firebase/Database/Utilities/Tuples/FTupleSetIdPath.m; sourceTree = ""; }; + B4DCF5F9A05116C8E5BEB7E4672C77F0 /* FIREmailLinkSignInRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIREmailLinkSignInRequest.h; path = Firebase/Auth/Source/RPCs/FIREmailLinkSignInRequest.h; sourceTree = ""; }; + B50A16C7653FEFB535C922A6E394F409 /* comparator.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = comparator.cc; path = util/comparator.cc; sourceTree = ""; }; + B50EE45BEEE9696770C9F0E3526DABF0 /* FIRMessagingVersionUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingVersionUtilities.h; path = Firebase/Messaging/FIRMessagingVersionUtilities.h; sourceTree = ""; }; + B5A15BC3357E674F08C9999C7D329D3D /* FEventEmitter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEventEmitter.h; path = Firebase/Database/Utilities/FEventEmitter.h; sourceTree = ""; }; + B5C3F4B78DF3673687E6F9E9D5672781 /* FTupleObjects.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleObjects.h; path = Firebase/Database/Utilities/Tuples/FTupleObjects.h; sourceTree = ""; }; + B6032ED1761DE16D733B707DC6D72F5B /* GPBUnknownField.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownField.h; path = objectivec/GPBUnknownField.h; sourceTree = ""; }; + B60A88AD3A3288AB7892EBF19A5E3DD7 /* FIRMessagingSecureSocket.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingSecureSocket.m; path = Firebase/Messaging/FIRMessagingSecureSocket.m; sourceTree = ""; }; + B6553318BF52F3BEAC785032DE0A7878 /* FViewProcessorResult.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FViewProcessorResult.m; path = Firebase/Database/FViewProcessorResult.m; sourceTree = ""; }; + B662A5489E41A07B7B8124D85511A255 /* Pods_My_MindTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_My_MindTests.framework; path = "Pods-My MindTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + B6706057DE50E1D3EE4A4008BC96310A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B68C0AB6F0930895E952BF5A780C56D6 /* FIRVerifyCustomTokenResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyCustomTokenResponse.h; path = Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenResponse.h; sourceTree = ""; }; + B6C8EB92AE55113567DF336B2C0EA1AB /* FIRAuthWebViewController.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthWebViewController.m; path = Firebase/Auth/Source/FIRAuthWebViewController.m; sourceTree = ""; }; + B7090A47010657A1918B87BAE29D0A1E /* FIRMessagingPubSubRegistrar.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingPubSubRegistrar.m; path = Firebase/Messaging/FIRMessagingPubSubRegistrar.m; sourceTree = ""; }; + B71F9CA1A6DFC5C710C50B9AFA31CBAF /* iterator_wrapper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = iterator_wrapper.h; path = table/iterator_wrapper.h; sourceTree = ""; }; + B7365E12A17D8AEA411AFD1AE22C6647 /* FIRAdditionalUserInfo.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAdditionalUserInfo.h; path = Firebase/Auth/Source/Public/FIRAdditionalUserInfo.h; sourceTree = ""; }; + B84AB522D96FDBEF56178B4E103D0722 /* FIRMessagingTopicOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingTopicOperation.h; path = Firebase/Messaging/FIRMessagingTopicOperation.h; sourceTree = ""; }; + B8B02B5F674C3C2DB98EF004508CFCC3 /* GPBRootObject.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBRootObject.m; path = objectivec/GPBRootObject.m; sourceTree = ""; }; + B950CCF786F09E70D271B41775C47615 /* NSData+SRB64Additions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+SRB64Additions.h"; path = "Firebase/Database/third_party/SocketRocket/NSData+SRB64Additions.h"; sourceTree = ""; }; + B9962BD291505BFFBA34CC528C43DE1C /* SwiftForms-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftForms-prefix.pch"; sourceTree = ""; }; + B9B72DC800D477FEA2AC16E17CC60AE1 /* FIRDatabase_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabase_Private.h; path = Firebase/Database/Api/Private/FIRDatabase_Private.h; sourceTree = ""; }; + B9C0F3D003CEE3E5CBD1B6E5C94D1702 /* FirebaseMessaging.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FirebaseMessaging.xcconfig; sourceTree = ""; }; + BA3EDB47D8082026DB6188D3030E770B /* FIRAuthURLPresenter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthURLPresenter.m; path = Firebase/Auth/Source/FIRAuthURLPresenter.m; sourceTree = ""; }; + BB096EC76A1266B8C0F8E2ACC1A31ED2 /* GPBMessage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBMessage.h; path = objectivec/GPBMessage.h; sourceTree = ""; }; + BB147D332EB59A3C55AD8275F836ADCF /* Pods-My Mind-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My Mind-resources.sh"; sourceTree = ""; }; + BB4A6AB1B3EAD07AD843777C90166F83 /* FIRStorageUpdateMetadataTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageUpdateMetadataTask.h; path = Firebase/Storage/Private/FIRStorageUpdateMetadataTask.h; sourceTree = ""; }; + BB4A6F767E6E29DB9A1B3EE2B13EBFCD /* FirebaseStorage.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FirebaseStorage.modulemap; sourceTree = ""; }; + BBA75DF8FF00F58C0B862CFBFDE225AE /* filename.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = filename.h; path = db/filename.h; sourceTree = ""; }; + BC4A443A1DF1810B7A9803C462DADFEB /* FTypedefs.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTypedefs.h; path = Firebase/Database/Utilities/FTypedefs.h; sourceTree = ""; }; + BC4C2E22EF2E783BAC029A803B491668 /* FIRInteropEventNames.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRInteropEventNames.h; path = Interop/Analytics/Public/FIRInteropEventNames.h; sourceTree = ""; }; + BC564D3F08952BAF72AA3D8FA599A413 /* Empty.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Empty.pbobjc.h; path = objectivec/google/protobuf/Empty.pbobjc.h; sourceTree = ""; }; + BC6957CC5CFB8C0C21FB9630CB797E96 /* FIRGitHubAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGitHubAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/GitHub/FIRGitHubAuthProvider.m; sourceTree = ""; }; + BCA9949E729F8FA89A2FBA1FC41A08C4 /* FIRSecureTokenRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSecureTokenRequest.h; path = Firebase/Auth/Source/RPCs/FIRSecureTokenRequest.h; sourceTree = ""; }; + BCF80591D51DDED99DCFEB418DAF6C6D /* FIRResetPasswordRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRResetPasswordRequest.m; path = Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.m; sourceTree = ""; }; + BD4117C893A97D98EE31E12226EB41F9 /* FChildrenNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FChildrenNode.h; path = Firebase/Database/Snapshot/FChildrenNode.h; sourceTree = ""; }; + BD91CFB92703A5598BBF2CC6E38F9678 /* FSparseSnapshotTree.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSparseSnapshotTree.m; path = Firebase/Database/Core/FSparseSnapshotTree.m; sourceTree = ""; }; + BDA8D286B82FAEEDBA4BB4A834E41412 /* FSyncPoint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSyncPoint.h; path = Firebase/Database/Core/FSyncPoint.h; sourceTree = ""; }; + BDE06C7169B511B43A4220DCCA6B9012 /* NSDictionary+FIRMessaging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSDictionary+FIRMessaging.h"; path = "Firebase/Messaging/NSDictionary+FIRMessaging.h"; sourceTree = ""; }; + BE0B0BCBB4CAA4C8D82EF4D06A6D1CA9 /* FIRDatabaseComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseComponent.h; path = Firebase/Database/Api/FIRDatabaseComponent.h; sourceTree = ""; }; + BE0BCF2C1C9FD3078B1F5A3C3EE7C25A /* FIRMessagingConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingConstants.h; path = Firebase/Messaging/FIRMessagingConstants.h; sourceTree = ""; }; + BE58957B596510DF2E8953AC74AD5FE3 /* FMerge.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMerge.m; path = Firebase/Database/Core/Operation/FMerge.m; sourceTree = ""; }; + BE94296B133418A27910B00D5294FF16 /* GULLogger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULLogger.h; path = GoogleUtilities/Logger/Private/GULLogger.h; sourceTree = ""; }; + BF57C0F85A406C3D449F4E1AF68D0A9B /* FIRSendVerificationCodeResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSendVerificationCodeResponse.m; path = Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.m; sourceTree = ""; }; + BF633D289C9053169D2324C32B3F5AEE /* FIRStorage_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorage_Private.h; path = Firebase/Storage/Private/FIRStorage_Private.h; sourceTree = ""; }; + C0579785095D37C75777806A0548CD41 /* pb_common.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = pb_common.h; sourceTree = ""; }; + C08FC41A4A7E8D144554D360A843190E /* FirebaseDatabase-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FirebaseDatabase-umbrella.h"; sourceTree = ""; }; + C185A4DDD2586774727CB23BCBED0299 /* FIRSignInWithGameCenterRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSignInWithGameCenterRequest.m; path = Firebase/Auth/Source/RPCs/FIRSignInWithGameCenterRequest.m; sourceTree = ""; }; + C1A0FB94A0B45A747CBE8D23321B8BCD /* FIRAuthBackend.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthBackend.m; path = Firebase/Auth/Source/RPCs/FIRAuthBackend.m; sourceTree = ""; }; + C1D412970289721316660D54C69470C1 /* FIRAuthKeychain.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthKeychain.h; path = Firebase/Auth/Source/FIRAuthKeychain.h; sourceTree = ""; }; + C1FAF04CD4B2CBB223911ECA4F6BD75B /* FQueryParams.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FQueryParams.m; path = Firebase/Database/Core/FQueryParams.m; sourceTree = ""; }; + C22FFA05A12B4D3BDF4C4307840FD4E6 /* nanopb.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = nanopb.framework; path = nanopb.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C24FC54E82667CD883433C507452C248 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/MobileCoreServices.framework; sourceTree = DEVELOPER_DIR; }; + C2A917B7B3143CB35B45491393EFE099 /* FIRSignUpNewUserRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRSignUpNewUserRequest.m; path = Firebase/Auth/Source/RPCs/FIRSignUpNewUserRequest.m; sourceTree = ""; }; + C2B6EFFEA69D94C962C92D480A5F7B5D /* FIRGameCenterAuthCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGameCenterAuthCredential.m; path = Firebase/Auth/Source/AuthProviders/GameCenter/FIRGameCenterAuthCredential.m; sourceTree = ""; }; + C2E41B74D9C1720A05CE0AB191067AFE /* builder.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = builder.cc; path = db/builder.cc; sourceTree = ""; }; + C2FF98AE061B3CCF1FD81B6324D7D16B /* FIRMessagingPacketQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingPacketQueue.h; path = Firebase/Messaging/FIRMessagingPacketQueue.h; sourceTree = ""; }; + C3276A2BFA726F605D0020C6E3F30F22 /* FSyncTree.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSyncTree.h; path = Firebase/Database/Core/FSyncTree.h; sourceTree = ""; }; + C3FFC4ACEC5591F801B1902AB763DA62 /* GPBDescriptor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDescriptor.h; path = objectivec/GPBDescriptor.h; sourceTree = ""; }; + C4B963BE88DF9BAD70BB2577285B94FA /* FirebaseAuth-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FirebaseAuth-umbrella.h"; sourceTree = ""; }; + C52EC904B0F3150B87E3EA668BEAD512 /* FTupleObjectNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleObjectNode.m; path = Firebase/Database/Utilities/Tuples/FTupleObjectNode.m; sourceTree = ""; }; + C5578903E5AF1A9CA32A01FFF0D569CA /* FIRAuthUserDefaultsStorage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthUserDefaultsStorage.h; path = Firebase/Auth/Source/FIRAuthUserDefaultsStorage.h; sourceTree = ""; }; + C5D45A7FC3F4035103ED107B1F6127F3 /* FIRGetOOBConfirmationCodeResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRGetOOBConfirmationCodeResponse.m; path = Firebase/Auth/Source/RPCs/FIRGetOOBConfirmationCodeResponse.m; sourceTree = ""; }; + C5D5E994D8F0EFDF52C43C5BA09B95A2 /* GPBExtensionInternals.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionInternals.m; path = objectivec/GPBExtensionInternals.m; sourceTree = ""; }; + C647DA2D0CD5FB0B7BF0E68188DC9A02 /* FValueEventRegistration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FValueEventRegistration.m; path = Firebase/Database/Core/View/FValueEventRegistration.m; sourceTree = ""; }; + C6D1B26A950547F59D7E738E2C779092 /* FIRUserInfo.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUserInfo.h; path = Firebase/Auth/Source/Public/FIRUserInfo.h; sourceTree = ""; }; + C6EA16B802C4C8FC4C6BE6B9A2CBCCC5 /* FPendingPut.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPendingPut.h; path = Firebase/Database/Persistence/FPendingPut.h; sourceTree = ""; }; + C7664078AAB63061F0485623401B4036 /* FIRAuthUserDefaultsStorage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthUserDefaultsStorage.m; path = Firebase/Auth/Source/FIRAuthUserDefaultsStorage.m; sourceTree = ""; }; + C7B4E1AC707BFEC7671666CC0530312A /* FIRStorageUtils.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageUtils.h; path = Firebase/Storage/Private/FIRStorageUtils.h; sourceTree = ""; }; + C7CD4E9BC7D2C83FF01A0328A280F5FA /* Pods-My Mind-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-My Mind-acknowledgements.plist"; sourceTree = ""; }; + C867367352BE84E57F50CB0AD6199922 /* FIRComponentType.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRComponentType.m; path = Firebase/Core/FIRComponentType.m; sourceTree = ""; }; + C892A85A358C20C1C99EDA725170E12E /* FIRAuthAppCredential.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthAppCredential.m; path = Firebase/Auth/Source/FIRAuthAppCredential.m; sourceTree = ""; }; + C8C7086328E78F3238E42C4FFFF6C84D /* FOperationSource.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FOperationSource.m; path = Firebase/Database/Core/Operation/FOperationSource.m; sourceTree = ""; }; + C9ADC47D30FF0AAF24724A272E5DEBE8 /* FLLRBEmptyNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLLRBEmptyNode.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FLLRBEmptyNode.h; sourceTree = ""; }; + C9AEE3D9A205088F3D2E0972D99DE8D7 /* FIRMessagingRemoteNotificationsProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingRemoteNotificationsProxy.m; path = Firebase/Messaging/FIRMessagingRemoteNotificationsProxy.m; sourceTree = ""; }; + CA78AE84FFDE46D92C15B239A36D72EC /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + CADBF9EAB8E6375218D133DE8EC36296 /* FirebaseAuth.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FirebaseAuth.framework; path = FirebaseAuth.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CB57BCF1E73C7B8A4B2CAE6F512FB8A5 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + CB5E5EDC823A0512816F5F6A8AAE7BCD /* FIRIdentityToolkitRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRIdentityToolkitRequest.h; path = Firebase/Auth/Source/RPCs/FIRIdentityToolkitRequest.h; sourceTree = ""; }; + CB6099DEF2E3EDF5BDE646A402A7223C /* FIRAuthAPNSTokenManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthAPNSTokenManager.h; path = Firebase/Auth/Source/FIRAuthAPNSTokenManager.h; sourceTree = ""; }; + CB75ED76F6A5CB316ABCE459B35449B1 /* FOverwrite.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FOverwrite.h; path = Firebase/Database/Core/Operation/FOverwrite.h; sourceTree = ""; }; + CB84AAF13B2D3F5576311B23B58E94EF /* FSnapshotUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FSnapshotUtilities.h; path = Firebase/Database/Snapshot/FSnapshotUtilities.h; sourceTree = ""; }; + CBF3C805C4BA2351F7663FC5BBB51446 /* FTupleOnDisconnect.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleOnDisconnect.m; path = Firebase/Database/Utilities/Tuples/FTupleOnDisconnect.m; sourceTree = ""; }; + CC590D92037B35FC414FF8BCEF4C66B9 /* FAckUserWrite.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FAckUserWrite.h; path = Firebase/Database/Core/Operation/FAckUserWrite.h; sourceTree = ""; }; + CC6154B7CE684A1970FFE54F20E8392F /* table.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = table.h; path = include/leveldb/table.h; sourceTree = ""; }; + CC6ADBF7520BE4C24E99069E832C1E44 /* Any.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = objectivec/google/protobuf/Any.pbobjc.m; sourceTree = ""; }; + CCD534072CDFAE76358EC05074E7A1FD /* FIRMessagingCodedInputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingCodedInputStream.m; path = Firebase/Messaging/FIRMessagingCodedInputStream.m; sourceTree = ""; }; + CCF7C96D9FF6B74D1BB5DD455A95B971 /* FImmutableSortedSet.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FImmutableSortedSet.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FImmutableSortedSet.h; sourceTree = ""; }; + CD10E05003650C16485F6681FFCFB453 /* FIRAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthCredential.h; path = Firebase/Auth/Source/Public/FIRAuthCredential.h; sourceTree = ""; }; + CD292B336F5C12C67D9382555FB39F84 /* FIRStorageDownloadTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageDownloadTask.h; path = Firebase/Storage/Public/FIRStorageDownloadTask.h; sourceTree = ""; }; + CD321F3BDAC9E5C193BB7538DB15F36B /* FIRUser_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRUser_Internal.h; path = Firebase/Auth/Source/FIRUser_Internal.h; sourceTree = ""; }; + CD5261ED7894617F948B8217A7A98098 /* FIRMessagingConnection.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingConnection.m; path = Firebase/Messaging/FIRMessagingConnection.m; sourceTree = ""; }; + CD56393A1C061A90D9EADCAE84B22F19 /* FLeafNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FLeafNode.h; path = Firebase/Database/Snapshot/FLeafNode.h; sourceTree = ""; }; + CDDE3270485F6BA958F0E5A5253C05C9 /* FIRStorageReference.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageReference.h; path = Firebase/Storage/Public/FIRStorageReference.h; sourceTree = ""; }; + CDF371265A9A6D8E73196A94E4D28CC6 /* FIRMessagingPersistentSyncMessage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingPersistentSyncMessage.m; path = Firebase/Messaging/FIRMessagingPersistentSyncMessage.m; sourceTree = ""; }; + CE0A99214530B0FAF71E7F69ADE4F9B5 /* FIRStorageErrors.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageErrors.m; path = Firebase/Storage/FIRStorageErrors.m; sourceTree = ""; }; + CE4660BA7D6E8CFDAD16757199161DB4 /* FIRFacebookAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRFacebookAuthCredential.h; path = Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthCredential.h; sourceTree = ""; }; + CE58A9D71591B0BDA8F839EF6D8E13F8 /* FIRStorageTask_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageTask_Private.h; path = Firebase/Storage/Private/FIRStorageTask_Private.h; sourceTree = ""; }; + CEA0478245F572D019A39A44DE52A3A4 /* FIRStorageMetadata.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageMetadata.h; path = Firebase/Storage/Public/FIRStorageMetadata.h; sourceTree = ""; }; + CECD1A2BFBF0E479DFBB774F092537C4 /* FTree.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTree.h; path = Firebase/Database/Core/Utilities/FTree.h; sourceTree = ""; }; + CEE1E52025454E30EC0E6663FF8E2467 /* FUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FUtilities.h; path = Firebase/Database/Utilities/FUtilities.h; sourceTree = ""; }; + CF39E63BAD15EE14C47C6750CC780862 /* FIRPhoneAuthCredential.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRPhoneAuthCredential.h; path = Firebase/Auth/Source/Public/FIRPhoneAuthCredential.h; sourceTree = ""; }; + CF3A590F142F7E04CFCCE40F7894F3ED /* FViewCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FViewCache.m; path = Firebase/Database/Core/View/FViewCache.m; sourceTree = ""; }; + CF6C4A834EC0A2207726AB45C8E5DF0E /* FIRAuthAppCredentialManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthAppCredentialManager.m; path = Firebase/Auth/Source/FIRAuthAppCredentialManager.m; sourceTree = ""; }; + CFA8257B2CAC756753E55E997D0374B3 /* FIRAdditionalUserInfo.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAdditionalUserInfo.m; path = Firebase/Auth/Source/FIRAdditionalUserInfo.m; sourceTree = ""; }; + D11762CCA4EA49A55F93AF08FB928633 /* FIRAuthAPNSToken.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthAPNSToken.m; path = Firebase/Auth/Source/FIRAuthAPNSToken.m; sourceTree = ""; }; + D17AC93D8B3ED45BD0F5116710A62D29 /* arena.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = arena.h; path = util/arena.h; sourceTree = ""; }; + D18CEA84295910BAB47D481FA1692F0D /* FIRVerifyClientResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRVerifyClientResponse.m; path = Firebase/Auth/Source/RPCs/FIRVerifyClientResponse.m; sourceTree = ""; }; + D1B6EF52D08A5CB66B19509A9FA26392 /* FirebaseDatabase.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FirebaseDatabase.framework; path = FirebaseDatabase.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D1BCA22721EC82476AD1ECBFFC47FDE4 /* FNamedNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FNamedNode.m; path = Firebase/Database/FNamedNode.m; sourceTree = ""; }; + D1D35C7CEFB980F5F15231F61E072857 /* FIRActionCodeSettings.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRActionCodeSettings.h; path = Firebase/Auth/Source/Public/FIRActionCodeSettings.h; sourceTree = ""; }; + D1D80F314DC9DFCAF4DF1930A7FF0432 /* FirebaseDatabase.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FirebaseDatabase.xcconfig; sourceTree = ""; }; + D1FBF0A9EE42AF399B2B94CD6809F898 /* FLeafNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FLeafNode.m; path = Firebase/Database/Snapshot/FLeafNode.m; sourceTree = ""; }; + D231D1C9A6DC029C392DA35062159AD0 /* FIRAuthBackend.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthBackend.h; path = Firebase/Auth/Source/RPCs/FIRAuthBackend.h; sourceTree = ""; }; + D32F70B25D7F29D35CFA300BD1BAAE9E /* Protobuf.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Protobuf.xcconfig; sourceTree = ""; }; + D37225295D40A9C051F75D0BC81405E1 /* FIRVerifyCustomTokenRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyCustomTokenRequest.h; path = Firebase/Auth/Source/RPCs/FIRVerifyCustomTokenRequest.h; sourceTree = ""; }; + D3BF55E62435B01E8C350625673407B2 /* GULMutableDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULMutableDictionary.m; path = GoogleUtilities/Network/GULMutableDictionary.m; sourceTree = ""; }; + D3FCE7821A5559920675860218C3E7B6 /* FIRUserInfoImpl.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRUserInfoImpl.m; path = Firebase/Auth/Source/FIRUserInfoImpl.m; sourceTree = ""; }; + D4B06DF0BDF7821D048B9478C5F9D97B /* FTreeNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTreeNode.m; path = Firebase/Database/Core/Utilities/FTreeNode.m; sourceTree = ""; }; + D4DE91FD1133887F4AAC325B2A16F0FC /* FPersistentConnection.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPersistentConnection.m; path = Firebase/Database/Core/FPersistentConnection.m; sourceTree = ""; }; + D4E9DA654B479F3D6D45FA95B672723B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D54AF9EA9805ABF27B6EE19DE73292C9 /* cache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = cache.h; path = include/leveldb/cache.h; sourceTree = ""; }; + D56EDA2992910A82DF34AF0EDB0669B2 /* FIRStorageGetMetadataTask.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageGetMetadataTask.m; path = Firebase/Storage/FIRStorageGetMetadataTask.m; sourceTree = ""; }; + D5863210436D92737B63B73087F63968 /* FIRVerifyPasswordRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyPasswordRequest.h; path = Firebase/Auth/Source/RPCs/FIRVerifyPasswordRequest.h; sourceTree = ""; }; + D5CE9FDA9DE67B0F21F0E0F042EC9399 /* FirebaseStorage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FirebaseStorage-umbrella.h"; sourceTree = ""; }; + D5EB1CBA1D1666D7B3560FAA3427A1C9 /* FIRStorageUploadTask_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageUploadTask_Private.h; path = Firebase/Storage/Private/FIRStorageUploadTask_Private.h; sourceTree = ""; }; + D5FA71E496F7AA410D948D768C02A01C /* FOverwrite.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FOverwrite.m; path = Firebase/Database/Core/Operation/FOverwrite.m; sourceTree = ""; }; + D616343B4F9F391E6FEA8F0DECC1E7C2 /* GULReachabilityChecker.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULReachabilityChecker.m; path = GoogleUtilities/Reachability/GULReachabilityChecker.m; sourceTree = ""; }; + D64CE5DB6A98F389176B81AB143A03A1 /* c.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = c.cc; path = db/c.cc; sourceTree = ""; }; + D6BB61D1DB5D35D8FCF2FAC65BB2D959 /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRuntimeTypes.h; path = objectivec/GPBRuntimeTypes.h; sourceTree = ""; }; + D81F978D0BA4662DD96F6F62D35FC8C3 /* FTuplePathValue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTuplePathValue.m; path = Firebase/Database/Utilities/Tuples/FTuplePathValue.m; sourceTree = ""; }; + D85725E49DA341F05193CDB8F70FB05C /* Pods-My MindUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My MindUITests-frameworks.sh"; sourceTree = ""; }; + D897AF51D9D53A189E407BC729E743A8 /* Struct.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Struct.pbobjc.h; path = objectivec/google/protobuf/Struct.pbobjc.h; sourceTree = ""; }; + D89CBF341E031516C3B740A39C2A597D /* FIRVerifyClientRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyClientRequest.h; path = Firebase/Auth/Source/RPCs/FIRVerifyClientRequest.h; sourceTree = ""; }; + D8D66411B1D52F4EEB26FA6AE6A04187 /* FArraySortedDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FArraySortedDictionary.h; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.h; sourceTree = ""; }; + D9356AFA47E58DAC25375A606AEBDD04 /* FIRDatabaseConfig_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseConfig_Private.h; path = Firebase/Database/FIRDatabaseConfig_Private.h; sourceTree = ""; }; + D940987A9FD15F075D87E6F596C88350 /* FRepoInfo.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRepoInfo.h; path = Firebase/Database/Core/FRepoInfo.h; sourceTree = ""; }; + D97D7500FF14C5EC413647CED0DE06EB /* histogram.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = histogram.h; path = util/histogram.h; sourceTree = ""; }; + D9A33F10F6D5631362A4E2C21DEEAB0B /* FIRAuthCredential_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthCredential_Internal.h; path = Firebase/Auth/Source/FIRAuthCredential_Internal.h; sourceTree = ""; }; + D9FB7EE240FB526E2B6E1D0ACFAA87B0 /* FirebaseCore-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FirebaseCore-umbrella.h"; sourceTree = ""; }; + DA833CB65907D992C5524A7B7E0E8342 /* FIRApp.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRApp.m; path = Firebase/Core/FIRApp.m; sourceTree = ""; }; + DAB331FBC7C4E444D49D2095E2B10937 /* FIndex.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIndex.m; path = Firebase/Database/FIndex.m; sourceTree = ""; }; + DB021ACCB48A686C9395F474B83CDC23 /* FIRTwitterAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRTwitterAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/Twitter/FIRTwitterAuthProvider.m; sourceTree = ""; }; + DB34977EAC5FC57813546A70B32C7B9D /* FirebaseMessaging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseMessaging.h; path = Firebase/Messaging/Public/FirebaseMessaging.h; sourceTree = ""; }; + DBEBD39CF1E6349AD5DA85B84BC7DFCF /* FRepoManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRepoManager.h; path = Firebase/Database/Core/FRepoManager.h; sourceTree = ""; }; + DC3D972C91B6D9FB1DE234EB59AB07A6 /* FIRAuthWebView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthWebView.h; path = Firebase/Auth/Source/FIRAuthWebView.h; sourceTree = ""; }; + DC4966A882229EFA017144185FF21757 /* FTupleNodePath.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleNodePath.h; path = Firebase/Database/Utilities/Tuples/FTupleNodePath.h; sourceTree = ""; }; + DC5BCCD19D83503611CAFE7CCBF2D059 /* FKeepSyncedEventRegistration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FKeepSyncedEventRegistration.h; path = Firebase/Database/Core/View/FKeepSyncedEventRegistration.h; sourceTree = ""; }; + DC7302524ADB8DC85494B6AAD3CBA1D8 /* pb_encode.c */ = {isa = PBXFileReference; includeInIndex = 1; path = pb_encode.c; sourceTree = ""; }; + DC9216026608FFA44A02C2E8BF9A9E3C /* FTupleTransaction.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FTupleTransaction.m; path = Firebase/Database/Utilities/Tuples/FTupleTransaction.m; sourceTree = ""; }; + DC9B8460FA63820AFA6854A35DA829C6 /* FChildrenNode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FChildrenNode.m; path = Firebase/Database/Snapshot/FChildrenNode.m; sourceTree = ""; }; + DCFB485E7EE041483501574C5B2F7CCA /* FIRDeleteAccountResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDeleteAccountResponse.m; path = Firebase/Auth/Source/RPCs/FIRDeleteAccountResponse.m; sourceTree = ""; }; + DD8F80849FF142E6CEA8C80A9429B455 /* FIRMutableData.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMutableData.h; path = Firebase/Database/Public/FIRMutableData.h; sourceTree = ""; }; + DE26B28C737D0FE9E95269B09CF011BF /* FIRMessagingPubSubRegistrar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingPubSubRegistrar.h; path = Firebase/Messaging/FIRMessagingPubSubRegistrar.h; sourceTree = ""; }; + DE84738710FAC6778EC1FBE3B5235F5D /* GPBProtocolBuffers_RuntimeSupport.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBProtocolBuffers_RuntimeSupport.h; path = objectivec/GPBProtocolBuffers_RuntimeSupport.h; sourceTree = ""; }; + DEE1195481C3E699963E947E9FDAD7EA /* FPriorityIndex.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPriorityIndex.m; path = Firebase/Database/FPriorityIndex.m; sourceTree = ""; }; + DEEA04A7AF313BCFBBB48A30AA8E1EF3 /* leveldb-library-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "leveldb-library-umbrella.h"; sourceTree = ""; }; + DEED9B0809AD0BCE53D0943BD7BCD19D /* FListenComplete.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FListenComplete.h; path = Firebase/Database/FListenComplete.h; sourceTree = ""; }; + DF89E6C6615E5188CAC12F41A08EA8E4 /* FChange.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FChange.m; path = Firebase/Database/Core/View/FChange.m; sourceTree = ""; }; + DF98451C4B15976BDA23D038EBF6A0EC /* FormStepperCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormStepperCell.swift; path = SwiftForms/cells/FormStepperCell.swift; sourceTree = ""; }; + DFAA5FB160375FF5C55D7C4D8FEAA640 /* FIRAuthRPCResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthRPCResponse.h; path = Firebase/Auth/Source/RPCs/FIRAuthRPCResponse.h; sourceTree = ""; }; + DFF02281941C12B08E8712F2DE9DC391 /* FIndexedNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIndexedNode.h; path = Firebase/Database/Snapshot/FIndexedNode.h; sourceTree = ""; }; + E0216286990A5FC34839E3F80B8D6C96 /* FViewProcessor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FViewProcessor.h; path = Firebase/Database/FViewProcessor.h; sourceTree = ""; }; + E09ECF63E89195F26D272FC3BD8C7044 /* filter_block.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = filter_block.cc; path = table/filter_block.cc; sourceTree = ""; }; + E0B1B26588D39F632E7FAE741113153C /* FIRStorageObservableTask_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageObservableTask_Private.h; path = Firebase/Storage/Private/FIRStorageObservableTask_Private.h; sourceTree = ""; }; + E0F0F5DF6F0408D75CDCE659553410AD /* GULReachabilityChecker.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULReachabilityChecker.h; path = GoogleUtilities/Reachability/Private/GULReachabilityChecker.h; sourceTree = ""; }; + E0F5DF31EC2E62475823F5669748B32A /* coding.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = coding.h; path = util/coding.h; sourceTree = ""; }; + E17134467E8954E9AF37025460CAB049 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + E1CECB23F7293747C87E09C0248F6AED /* FIRAuth_Internal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuth_Internal.h; path = Firebase/Auth/Source/FIRAuth_Internal.h; sourceTree = ""; }; + E2DC2EB959470FCEF39EC7C80F5316B0 /* FRangedFilter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRangedFilter.h; path = Firebase/Database/FRangedFilter.h; sourceTree = ""; }; + E2EB03A9C23A3485A23624B691D9B7A8 /* FIRComponentContainer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRComponentContainer.h; path = Firebase/Core/Private/FIRComponentContainer.h; sourceTree = ""; }; + E317B12D5F902A2C6E951A9FCCC59530 /* FIRStorageTaskSnapshot.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageTaskSnapshot.h; path = Firebase/Storage/Public/FIRStorageTaskSnapshot.h; sourceTree = ""; }; + E332EF6637191BA88B5B349CBC134581 /* FTupleObjectNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleObjectNode.h; path = Firebase/Database/Utilities/Tuples/FTupleObjectNode.h; sourceTree = ""; }; + E35D272AECCFDD36EEA858CFE9754389 /* FirebaseStorage.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FirebaseStorage.framework; path = FirebaseStorage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E39B46C41B2E94BA9A549054158CE7D2 /* FIRDeleteAccountRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRDeleteAccountRequest.m; path = Firebase/Auth/Source/RPCs/FIRDeleteAccountRequest.m; sourceTree = ""; }; + E3BF03E4739013E7453C5D34B1E4DB00 /* FIRAuthOperationType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthOperationType.h; path = Firebase/Auth/Source/FIRAuthOperationType.h; sourceTree = ""; }; + E4EAF32030EF5CA9819B3EE91BF69845 /* FPriorityIndex.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPriorityIndex.h; path = Firebase/Database/FPriorityIndex.h; sourceTree = ""; }; + E4ECDD1348A475B5ADCE6B521AF2DAF0 /* FValidation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FValidation.h; path = Firebase/Database/Utilities/FValidation.h; sourceTree = ""; }; + E5225ECE5C504283C697AD841E3C44DD /* Pods-My MindUITests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-My MindUITests-resources.sh"; sourceTree = ""; }; + E53EA631D6B0E9EEA7B2FADB660D1EEA /* skiplist.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = skiplist.h; path = db/skiplist.h; sourceTree = ""; }; + E56C14A11112A55CF82997DF7D888028 /* version_set.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = version_set.h; path = db/version_set.h; sourceTree = ""; }; + E5C19961FA70611535C5C36236F23D9C /* FValueEventRegistration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FValueEventRegistration.h; path = Firebase/Database/Core/View/FValueEventRegistration.h; sourceTree = ""; }; + E5ECBBFA8BFE9B48F5ECAD6DBD5D940C /* FIRCreateAuthURIRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRCreateAuthURIRequest.m; path = Firebase/Auth/Source/RPCs/FIRCreateAuthURIRequest.m; sourceTree = ""; }; + E68A2AA637BDE4FEB94C7CBB17526C5A /* FPersistentConnection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FPersistentConnection.h; path = Firebase/Database/Core/FPersistentConnection.h; sourceTree = ""; }; + E6913AC5D85713434F74209FB9DF8190 /* status.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = status.cc; path = util/status.cc; sourceTree = ""; }; + E6ADDAD8E70600449B60E0A2A6A84AA6 /* GULLoggerCodes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULLoggerCodes.h; path = GoogleUtilities/Common/GULLoggerCodes.h; sourceTree = ""; }; + E70889143006716935C52FEB99418BDE /* FNamedNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FNamedNode.h; path = Firebase/Database/FNamedNode.h; sourceTree = ""; }; + E71A396EC91191A023047F9E295CDCC4 /* FIRStorageComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageComponent.h; path = Firebase/Storage/Private/FIRStorageComponent.h; sourceTree = ""; }; + E7A59D3F7A1A6EB8A8A65F5269D9F6EB /* FIRAnalyticsConfiguration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAnalyticsConfiguration.m; path = Firebase/Core/FIRAnalyticsConfiguration.m; sourceTree = ""; }; + E7C9E6358BF67C02F1D141654EA02672 /* FIRAuthErrorUtils.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthErrorUtils.m; path = Firebase/Auth/Source/FIRAuthErrorUtils.m; sourceTree = ""; }; + E7DD9769669DB7F9E67FC275C3FB7C4B /* FEventRegistration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEventRegistration.h; path = Firebase/Database/Core/View/FEventRegistration.h; sourceTree = ""; }; + E7FB12B47C9D60E0AF8953271C31107A /* FTupleUserCallback.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleUserCallback.h; path = Firebase/Database/Utilities/Tuples/FTupleUserCallback.h; sourceTree = ""; }; + E83395DDC37AB2B43925CB22AB834320 /* GPBExtensionRegistry.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBExtensionRegistry.h; path = objectivec/GPBExtensionRegistry.h; sourceTree = ""; }; + E8340D499EC8097E61282D5B6D61DAB0 /* FIRAuthSettings.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthSettings.h; path = Firebase/Auth/Source/Public/FIRAuthSettings.h; sourceTree = ""; }; + E8777028A6004E068FD4E41BDFD48861 /* FSyncPoint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FSyncPoint.m; path = Firebase/Database/Core/FSyncPoint.m; sourceTree = ""; }; + E921EE2F6E50B2B950BD43A6A6862162 /* FTupleFirebase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleFirebase.h; path = Firebase/Database/Utilities/Tuples/FTupleFirebase.h; sourceTree = ""; }; + E9445B15B9114E5F95CD4E870F39436A /* FIRAuthAppDelegateProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthAppDelegateProxy.m; path = Firebase/Auth/Source/FIRAuthAppDelegateProxy.m; sourceTree = ""; }; + E9A0AA959E20E29F08FC62B2BC5D5DD9 /* FIRBundleUtil.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRBundleUtil.h; path = Firebase/Core/Private/FIRBundleUtil.h; sourceTree = ""; }; + E9ABDE6BBA1A94C280712138E8C978C7 /* snapshot.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = snapshot.h; path = db/snapshot.h; sourceTree = ""; }; + E9F29370AA19CCEBB83FD2748FE606CE /* FClock.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FClock.h; path = Firebase/Database/FClock.h; sourceTree = ""; }; + E9FCF84F7BA642F2599D22BCF97995B1 /* FIRMessagingSyncMessageManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingSyncMessageManager.h; path = Firebase/Messaging/FIRMessagingSyncMessageManager.h; sourceTree = ""; }; + EA129F6051473738DE8F6680613B7386 /* FValueIndex.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FValueIndex.h; path = Firebase/Database/FValueIndex.h; sourceTree = ""; }; + EA86C1C2E7F7812ADB29376757F6DD4F /* FIRNoopAuthTokenProvider.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRNoopAuthTokenProvider.h; path = Firebase/Database/Login/FIRNoopAuthTokenProvider.h; sourceTree = ""; }; + EAA423220A289264800007CD89C00078 /* FIRVerifyPhoneNumberResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRVerifyPhoneNumberResponse.h; path = Firebase/Auth/Source/RPCs/FIRVerifyPhoneNumberResponse.h; sourceTree = ""; }; + EAB5351F6840056BB82AC5102A960BE9 /* FormCheckCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormCheckCell.swift; path = SwiftForms/cells/FormCheckCell.swift; sourceTree = ""; }; + EAEE4CEDCD6C42826ACDDFADE4DF0FB2 /* table_builder.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = table_builder.cc; path = table/table_builder.cc; sourceTree = ""; }; + EAFA346294A42DC00BC37D078709B709 /* Pods-My Mind.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My Mind.release.xcconfig"; sourceTree = ""; }; + EB3595599A6D697943276F3488DD6BEC /* FRepo_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FRepo_Private.h; path = Firebase/Database/Core/FRepo_Private.h; sourceTree = ""; }; + EB3848F29E49C46F357D0BC9679EAEE3 /* FIRSecureTokenResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSecureTokenResponse.h; path = Firebase/Auth/Source/RPCs/FIRSecureTokenResponse.h; sourceTree = ""; }; + EBACD6FF2BAF6C98C1E9D96D22E6E633 /* FPath.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPath.m; path = Firebase/Database/Core/Utilities/FPath.m; sourceTree = ""; }; + EBAFE747641CFE19EA7DD3E3143DC52C /* logging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = logging.h; path = util/logging.h; sourceTree = ""; }; + EBF70370314641E65536A91D17604E7F /* Struct.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Struct.pbobjc.m; path = objectivec/google/protobuf/Struct.pbobjc.m; sourceTree = ""; }; + EBF8441A787609A9C03B1FAB585F4CCF /* Pods_My_MindUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_My_MindUITests.framework; path = "Pods-My MindUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + EC2F40DC4BABBA1C34D6609803FED9F1 /* GPBUnknownFieldSet.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownFieldSet.h; path = objectivec/GPBUnknownFieldSet.h; sourceTree = ""; }; + EC5CE6854B764CF987743F870A9DD509 /* FIRDatabaseConfig.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseConfig.h; path = Firebase/Database/Api/FIRDatabaseConfig.h; sourceTree = ""; }; + EC93543560F23E0335E10D04FC89916A /* FormOptionsViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormOptionsViewController.swift; path = SwiftForms/controllers/FormOptionsViewController.swift; sourceTree = ""; }; + ED57FFADAE2E118F4B39FED169254F9B /* Wrappers.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Wrappers.pbobjc.h; path = objectivec/google/protobuf/Wrappers.pbobjc.h; sourceTree = ""; }; + EDB380628BB6381119D18060E3B1363C /* FIRComponentContainerInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRComponentContainerInternal.h; path = Firebase/Core/Private/FIRComponentContainerInternal.h; sourceTree = ""; }; + EE07AE37AF13904CAE7EB4AFEA96A9DB /* FOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FOperation.h; path = Firebase/Database/Core/Operation/FOperation.h; sourceTree = ""; }; + EEECFB49B1C1890C57ED844291FCAD69 /* FCompleteChildSource.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FCompleteChildSource.h; path = Firebase/Database/Core/View/Filter/FCompleteChildSource.h; sourceTree = ""; }; + EF22EB80F2D3ECF9EA4920E3DCDDFC51 /* Type.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Type.pbobjc.m; path = objectivec/google/protobuf/Type.pbobjc.m; sourceTree = ""; }; + EF2565BF522E6ED879327B1704A108DC /* FTupleStringNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleStringNode.h; path = Firebase/Database/Utilities/Tuples/FTupleStringNode.h; sourceTree = ""; }; + EF9B0B817B564DEA1E062086A289548D /* FirebaseAuth.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FirebaseAuth.xcconfig; sourceTree = ""; }; + EFE54910E41A84C06DFFFD3C00995957 /* FIRAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthProvider.m; path = Firebase/Auth/Source/FIRAuthProvider.m; sourceTree = ""; }; + F03EAA2EC81A15074DB6D1EA122E97C0 /* FArraySortedDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FArraySortedDictionary.m; path = Firebase/Database/third_party/FImmutableSortedDictionary/FImmutableSortedDictionary/FArraySortedDictionary.m; sourceTree = ""; }; + F08B3446D2D7E79BDED0E749BE1B104A /* FirebaseMessaging.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FirebaseMessaging.modulemap; sourceTree = ""; }; + F09277F67D2CA69E933081A31E0BE2F1 /* GULNSData+zlib.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "GULNSData+zlib.m"; path = "GoogleUtilities/NSData+zlib/GULNSData+zlib.m"; sourceTree = ""; }; + F0FFC65783EF4F9F0D9583E9873A1AD9 /* FIRMessagingRmqManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingRmqManager.m; path = Firebase/Messaging/FIRMessagingRmqManager.m; sourceTree = ""; }; + F130B0DE3FDFDE9134E3CF93A5B4075D /* FIRFacebookAuthProvider.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRFacebookAuthProvider.m; path = Firebase/Auth/Source/AuthProviders/Facebook/FIRFacebookAuthProvider.m; sourceTree = ""; }; + F13F2E644801D0E3C822FC88E1B1FA6E /* FIRMutableData_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMutableData_Private.h; path = Firebase/Database/Api/Private/FIRMutableData_Private.h; sourceTree = ""; }; + F1605E61657A7435C9C2AB1893D5E9F9 /* GULNetworkURLSession.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULNetworkURLSession.h; path = GoogleUtilities/Network/Private/GULNetworkURLSession.h; sourceTree = ""; }; + F1AE2FDC03291973313CBF81B1338212 /* FIRAppAssociationRegistration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAppAssociationRegistration.m; path = Firebase/Core/FIRAppAssociationRegistration.m; sourceTree = ""; }; + F1D8CB7DF2E46250C1C43220C97810B6 /* dbformat.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = dbformat.cc; path = db/dbformat.cc; sourceTree = ""; }; + F22610E4772184F5CBC2C803828100CA /* testharness.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = testharness.h; path = util/testharness.h; sourceTree = ""; }; + F2FADE2C536AB93A60E734718FD411F7 /* FIRGetAccountInfoRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRGetAccountInfoRequest.h; path = Firebase/Auth/Source/RPCs/FIRGetAccountInfoRequest.h; sourceTree = ""; }; + F305AC9FC0D8555AD1783A104FEDB22F /* GULSwizzler.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GULSwizzler.m; path = GoogleUtilities/MethodSwizzler/GULSwizzler.m; sourceTree = ""; }; + F3084FADD51BE52F8FAD4EDDF5886E44 /* GPBArray_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBArray_PackagePrivate.h; path = objectivec/GPBArray_PackagePrivate.h; sourceTree = ""; }; + F315942AF6B5C93E6FB28E2F583FC8B4 /* FIRAnalyticsConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAnalyticsConfiguration.h; path = Firebase/Core/Public/FIRAnalyticsConfiguration.h; sourceTree = ""; }; + F36514100428C5491F827F9CB81CEA6F /* FTreeNode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTreeNode.h; path = Firebase/Database/Core/Utilities/FTreeNode.h; sourceTree = ""; }; + F3CD7429816330A075E23E1CD8A04B36 /* Protobuf-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Protobuf-dummy.m"; sourceTree = ""; }; + F58D16C5FBEE3D3C9EE7D4F75929C633 /* FTupleCallbackStatus.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FTupleCallbackStatus.h; path = Firebase/Database/Utilities/Tuples/FTupleCallbackStatus.h; sourceTree = ""; }; + F5A2BF62391ECF98F03EB919C5C2380A /* FIRDatabaseReference.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRDatabaseReference.h; path = Firebase/Database/Public/FIRDatabaseReference.h; sourceTree = ""; }; + F5CFDBA1A91011693D868DC825A161AB /* pb_decode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = pb_decode.h; sourceTree = ""; }; + F5F63D1EB7FA70A254BE597E678D416D /* FEventRaiser.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FEventRaiser.h; path = Firebase/Database/Core/View/FEventRaiser.h; sourceTree = ""; }; + F647C20117821F0CBC11B9D07F881E2E /* FIRLogger.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRLogger.m; path = Firebase/Core/FIRLogger.m; sourceTree = ""; }; + F6680C23E17FDEF739AE9C28CE584837 /* nanopb.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = nanopb.xcconfig; sourceTree = ""; }; + F6A0E3ACCDA034A63E32E2E773A849B9 /* FIRAuthUIDelegate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthUIDelegate.h; path = Firebase/Auth/Source/Public/FIRAuthUIDelegate.h; sourceTree = ""; }; + F6A56D57F7830EB35CBFC515C582CF0A /* crc32c.cc */ = {isa = PBXFileReference; includeInIndex = 1; name = crc32c.cc; path = util/crc32c.cc; sourceTree = ""; }; + F6B33E27089631C018426D12DE3BF2B1 /* FIRStorageComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRStorageComponent.m; path = Firebase/Storage/FIRStorageComponent.m; sourceTree = ""; }; + F7526F869857A24835B865B3FC4871E3 /* port_posix.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = port_posix.h; path = port/port_posix.h; sourceTree = ""; }; + F78F642663E7302B237D8578707BB7CA /* FAtomicNumber.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FAtomicNumber.h; path = Firebase/Database/Utilities/FAtomicNumber.h; sourceTree = ""; }; + F7EADE67FC960214F7DED9045D807108 /* db.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = db.h; path = include/leveldb/db.h; sourceTree = ""; }; + F80CC5E45B9D60B0D5733364ECA9F9DF /* GPBUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUtilities.h; path = objectivec/GPBUtilities.h; sourceTree = ""; }; + F80EB3448A60D38ECC61534F768996CE /* GTMSessionFetcherService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherService.h; path = Source/GTMSessionFetcherService.h; sourceTree = ""; }; + F838EB368C156DCBF33114DF3D43DF9B /* FIRAuthRequestConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRAuthRequestConfiguration.h; path = Firebase/Auth/Source/RPCs/FIRAuthRequestConfiguration.h; sourceTree = ""; }; + F8482E2E1DB4B525FF0826BAE0A61D59 /* Pods-My MindUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-My MindUITests.debug.xcconfig"; sourceTree = ""; }; + F85F3E47AD33DA9D446FBF975B322883 /* FIRResetPasswordResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRResetPasswordResponse.m; path = Firebase/Auth/Source/RPCs/FIRResetPasswordResponse.m; sourceTree = ""; }; + F8EEA04BA35D6AA6DDE2D44BA30C6527 /* FNodeFilter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FNodeFilter.h; path = Firebase/Database/Core/View/Filter/FNodeFilter.h; sourceTree = ""; }; + F9CF71EEB7AF86F89B8AE4EE689AC486 /* FEventRaiser.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FEventRaiser.m; path = Firebase/Database/Core/View/FEventRaiser.m; sourceTree = ""; }; + FA2D1B490973CDAE6A8E40524F7FB975 /* FIRResetPasswordRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRResetPasswordRequest.h; path = Firebase/Auth/Source/RPCs/FIRResetPasswordRequest.h; sourceTree = ""; }; + FA90962585855F75431533CD68E4E496 /* FirebaseAuth.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FirebaseAuth.h; path = Firebase/Auth/Source/Public/FirebaseAuth.h; sourceTree = ""; }; + FB1E9CF96D680EA21D837060EF23667F /* FIRSendVerificationCodeRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSendVerificationCodeRequest.h; path = Firebase/Auth/Source/RPCs/FIRSendVerificationCodeRequest.h; sourceTree = ""; }; + FB339759EDEDCBAB839541CCC515B825 /* GULNetworkMessageCode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GULNetworkMessageCode.h; path = GoogleUtilities/Network/Private/GULNetworkMessageCode.h; sourceTree = ""; }; + FB7FAEB44184D619533442D7E1C2EACD /* GtalkExtensions.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GtalkExtensions.pbobjc.h; path = Firebase/Messaging/Protos/GtalkExtensions.pbobjc.h; sourceTree = ""; }; + FC73B473572AD55A393CF3469D719B60 /* FIRMessagingCheckinService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingCheckinService.h; path = Firebase/Messaging/FIRMessagingCheckinService.h; sourceTree = ""; }; + FC7C460601A2517E74B240EE306DF439 /* FPathIndex.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FPathIndex.m; path = Firebase/Database/FPathIndex.m; sourceTree = ""; }; + FC900162842DCBE91B0D3CE747B548A0 /* FIRAuthDefaultUIDelegate.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthDefaultUIDelegate.m; path = Firebase/Auth/Source/FIRAuthDefaultUIDelegate.m; sourceTree = ""; }; + FC9BEE8EF9E33D02A8E5B842C4EC1747 /* GPBExtensionRegistry.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionRegistry.m; path = objectivec/GPBExtensionRegistry.m; sourceTree = ""; }; + FCB3CE399BE35A4E8F9B829CB8F18A16 /* FormBaseCell.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormBaseCell.swift; path = SwiftForms/cells/base/FormBaseCell.swift; sourceTree = ""; }; + FDA6193F787E16C51CE19542A9069DBE /* FIRSendVerificationCodeResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRSendVerificationCodeResponse.h; path = Firebase/Auth/Source/RPCs/FIRSendVerificationCodeResponse.h; sourceTree = ""; }; + FDB044D43FDB91C9E18B19954C2084C4 /* FIRStorageObservableTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRStorageObservableTask.h; path = Firebase/Storage/Public/FIRStorageObservableTask.h; sourceTree = ""; }; + FDC169456A740BDFC932E5BF9A8BF8E4 /* Pods-My MindUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-My MindUITests-acknowledgements.markdown"; sourceTree = ""; }; + FDE8721AA1451531A2BE7D5A17E015FE /* FIRMessagingClient.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRMessagingClient.m; path = Firebase/Messaging/FIRMessagingClient.m; sourceTree = ""; }; + FE464DE5F2ADF86CCC4FBA2E5749B1F9 /* FWriteRecord.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FWriteRecord.m; path = Firebase/Database/Core/FWriteRecord.m; sourceTree = ""; }; + FE4B7054E146828925FC005DB56E8904 /* GoogleUtilities-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GoogleUtilities-dummy.m"; sourceTree = ""; }; + FE9E27ABE098D998E78AD75EBBA7544F /* FIRAuthWebView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRAuthWebView.m; path = Firebase/Auth/Source/FIRAuthWebView.m; sourceTree = ""; }; + FEC70A46FDF74AF507252CDF69F4337C /* FWriteTreeRef.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FWriteTreeRef.h; path = Firebase/Database/Core/FWriteTreeRef.h; sourceTree = ""; }; + FED3152358EC24AC1254184016912802 /* nanopb-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "nanopb-dummy.m"; sourceTree = ""; }; + FF3583499DA2598AA2E4C1B876EFC6DC /* FIRBundleUtil.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FIRBundleUtil.m; path = Firebase/Core/FIRBundleUtil.m; sourceTree = ""; }; + FFAB81D84005BC13B7205C87F1074E07 /* FIRCreateAuthURIResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRCreateAuthURIResponse.h; path = Firebase/Auth/Source/RPCs/FIRCreateAuthURIResponse.h; sourceTree = ""; }; + FFD573F1AB574F736E72462CA185FF02 /* FIRMessagingReceiver.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FIRMessagingReceiver.h; path = Firebase/Messaging/FIRMessagingReceiver.h; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 048B27D4FC4365B1E9007F9DA49AC3CB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + FC409897309F8E012973C893AF773117 /* Foundation.framework in Frameworks */, + 25BD5A9E2BB1FB1B4516291C971ACD0C /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0655C48C728F73F99BC5AB1B11AB5EC3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6F42A6B98CED5A87976CB199EC3007FA /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 09566CECE9666F15B9F3099A22879D47 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 583FE7D60284123D8C65C8AE24BEF1AC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 143A6B1F015B3C428A965831E8D28387 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BEB10ABF326685345381D2EB834029DB /* Foundation.framework in Frameworks */, + 5F5E3FE69B8ED5CEB2B462BA63EBBA60 /* Security.framework in Frameworks */, + 8EDBB7DBAA3BF2D76EBEF32F67A00D78 /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4E6529B2B4149EC8AFC03CF39D542F5B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 895D35F4A615219F80A7944477D1DA86 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6E984081A095D70D07D998B48BC38F15 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0D611A6D1BA11199662FCA250FFF8CF4 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9B08098DF508E32B908F1F589E4B8AF4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 315787FF4CC7A8C3020173EAA4957447 /* Foundation.framework in Frameworks */, + 60B8F4DA4C6208E62572814E08FB289E /* Security.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A28F455D6452C719007E7AE725EACC1D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 93D6683C3A685E2AEB12C507A89B39BD /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AF423F5CC7B9F0D02502F027B8E03B23 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EBA20935C28770BF8934A346F76C5EB7 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B5AA29F197F968B04B5A425EF066C65A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E4719BDDE80650C7A1E792DF2C011F4 /* Foundation.framework in Frameworks */, + BD6D70EFF7DD0E5BB20BE976C6BBEDD9 /* SafariServices.framework in Frameworks */, + 27C4FCE0C3EBCD347685FE38B934F608 /* Security.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C37D2CEF682C0259FB70478168453E22 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9EF75B2E4E2EDFE1D9446E65835535E4 /* CFNetwork.framework in Frameworks */, + F9D00D0E8CDC4255CA25137F3B76264E /* Foundation.framework in Frameworks */, + 4B71158A817AF0F60DE979F2AC709276 /* Security.framework in Frameworks */, + 42417A7D0D3025CE0CD3954A5180448D /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CE33C54DF5DB61D9669BEB4C03781675 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A4AE8E529212651C640D9649EAD0AB95 /* Foundation.framework in Frameworks */, + 31010EF42D84A135C1CB0E1B39A43E4D /* MobileCoreServices.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CECA8FCA1D8F6F5CD8AE4C60FC35F5CB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3618415B8ADA597762A024D5B7A425BA /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D5F6CCE4A47F38EFF44ABEC022EA2AB6 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2DBB5514F29F5829C5AE527F6E4FDA05 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 092C115D312095D3FED4A00E3261A324 /* FirebaseMessaging */ = { + isa = PBXGroup; + children = ( + DB34977EAC5FC57813546A70B32C7B9D /* FirebaseMessaging.h */, + 4485AF69CA9E95F41797643FEB969885 /* FirebaseMessaging.h */, + A5F1DF0DE04325F03FFC21877D9F2DD6 /* FIRMessaging.h */, + 19BFB803A0CA8832F957B481C492303E /* FIRMessaging.m */, + 0A2649CC5725FA949A3D54FB633180B6 /* FIRMessaging_Private.h */, + 24C4C8F54426C9EFB4F6CEA3C77E8E45 /* FIRMessagingAnalytics.h */, + 8045F511732AF21BD969650BBDB79264 /* FIRMessagingAnalytics.m */, + FC73B473572AD55A393CF3469D719B60 /* FIRMessagingCheckinService.h */, + 9FBD462DDA28EDB862ADCA7FCC50527D /* FIRMessagingCheckinService.m */, + 5DBC97B383D5D93C4468FCF29B800674 /* FIRMessagingClient.h */, + FDE8721AA1451531A2BE7D5A17E015FE /* FIRMessagingClient.m */, + 5D65988F3A1356BEE3BC3D0369BBAAC9 /* FIRMessagingCodedInputStream.h */, + CCD534072CDFAE76358EC05074E7A1FD /* FIRMessagingCodedInputStream.m */, + 235678AD0689F0483082B3B7FEB46171 /* FIRMessagingConnection.h */, + CD5261ED7894617F948B8217A7A98098 /* FIRMessagingConnection.m */, + BE0BCF2C1C9FD3078B1F5A3C3EE7C25A /* FIRMessagingConstants.h */, + A08220A6CDB071FCB4B1F7EC1186D5A5 /* FIRMessagingConstants.m */, + 90CAF6C078AC9FA0DDDF5AF785F595F4 /* FIRMessagingContextManagerService.h */, + 262865D53F46E4528F6B67FF9DC6A479 /* FIRMessagingContextManagerService.m */, + 519AD2081997EB288B842570149B0B7F /* FIRMessagingDataMessageManager.h */, + 58D5C0A45F0C7FAA8267304BFB70E2B2 /* FIRMessagingDataMessageManager.m */, + A6181FF5A800FCCC67FBFE0B7BF53D27 /* FIRMessagingDefines.h */, + A31F7EB02525A5A5990CCF17AFCBEEDF /* FIRMessagingDelayedMessageQueue.h */, + 65353A37CF47A6651F323694730E2BC7 /* FIRMessagingDelayedMessageQueue.m */, + 4B9FB583E7E3DD4C7B26A9FE34F5DF59 /* FIRMessagingInternalUtilities.h */, + 46079141822DE20B0FF0729023B40DB5 /* FIRMessagingLogger.h */, + 34AE0C022045C233A6AA55DF5C66D612 /* FIRMessagingLogger.m */, + C2FF98AE061B3CCF1FD81B6324D7D16B /* FIRMessagingPacketQueue.h */, + 9E3E1944E3D50CC93173226B11C47ACC /* FIRMessagingPacketQueue.m */, + ADFB0C91FF0A24C4F22AC190030E4908 /* FIRMessagingPendingTopicsList.h */, + 0BB05FBFFE9C45491F3750E50AD53A85 /* FIRMessagingPendingTopicsList.m */, + A7C4DF6F92826595F2A84D72365B5505 /* FIRMessagingPersistentSyncMessage.h */, + CDF371265A9A6D8E73196A94E4D28CC6 /* FIRMessagingPersistentSyncMessage.m */, + 76E425DE58AFB1DFDD7497FB60D1E793 /* FIRMessagingPubSub.h */, + 580D3A9DD3E77BC53E3D35F0023DDE1E /* FIRMessagingPubSub.m */, + DE26B28C737D0FE9E95269B09CF011BF /* FIRMessagingPubSubRegistrar.h */, + B7090A47010657A1918B87BAE29D0A1E /* FIRMessagingPubSubRegistrar.m */, + FFD573F1AB574F736E72462CA185FF02 /* FIRMessagingReceiver.h */, + 2A393A9D280CF827CED384D5807BDA33 /* FIRMessagingReceiver.m */, + 9D1DF1BF918CF6CEECA759D75788A242 /* FIRMessagingRegistrar.h */, + 5BB790ABECC5AB46EEC32C04E1E3DE9D /* FIRMessagingRegistrar.m */, + 26D0C49266BF657CB1AF5A18E8F591DB /* FIRMessagingRemoteNotificationsProxy.h */, + C9AEE3D9A205088F3D2E0972D99DE8D7 /* FIRMessagingRemoteNotificationsProxy.m */, + A950F6251ACB2BC29B9B91DFD2DE3CFD /* FIRMessagingRmq2PersistentStore.h */, + 550F30B53D98C5B179E6C9B95DCBBD49 /* FIRMessagingRmq2PersistentStore.m */, + 2CEEEDDBF0B7C02B72407C0E80B35688 /* FIRMessagingRmqManager.h */, + F0FFC65783EF4F9F0D9583E9873A1AD9 /* FIRMessagingRmqManager.m */, + 736C022A06E3955768DC6544360A723E /* FIRMessagingSecureSocket.h */, + B60A88AD3A3288AB7892EBF19A5E3DD7 /* FIRMessagingSecureSocket.m */, + E9FCF84F7BA642F2599D22BCF97995B1 /* FIRMessagingSyncMessageManager.h */, + 92DCCD218678B124254F507D53D566A5 /* FIRMessagingSyncMessageManager.m */, + B84AB522D96FDBEF56178B4E103D0722 /* FIRMessagingTopicOperation.h */, + 9BFA0AB7799DA0A5FF85F62324964A2F /* FIRMessagingTopicOperation.m */, + 1B5BD339D6126E58145A91C670A79B57 /* FIRMessagingTopicsCommon.h */, + 51B29CF73AD215059BC28D3753ECE814 /* FIRMessagingUtilities.h */, + 143163CDF7251156D7FE094D45C15FEB /* FIRMessagingUtilities.m */, + B50EE45BEEE9696770C9F0E3526DABF0 /* FIRMessagingVersionUtilities.h */, + 7C96AB097262F1C3DCC11C50D3E59544 /* FIRMessagingVersionUtilities.m */, + 15918B10BD6CE7C57B16DB55766DE2AE /* FIRMMessageCode.h */, + A54BE9E44DCB1F38C08F562BD72CAE85 /* GtalkCore.pbobjc.h */, + 4C7934CC4C320D6B8EED446F41CB3070 /* GtalkCore.pbobjc.m */, + FB7FAEB44184D619533442D7E1C2EACD /* GtalkExtensions.pbobjc.h */, + 6F11B8D726B6EB35E25DBAFF2E410D30 /* GtalkExtensions.pbobjc.m */, + BDE06C7169B511B43A4220DCCA6B9012 /* NSDictionary+FIRMessaging.h */, + 35ACEC850EA6B8AF4B8B76044A429AA6 /* NSDictionary+FIRMessaging.m */, + 8FA1D93D5FF3EDB8C2273A0FC52FDD92 /* NSError+FIRMessaging.h */, + 6C2D515DB16433C8F3E59AAF36EF38EE /* NSError+FIRMessaging.m */, + A0B2BADB8D528CA49E6F669EAC9F61F1 /* Support Files */, + ); + name = FirebaseMessaging; + path = FirebaseMessaging; + sourceTree = ""; + }; + 0BCCD19470F228B0326A8213A73A24BF /* FirebaseAuth */ = { + isa = PBXGroup; + children = ( + D1D35C7CEFB980F5F15231F61E072857 /* FIRActionCodeSettings.h */, + A7F1204A860C29B4A4BAEF12AC3CA224 /* FIRActionCodeSettings.m */, + B7365E12A17D8AEA411AFD1AE22C6647 /* FIRAdditionalUserInfo.h */, + CFA8257B2CAC756753E55E997D0374B3 /* FIRAdditionalUserInfo.m */, + 446370E4A06E1F0DF2205B16D666D0AD /* FIRAdditionalUserInfo_Internal.h */, + 0239D1D4504BAE07E728075902DC1878 /* FIRAuth.h */, + A1D37659A08CA55180F3AA24ED62C072 /* FIRAuth.m */, + E1CECB23F7293747C87E09C0248F6AED /* FIRAuth_Internal.h */, + 50D69B40CB7B6EE788D4ED8121EE5627 /* FIRAuthAPNSToken.h */, + D11762CCA4EA49A55F93AF08FB928633 /* FIRAuthAPNSToken.m */, + CB6099DEF2E3EDF5BDE646A402A7223C /* FIRAuthAPNSTokenManager.h */, + A971443D94F15814ACF2372DEC544C9E /* FIRAuthAPNSTokenManager.m */, + 005F17A0CA6BD689AE60571DA2BAFA11 /* FIRAuthAPNSTokenType.h */, + 2A48BB8A8D3B8F2F32F334BD438F45DA /* FIRAuthAppCredential.h */, + C892A85A358C20C1C99EDA725170E12E /* FIRAuthAppCredential.m */, + 366FDECE49AF8E55FF1E41E5B8D8A099 /* FIRAuthAppCredentialManager.h */, + CF6C4A834EC0A2207726AB45C8E5DF0E /* FIRAuthAppCredentialManager.m */, + AA8F8C049192849495466614A330F2EF /* FIRAuthAppDelegateProxy.h */, + E9445B15B9114E5F95CD4E870F39436A /* FIRAuthAppDelegateProxy.m */, + D231D1C9A6DC029C392DA35062159AD0 /* FIRAuthBackend.h */, + C1A0FB94A0B45A747CBE8D23321B8BCD /* FIRAuthBackend.m */, + CD10E05003650C16485F6681FFCFB453 /* FIRAuthCredential.h */, + 58DAD62A1384B6C2202497AAECD4FEF9 /* FIRAuthCredential.m */, + D9A33F10F6D5631362A4E2C21DEEAB0B /* FIRAuthCredential_Internal.h */, + 13B62195E3A11B0D93DB60EBB5ED122A /* FIRAuthDataResult.h */, + 1A49F1C98CBAA4564CA3708149127C6D /* FIRAuthDataResult.m */, + AD06A572C80510926057D48A1FF3CFC4 /* FIRAuthDataResult_Internal.h */, + 9C5043AB5D8305D0A639BECC966F573B /* FIRAuthDefaultUIDelegate.h */, + FC900162842DCBE91B0D3CE747B548A0 /* FIRAuthDefaultUIDelegate.m */, + 77F9D6EC5529498A65162396F20E0832 /* FIRAuthDispatcher.h */, + 5D9EAD1637B2E283AC5ACDA1E015C325 /* FIRAuthDispatcher.m */, + 95334361346B957D96FDAF00D5ACED6C /* FIRAuthErrors.h */, + 3202E21A3C70DC101F9BC193374415EC /* FIRAuthErrorUtils.h */, + E7C9E6358BF67C02F1D141654EA02672 /* FIRAuthErrorUtils.m */, + 300E08C04185ADA1E87FE6C0D81A10E8 /* FIRAuthExceptionUtils.h */, + 7AF6DE6416DB4C133F69C73FA0A99C96 /* FIRAuthExceptionUtils.m */, + 386373BFF6E630E359797C1A82AB1070 /* FIRAuthGlobalWorkQueue.h */, + 3023906E936612450A901BB43816EB8C /* FIRAuthGlobalWorkQueue.m */, + 99AC8DEBC31A6F60675A164487CD70F0 /* FIRAuthInternalErrors.h */, + C1D412970289721316660D54C69470C1 /* FIRAuthKeychain.h */, + 3E58E6D786617300484ECDDFACB2FA6F /* FIRAuthKeychain.m */, + 1CA6D0718F1BE8F2CD2B515567E26AB1 /* FIRAuthNotificationManager.h */, + 5546B6C998BFFC4D1BE353AACAB4656B /* FIRAuthNotificationManager.m */, + E3BF03E4739013E7453C5D34B1E4DB00 /* FIRAuthOperationType.h */, + EFE54910E41A84C06DFFFD3C00995957 /* FIRAuthProvider.m */, + F838EB368C156DCBF33114DF3D43DF9B /* FIRAuthRequestConfiguration.h */, + 5DC32D3EC7D2CD53597176FFB6E5F799 /* FIRAuthRequestConfiguration.m */, + AC05B3DB4EDE20A5FD7CE64075AB866E /* FIRAuthRPCRequest.h */, + DFAA5FB160375FF5C55D7C4D8FEAA640 /* FIRAuthRPCResponse.h */, + 119A6FE215E962613478EEBFC1F4F505 /* FIRAuthSerialTaskQueue.h */, + 44009DA6BD52A71E123946AA1B2A1CCC /* FIRAuthSerialTaskQueue.m */, + E8340D499EC8097E61282D5B6D61DAB0 /* FIRAuthSettings.h */, + 8AE098A043EF747C4AB64731CEDC3FA3 /* FIRAuthSettings.m */, + 70BF98E2DC5C000BD8610127B3AD8AF6 /* FIRAuthTokenResult.h */, + 8086976E909F242ED65F58A319245ADD /* FIRAuthTokenResult.m */, + 35C0A0B5A99461EBCFD376962B2F5C0D /* FIRAuthTokenResult_Internal.h */, + F6A0E3ACCDA034A63E32E2E773A849B9 /* FIRAuthUIDelegate.h */, + 61B27FDBC34602CF2A3DFD944ED2B245 /* FIRAuthURLPresenter.h */, + BA3EDB47D8082026DB6188D3030E770B /* FIRAuthURLPresenter.m */, + C5578903E5AF1A9CA32A01FFF0D569CA /* FIRAuthUserDefaultsStorage.h */, + C7664078AAB63061F0485623401B4036 /* FIRAuthUserDefaultsStorage.m */, + 5E7945D06F7A9490E3DFDF843C010E48 /* FIRAuthWebUtils.h */, + 50B1EEF969FB395B98F5ACBC29642FB0 /* FIRAuthWebUtils.m */, + DC3D972C91B6D9FB1DE234EB59AB07A6 /* FIRAuthWebView.h */, + FE9E27ABE098D998E78AD75EBBA7544F /* FIRAuthWebView.m */, + 30C9C71BCCDD2CD24C276AE7ED003666 /* FIRAuthWebViewController.h */, + B6C8EB92AE55113567DF336B2C0EA1AB /* FIRAuthWebViewController.m */, + 402D85148074A575F2F4BE6D41FE80D8 /* FIRCreateAuthURIRequest.h */, + E5ECBBFA8BFE9B48F5ECAD6DBD5D940C /* FIRCreateAuthURIRequest.m */, + FFAB81D84005BC13B7205C87F1074E07 /* FIRCreateAuthURIResponse.h */, + 12A5C3A9A8DA7A2944A508E1378B93B1 /* FIRCreateAuthURIResponse.m */, + 389D2E096B89ACC945F9139E64B99063 /* FIRDeleteAccountRequest.h */, + E39B46C41B2E94BA9A549054158CE7D2 /* FIRDeleteAccountRequest.m */, + 0E6EEACCBF201D7F886D030A77A7A82C /* FIRDeleteAccountResponse.h */, + DCFB485E7EE041483501574C5B2F7CCA /* FIRDeleteAccountResponse.m */, + FA90962585855F75431533CD68E4E496 /* FirebaseAuth.h */, + A9D4C247886677E0DE4667C1879C2A92 /* FirebaseAuthVersion.h */, + 9DEB6F89764B79942EF4FF1368A9F6C8 /* FirebaseAuthVersion.m */, + 060A5011E8273A2F4FB12E14AA12DD51 /* FIREmailAuthProvider.h */, + 5035A64EE2A9A3DB9A03376F395A3702 /* FIREmailAuthProvider.m */, + B4DCF5F9A05116C8E5BEB7E4672C77F0 /* FIREmailLinkSignInRequest.h */, + 82BF3B71827ABBD71A94D5711CFE9608 /* FIREmailLinkSignInRequest.m */, + 5D650E258391748C898E6F33D5F2942A /* FIREmailLinkSignInResponse.h */, + 72B13FA9D89B5C3A0B31E47601B35B31 /* FIREmailLinkSignInResponse.m */, + 7D8E3F4071E80D79F82FA3705A1B7D05 /* FIREmailPasswordAuthCredential.h */, + 1261B3607B95AB5FCC0789BAC0335F4D /* FIREmailPasswordAuthCredential.m */, + CE4660BA7D6E8CFDAD16757199161DB4 /* FIRFacebookAuthCredential.h */, + 37A41E82010FCD2D354DE448260E8240 /* FIRFacebookAuthCredential.m */, + 4F0A45134989F661BACC63DCA7091243 /* FIRFacebookAuthProvider.h */, + F130B0DE3FDFDE9134E3CF93A5B4075D /* FIRFacebookAuthProvider.m */, + 8C7AF4806829E1A7FBD4AC2CF543B2DA /* FIRGameCenterAuthCredential.h */, + C2B6EFFEA69D94C962C92D480A5F7B5D /* FIRGameCenterAuthCredential.m */, + 74E0D6E907564B3A142EAA69A8541AD6 /* FIRGameCenterAuthProvider.h */, + 512270231AF1BD7162D2DF64A91E39D7 /* FIRGameCenterAuthProvider.m */, + F2FADE2C536AB93A60E734718FD411F7 /* FIRGetAccountInfoRequest.h */, + 01D86F9DE1F79FD6C75EEAAD33BE292E /* FIRGetAccountInfoRequest.m */, + 44750059DC524A1D74F3CE34D403991A /* FIRGetAccountInfoResponse.h */, + 26C18E86BC3C699C7D43F84F8E6ABBA6 /* FIRGetAccountInfoResponse.m */, + 7DD22742CF31B2734B421A041B5F23FA /* FIRGetOOBConfirmationCodeRequest.h */, + 248D6396DD17D8431F0B3A31293DBA66 /* FIRGetOOBConfirmationCodeRequest.m */, + 1FA4FBB774B84B9517944CCF8010D41D /* FIRGetOOBConfirmationCodeResponse.h */, + C5D45A7FC3F4035103ED107B1F6127F3 /* FIRGetOOBConfirmationCodeResponse.m */, + 7C8725D11133377692FA563EF613C7C6 /* FIRGetProjectConfigRequest.h */, + 72DAEB8DAF3F23E6A8C884A9E87C387E /* FIRGetProjectConfigRequest.m */, + 64EB27157BEA9B6EBFBC9D30A55480BE /* FIRGetProjectConfigResponse.h */, + 83AA3E602C3A2961790AEAADF22D1659 /* FIRGetProjectConfigResponse.m */, + 769FB4DFF434F108F981154B69D3C883 /* FIRGitHubAuthCredential.h */, + A82B173D007A576E78AC1896EC794E94 /* FIRGitHubAuthCredential.m */, + 08BE0BDCDEF190A30B893BEC5F1A9358 /* FIRGitHubAuthProvider.h */, + BC6957CC5CFB8C0C21FB9630CB797E96 /* FIRGitHubAuthProvider.m */, + 6CBEB890F1BD0F79AC3D8CE936C581EE /* FIRGoogleAuthCredential.h */, + 03AD6BA64F476C451207DEF30D1C0DF7 /* FIRGoogleAuthCredential.m */, + 95AAEB80477A015CAFD91C1AB9C14DA7 /* FIRGoogleAuthProvider.h */, + 90547EAE2B940B2E499C30B4B93D1996 /* FIRGoogleAuthProvider.m */, + CB5E5EDC823A0512816F5F6A8AAE7BCD /* FIRIdentityToolkitRequest.h */, + 0ED14CD3D134195AD99E47BD299EBDF7 /* FIRIdentityToolkitRequest.m */, + 758F44968682287AD497896C6C56B2F6 /* FIROAuthCredential.h */, + 6056409035CBAA33FC4C1E992C685A4D /* FIROAuthCredential.m */, + 3CFA6E1D288C15BD5851CFEDE6AEA633 /* FIROAuthProvider.h */, + 673AC49687E8659EB56A9747F2AD855A /* FIROAuthProvider.m */, + CF39E63BAD15EE14C47C6750CC780862 /* FIRPhoneAuthCredential.h */, + 052D3EAECFCF7B7A9741902E21858002 /* FIRPhoneAuthCredential.m */, + 33865930EE20D6BBB99E16994933D2BE /* FIRPhoneAuthCredential_Internal.h */, + 2FE952393E91F78CAE5094FFA1EBBA52 /* FIRPhoneAuthProvider.h */, + 29343B35E5F2B0EFA39F218482ACB0CB /* FIRPhoneAuthProvider.m */, + FA2D1B490973CDAE6A8E40524F7FB975 /* FIRResetPasswordRequest.h */, + BCF80591D51DDED99DCFEB418DAF6C6D /* FIRResetPasswordRequest.m */, + 19DE6E8E7B6B1372BCE4CC0AAB53C3AC /* FIRResetPasswordResponse.h */, + F85F3E47AD33DA9D446FBF975B322883 /* FIRResetPasswordResponse.m */, + BCA9949E729F8FA89A2FBA1FC41A08C4 /* FIRSecureTokenRequest.h */, + 4879E1F0A6D1768BFA268E9A80030B20 /* FIRSecureTokenRequest.m */, + EB3848F29E49C46F357D0BC9679EAEE3 /* FIRSecureTokenResponse.h */, + 66861CF6B01E5AA0D15E1B102B1ED8CC /* FIRSecureTokenResponse.m */, + 136CC9E6128297BD62D6F21F1284BF89 /* FIRSecureTokenService.h */, + 7E38B04C7F997C0C975D2B0D29941212 /* FIRSecureTokenService.m */, + FB1E9CF96D680EA21D837060EF23667F /* FIRSendVerificationCodeRequest.h */, + 0E91BBDEE4AE9CD077A210B6FD93D664 /* FIRSendVerificationCodeRequest.m */, + FDA6193F787E16C51CE19542A9069DBE /* FIRSendVerificationCodeResponse.h */, + BF57C0F85A406C3D449F4E1AF68D0A9B /* FIRSendVerificationCodeResponse.m */, + 70B2BC7C8E160DF34E8B88E3EC14A5F4 /* FIRSetAccountInfoRequest.h */, + 9A73AA5071EC8EB467C178B670E2D98D /* FIRSetAccountInfoRequest.m */, + AFB0AC6451A7F1334E2461C600716593 /* FIRSetAccountInfoResponse.h */, + 6506C0D8E4A809C7E2AA6AD0EC391E50 /* FIRSetAccountInfoResponse.m */, + 65B16A3C4124590E56D417A1088A2B7A /* FIRSignInWithGameCenterRequest.h */, + C185A4DDD2586774727CB23BCBED0299 /* FIRSignInWithGameCenterRequest.m */, + AA4C3D674727250939C11F0687171F23 /* FIRSignInWithGameCenterResponse.h */, + 6770B86455BBED608BD0F1FCAA2346F9 /* FIRSignInWithGameCenterResponse.m */, + 7BBCD51FAF30C35611BEB23B626C6624 /* FIRSignUpNewUserRequest.h */, + C2A917B7B3143CB35B45491393EFE099 /* FIRSignUpNewUserRequest.m */, + 6B9420FD08C302FF4ABE9F9E8AB18A16 /* FIRSignUpNewUserResponse.h */, + 4B2E73208606BF9C75DD9E3264B83E42 /* FIRSignUpNewUserResponse.m */, + 7195FC7DA43CAFF389557007B61500CF /* FIRTwitterAuthCredential.h */, + 05E0E3991A44C3DB0537924A5B2482D6 /* FIRTwitterAuthCredential.m */, + 9DBBB76901A980386DB2BECA4667AA5D /* FIRTwitterAuthProvider.h */, + DB021ACCB48A686C9395F474B83CDC23 /* FIRTwitterAuthProvider.m */, + 44B502759D088A3DA6A61F8E45DABA0D /* FIRUser.h */, + 82B3C6D58D32965D5CB48FD4B37BA1A4 /* FIRUser.m */, + CD321F3BDAC9E5C193BB7538DB15F36B /* FIRUser_Internal.h */, + C6D1B26A950547F59D7E738E2C779092 /* FIRUserInfo.h */, + 40A760468EF4E6190C18CA4B004F5C0E /* FIRUserInfoImpl.h */, + D3FCE7821A5559920675860218C3E7B6 /* FIRUserInfoImpl.m */, + 17DE2AD6AD6B952E14BD83D4D76F3E5A /* FIRUserMetadata.h */, + 68055C3921D68B4D2A9E01154969543C /* FIRUserMetadata.m */, + 4617A321F3C66DFCDB857489511992AE /* FIRUserMetadata_Internal.h */, + 4E20EFABC4BDDD0348F7A103E0A8FDF7 /* FIRVerifyAssertionRequest.h */, + 62AADFBC08D568729C990BADB7ECB893 /* FIRVerifyAssertionRequest.m */, + 3E7DE789305AEF826F8350378348A196 /* FIRVerifyAssertionResponse.h */, + 82EF6EA3A6D823BECFDF2D38E49A1895 /* FIRVerifyAssertionResponse.m */, + D89CBF341E031516C3B740A39C2A597D /* FIRVerifyClientRequest.h */, + 4FE6FFD73A1F41902CEAA39F2D6CAD7A /* FIRVerifyClientRequest.m */, + 909BF2B1ECC1C9990B47F744DBFE4353 /* FIRVerifyClientResponse.h */, + D18CEA84295910BAB47D481FA1692F0D /* FIRVerifyClientResponse.m */, + D37225295D40A9C051F75D0BC81405E1 /* FIRVerifyCustomTokenRequest.h */, + 365E83317995CD7525ED8911984FA695 /* FIRVerifyCustomTokenRequest.m */, + B68C0AB6F0930895E952BF5A780C56D6 /* FIRVerifyCustomTokenResponse.h */, + 68AB70689ECD68BDF9F973D46450CA1F /* FIRVerifyCustomTokenResponse.m */, + D5863210436D92737B63B73087F63968 /* FIRVerifyPasswordRequest.h */, + A3010B8604A66F46C262E7C7847DADA3 /* FIRVerifyPasswordRequest.m */, + 5D2E468E56AC4645517F8EF8383EFA59 /* FIRVerifyPasswordResponse.h */, + 7635E3F9E1F28E2FD77AD02BFB30ED18 /* FIRVerifyPasswordResponse.m */, + 52DFF27FBBEDFDB18FA44BEAD7283C38 /* FIRVerifyPhoneNumberRequest.h */, + AF170DAA3F83CF4EBDF6F1339EF00018 /* FIRVerifyPhoneNumberRequest.m */, + EAA423220A289264800007CD89C00078 /* FIRVerifyPhoneNumberResponse.h */, + 0192E00D386318F5FECB4BB5FC607F7D /* FIRVerifyPhoneNumberResponse.m */, + 0BC11EBDA615AAA6167464EEE00C3EE1 /* NSData+FIRBase64.h */, + 7DBC6776E71F32FE26F370F3CC2E5792 /* NSData+FIRBase64.m */, + 4AE2B64DE4751F031D80CF1C6C2E9CEE /* Support Files */, + ); + name = FirebaseAuth; + path = FirebaseAuth; + sourceTree = ""; + }; + 0F75DF6C7C5F002280EC53F48E80B587 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 7EFEEDD91F2B5950C9F07F344BAFC504 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 196A2B543D4B5CB1747A734C31058706 /* encode */ = { + isa = PBXGroup; + children = ( + ); + name = encode; + sourceTree = ""; + }; + 1BA27E865E53795D87E139A2F79AFEF4 /* Firebase */ = { + isa = PBXGroup; + children = ( + 3009869BC477B7929401BD61318CAF45 /* CoreOnly */, + ); + name = Firebase; + path = Firebase; + sourceTree = ""; + }; + 1D9D3DC7748BB6D45C201E8576C530F4 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 28DD4217FC6A0D73528ACAA60B8925E4 /* Pods-My Mind */, + 2ADDB84ECB79009BC2E7BFE2521CD619 /* Pods-My MindTests */, + 81E4053A069D2B42C612892AE9755D27 /* Pods-My MindUITests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 1E007DA9363BD8C7AD6B460292D110EC /* MethodSwizzler */ = { + isa = PBXGroup; + children = ( + 3D4C5029B4F56F33C0AFF2C7BB347753 /* GULOriginalIMPConvenienceMacros.h */, + 9A425C87553240C22CA6ECCE49E65196 /* GULSwizzler.h */, + F305AC9FC0D8555AD1783A104FEDB22F /* GULSwizzler.m */, + ); + name = MethodSwizzler; + sourceTree = ""; + }; + 1F34D31012DF852EA54F306726AE1F70 /* FirebaseInstanceID */ = { + isa = PBXGroup; + children = ( + 9A77C0FFDBAE19797B1DF37B4DAAA5C1 /* Frameworks */, + ); + name = FirebaseInstanceID; + path = FirebaseInstanceID; + sourceTree = ""; + }; + 22BE2ED4240A362CBE3E6DDFA1EE4CFE /* Reachability */ = { + isa = PBXGroup; + children = ( + E0F0F5DF6F0408D75CDCE659553410AD /* GULReachabilityChecker.h */, + D616343B4F9F391E6FEA8F0DECC1E7C2 /* GULReachabilityChecker.m */, + 8D7BE7EA6367DA949086D526736A7DE0 /* GULReachabilityChecker+Internal.h */, + 195F2A114F33FC39E8EE0AF6ECE74737 /* GULReachabilityMessageCode.h */, + ); + name = Reachability; + sourceTree = ""; + }; + 23D865198669DB6537255F32D5E5D385 /* Support Files */ = { + isa = PBXGroup; + children = ( + D4E9DA654B479F3D6D45FA95B672723B /* Info.plist */, + ACA1566B042023738C7E7216DCC158C5 /* leveldb-library.modulemap */, + 532A60C333164404D23A05ACB55C6E71 /* leveldb-library.xcconfig */, + 00773E4B291D7B6F765A193B71873384 /* leveldb-library-dummy.m */, + 4B91F276ACCA0FA41F13EAFA194E3FDE /* leveldb-library-prefix.pch */, + DEEA04A7AF313BCFBBB48A30AA8E1EF3 /* leveldb-library-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/leveldb-library"; + sourceTree = ""; + }; + 26F6FFAADD8EBDBE1789C5EBDF9FF5D5 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 54DB67BBBF0DFC563CE6CFB817F5D9A7 /* FIRAnalyticsConnector.framework */, + B30A46EF299C9AE94179DFBE2C0A1583 /* FirebaseAnalytics.framework */, + 52E24DBE1C27A0E703963706FF750477 /* FirebaseCoreDiagnostics.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 28DD4217FC6A0D73528ACAA60B8925E4 /* Pods-My Mind */ = { + isa = PBXGroup; + children = ( + CA78AE84FFDE46D92C15B239A36D72EC /* Info.plist */, + 368FFE6CB6D2F8002E6237D83CC0D3C3 /* Pods-My Mind.modulemap */, + A1136B2404BFAF4882B76A1FB3876A79 /* Pods-My Mind-acknowledgements.markdown */, + C7CD4E9BC7D2C83FF01A0328A280F5FA /* Pods-My Mind-acknowledgements.plist */, + 3DA0DF0B81ED2E59E65402AA12829CDE /* Pods-My Mind-dummy.m */, + 504066F2745B7E4AD642CAD54BDE53EC /* Pods-My Mind-frameworks.sh */, + BB147D332EB59A3C55AD8275F836ADCF /* Pods-My Mind-resources.sh */, + 750AE2BD4EAC19C11179AC6E5CE3BF7E /* Pods-My Mind-umbrella.h */, + 441DBA22AFAC3463555CEA3C57697304 /* Pods-My Mind.debug.xcconfig */, + EAFA346294A42DC00BC37D078709B709 /* Pods-My Mind.release.xcconfig */, + ); + name = "Pods-My Mind"; + path = "Target Support Files/Pods-My Mind"; + sourceTree = ""; + }; + 2ADDB84ECB79009BC2E7BFE2521CD619 /* Pods-My MindTests */ = { + isa = PBXGroup; + children = ( + 3BE90917ABE234BE1286DC10A4D177F1 /* Info.plist */, + 5C1FEDE4CE6EE40E810E2832FFCC90B6 /* Pods-My MindTests.modulemap */, + 743A102405B7E18D6CA2D8402079C09D /* Pods-My MindTests-acknowledgements.markdown */, + 0F8B1871C7FFB70E87F78EF2A17A58B4 /* Pods-My MindTests-acknowledgements.plist */, + 027526482DD73377A6A7A78E8339F2A5 /* Pods-My MindTests-dummy.m */, + 7ADD427EA772DEE9928CC4A60652E1F1 /* Pods-My MindTests-frameworks.sh */, + 3081C96D7043D1BCEE537DC6020F9A52 /* Pods-My MindTests-resources.sh */, + 95C32177E2BED1782D2001DFA1FF0550 /* Pods-My MindTests-umbrella.h */, + AC29AD359CB65A16BC601242EC2BC78F /* Pods-My MindTests.debug.xcconfig */, + 14C8ECD8310E798246C725B33683BD31 /* Pods-My MindTests.release.xcconfig */, + ); + name = "Pods-My MindTests"; + path = "Target Support Files/Pods-My MindTests"; + sourceTree = ""; + }; + 2FF3A060DBFFD5C2500278A4E39BDE7F /* nanopb */ = { + isa = PBXGroup; + children = ( + 301054B3F03AB321796CB62FDD44BE25 /* pb.h */, + AAD8583A56D06F8B53175D035AF9D864 /* pb_common.c */, + C0579785095D37C75777806A0548CD41 /* pb_common.h */, + 1AAD408CF6F37412CD16C253807B02FF /* pb_decode.c */, + F5CFDBA1A91011693D868DC825A161AB /* pb_decode.h */, + DC7302524ADB8DC85494B6AAD3CBA1D8 /* pb_encode.c */, + A9A58585F2C08E9463E0F2DC3EC61173 /* pb_encode.h */, + ECC5ECB8EA94143AAEFF4F5C8C384B79 /* decode */, + 196A2B543D4B5CB1747A734C31058706 /* encode */, + A3E8C2DDF092554068F18EE61CB4DD08 /* Support Files */, + ); + name = nanopb; + path = nanopb; + sourceTree = ""; + }; + 3009869BC477B7929401BD61318CAF45 /* CoreOnly */ = { + isa = PBXGroup; + children = ( + 82C76459EDA44C637947DB893A87631C /* Firebase.h */, + ); + name = CoreOnly; + sourceTree = ""; + }; + 3439E5262F178D1F9B4A066615F6D693 /* Core */ = { + isa = PBXGroup; + children = ( + 1A4C69A6E7DCD1DA0FE2647B81119490 /* GTMSessionFetcher.h */, + 3C94FF97478A1FE3BF81F60237C1B74C /* GTMSessionFetcher.m */, + 789256212F2759B2374887DCC6A6854E /* GTMSessionFetcherLogging.h */, + 2D49C8229916022BD904F466DD4B1695 /* GTMSessionFetcherLogging.m */, + F80EB3448A60D38ECC61534F768996CE /* GTMSessionFetcherService.h */, + 7577A71A88803C69782A292FCE3A8583 /* GTMSessionFetcherService.m */, + 54D2205BB0299DF468F8355C100D0647 /* GTMSessionUploadFetcher.h */, + 42BC28884C5305F80E35B4E805480874 /* GTMSessionUploadFetcher.m */, + ); + name = Core; + sourceTree = ""; + }; + 35A674E0697A027DB6355B9C9D8D93C6 /* Support Files */ = { + isa = PBXGroup; + children = ( + 656C3EA7E5E83D408C6465B56BA18268 /* FirebaseCore.modulemap */, + B042774A378BD6A6A47CAF43D174D354 /* FirebaseCore.xcconfig */, + 682FB182ED2813B933EC052FF4298A6F /* FirebaseCore-dummy.m */, + D9FB7EE240FB526E2B6E1D0ACFAA87B0 /* FirebaseCore-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/FirebaseCore"; + sourceTree = ""; + }; + 3C2A3F24A3209A37991B966325EEC297 /* AppDelegateSwizzler */ = { + isa = PBXGroup; + children = ( + ACB3D17DA57ABABF8DEFB9172C36AF43 /* GULAppDelegateSwizzler.h */, + 938DFBB9348CD99AFF254CF39CF17698 /* GULAppDelegateSwizzler.m */, + 9DBFB549CA0840AFD4B56E933019DF0A /* GULAppDelegateSwizzler_Private.h */, + E6ADDAD8E70600449B60E0A2A6A84AA6 /* GULLoggerCodes.h */, + ); + name = AppDelegateSwizzler; + sourceTree = ""; + }; + 3DCA43ED9745C07120606066B8EEEC20 /* Pods */ = { + isa = PBXGroup; + children = ( + 1BA27E865E53795D87E139A2F79AFEF4 /* Firebase */, + 7DE5F80371BD26722753792B9342F074 /* FirebaseAnalytics */, + CF655F1E3635CC44708BD6E2C3BB86C9 /* FirebaseAnalyticsInterop */, + 0BCCD19470F228B0326A8213A73A24BF /* FirebaseAuth */, + 79055673CEFCE7CEDAA84C8645B378D7 /* FirebaseAuthInterop */, + 66AA99C178BDFB8CEE6DEBA36AFA8D2D /* FirebaseCore */, + C6309194E8E98243DA592750691DD468 /* FirebaseDatabase */, + 1F34D31012DF852EA54F306726AE1F70 /* FirebaseInstanceID */, + 092C115D312095D3FED4A00E3261A324 /* FirebaseMessaging */, + CB24FEA7C77F0ED6800218317257EF06 /* FirebaseStorage */, + C6DCA632A0241403E8C2B63C226E3FDE /* GoogleAppMeasurement */, + CB80E732D1B59BC1BFD500644F76E62A /* GoogleUtilities */, + AA120728779E91B4C3EFA571A3DBAEA1 /* GTMSessionFetcher */, + DC5AFC953EBD7FA261B9BB7B25ED5441 /* leveldb-library */, + 2FF3A060DBFFD5C2500278A4E39BDE7F /* nanopb */, + C3358E849786CD6629639EFD7EA91A04 /* Protobuf */, + 7A754D1FB8588572DA30BAE3E257B795 /* SwiftForms */, + ); + name = Pods; + sourceTree = ""; + }; + 42205DB17ED33C115B061F58407A7F39 /* Support Files */ = { + isa = PBXGroup; + children = ( + AFF0724B2C7C2E8E26274EEB21F79C60 /* Info.plist */, + AA2224EC04EF8A8CF027796F264D4AF6 /* SwiftForms.modulemap */, + 45A06472A76E939B327F33F87CB8F5AA /* SwiftForms.xcconfig */, + 87D05F4B7557FD9A9E830518CB5D0024 /* SwiftForms-dummy.m */, + B9962BD291505BFFBA34CC528C43DE1C /* SwiftForms-prefix.pch */, + A899DB3CC1F64B5D6F8B8877B8D5B7D2 /* SwiftForms-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftForms"; + sourceTree = ""; + }; + 4AE2B64DE4751F031D80CF1C6C2E9CEE /* Support Files */ = { + isa = PBXGroup; + children = ( + 167247C461FA542A015E0FDFE30C7A26 /* FirebaseAuth.modulemap */, + EF9B0B817B564DEA1E062086A289548D /* FirebaseAuth.xcconfig */, + 7FBE764F8D555B5617404FEE2CB64111 /* FirebaseAuth-dummy.m */, + C4B963BE88DF9BAD70BB2577285B94FA /* FirebaseAuth-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/FirebaseAuth"; + sourceTree = ""; + }; + 4BB017215827D6A750B79B7C5BE87947 /* Support Files */ = { + isa = PBXGroup; + children = ( + BB4A6F767E6E29DB9A1B3EE2B13EBFCD /* FirebaseStorage.modulemap */, + 1FB8225F6A8837C1B29AA8D1503478F1 /* FirebaseStorage.xcconfig */, + 757D739372A973A1A6B387E52878A9B6 /* FirebaseStorage-dummy.m */, + D5CE9FDA9DE67B0F21F0E0F042EC9399 /* FirebaseStorage-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/FirebaseStorage"; + sourceTree = ""; + }; + 66AA99C178BDFB8CEE6DEBA36AFA8D2D /* FirebaseCore */ = { + isa = PBXGroup; + children = ( + F315942AF6B5C93E6FB28E2F583FC8B4 /* FIRAnalyticsConfiguration.h */, + E7A59D3F7A1A6EB8A8A65F5269D9F6EB /* FIRAnalyticsConfiguration.m */, + 455B531E0B5384D77DBDDA413F3CDF03 /* FIRAnalyticsConfiguration+Internal.h */, + AA832C3FE6C7B3EC74C14089A07B2D7D /* FIRApp.h */, + DA833CB65907D992C5524A7B7E0E8342 /* FIRApp.m */, + A485EC28C2BCF093F8C31F8A206D38E6 /* FIRAppAssociationRegistration.h */, + F1AE2FDC03291973313CBF81B1338212 /* FIRAppAssociationRegistration.m */, + 0F38BB1D2C2DC6C63F1A53730F4F5F50 /* FIRAppInternal.h */, + E9A0AA959E20E29F08FC62B2BC5D5DD9 /* FIRBundleUtil.h */, + FF3583499DA2598AA2E4C1B876EFC6DC /* FIRBundleUtil.m */, + 03232B0207F9B72BCA1F06FB31EAF211 /* FIRComponent.h */, + 43C51F661E1732A453C8FF3CC41FE99B /* FIRComponent.m */, + E2EB03A9C23A3485A23624B691D9B7A8 /* FIRComponentContainer.h */, + 3E496823521868D352C97412E304C944 /* FIRComponentContainer.m */, + EDB380628BB6381119D18060E3B1363C /* FIRComponentContainerInternal.h */, + 8354D5D2A1E3BE749C059D69DD9A80E4 /* FIRComponentRegistrant.h */, + 7A28513C7E79F8D83ACCE3ADDEB0CA1B /* FIRComponentType.h */, + C867367352BE84E57F50CB0AD6199922 /* FIRComponentType.m */, + B0AD46A45553ED004551AE6C62A05B2C /* FIRConfiguration.h */, + 0C387A89EF9BCFB1D9AEC1628A6FFB57 /* FIRConfiguration.m */, + 36D45A7FA49317344BF019A206D17B1E /* FIRCoreConfigurable.h */, + 7BF676BAC287FD9AF2842E1602416108 /* FIRDependency.h */, + 00A0CB9CA5B1E26BDE9D15F6F93F607F /* FIRDependency.m */, + 28408A35C59B8DAEAB6216D22C3FB49D /* FirebaseCore.h */, + 508285CBB0038322C3CDFA2C14D67013 /* FIRErrorCode.h */, + A1B86C1FEFEAA44BF8471DF6A3B328BB /* FIRErrors.h */, + B17E60B74D249F60A7E8A809C20EFCBA /* FIRErrors.m */, + A386A5F444120EBDA11F9BF76D51E331 /* FIRLogger.h */, + F647C20117821F0CBC11B9D07F881E2E /* FIRLogger.m */, + 777D09D2C04A9EDDF146AD4F850B0308 /* FIRLoggerLevel.h */, + A7E45C4CB7E9A1B7DC4448F0725D4921 /* FIROptions.h */, + 13E143593E7232E1F8B12AC4FE62DA8A /* FIROptions.m */, + AD7412CA4B83C16AF5D10344627F2226 /* FIROptionsInternal.h */, + 796A9E6A5DF0679ED69FE7F4CDC25199 /* FIRVersion.h */, + 2DB687A0483C0EE960D37434597A35AE /* FIRVersion.m */, + 35A674E0697A027DB6355B9C9D8D93C6 /* Support Files */, + ); + name = FirebaseCore; + path = FirebaseCore; + sourceTree = ""; + }; + 79055673CEFCE7CEDAA84C8645B378D7 /* FirebaseAuthInterop */ = { + isa = PBXGroup; + children = ( + 2B45B623BB352D383633A4CF9C608127 /* FIRAuthInterop.h */, + ); + name = FirebaseAuthInterop; + path = FirebaseAuthInterop; + sourceTree = ""; + }; + 7A754D1FB8588572DA30BAE3E257B795 /* SwiftForms */ = { + isa = PBXGroup; + children = ( + FCB3CE399BE35A4E8F9B829CB8F18A16 /* FormBaseCell.swift */, + AECBA6A0BBA8C75D909C3BBA5A05C859 /* FormButtonCell.swift */, + EAB5351F6840056BB82AC5102A960BE9 /* FormCheckCell.swift */, + 4AFE8F37C120A82C78B58A29BCB9E818 /* FormDateCell.swift */, + 9E31C3BDBFCEDEA18A1165D42EB6C7D4 /* FormDescriptor.swift */, + 5A1D1A56E980A843F4C35E043C9858B9 /* FormErrorType.swift */, + 0E95E3219504D83CD57E912728E959D3 /* FormLabelCell.swift */, + EC93543560F23E0335E10D04FC89916A /* FormOptionsViewController.swift */, + 0F065833D4D711DB2314D643800DD031 /* FormPickerCell.swift */, + 21519CE5EB78FDA959307B63623B7289 /* FormRowDescriptor.swift */, + 491F309FF0747418811867CB4A81B0BC /* FormSectionDescriptor.swift */, + 1371CB007C4703ADBB046374DD799D44 /* FormSegmentedControlCell.swift */, + 7D7C14FEC5F42750CFF7801E2502AA30 /* FormSelector.swift */, + A5D054DB817811112B3951BAA5516B85 /* FormSelectorCell.swift */, + ABED8087C7A90B3FD277BAE0632749F8 /* FormSliderCell.swift */, + DF98451C4B15976BDA23D038EBF6A0EC /* FormStepperCell.swift */, + 26D74751413758177B3A96C50FF7FF7D /* FormSwitchCell.swift */, + 7B5056278F8531591B36DB9DB2654F5D /* FormTextFieldCell.swift */, + 4F3D1610EF8189FF2768299FB5504646 /* FormTextViewCell.swift */, + 2BEA6BEF99A18E7226D403A8BC1F4837 /* FormTitleCell.swift */, + 26B8BFBA5B3F70CF09022BCF57C36C70 /* FormValueCell.swift */, + 5B8615B87DA0E29530C8BE4B47E2D4FE /* FormViewController.swift */, + 42205DB17ED33C115B061F58407A7F39 /* Support Files */, + ); + name = SwiftForms; + path = SwiftForms; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 0F75DF6C7C5F002280EC53F48E80B587 /* Frameworks */, + 3DCA43ED9745C07120606066B8EEEC20 /* Pods */, + ECE75CA4E7E40274859412AB3EC76863 /* Products */, + 1D9D3DC7748BB6D45C201E8576C530F4 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 7DE5F80371BD26722753792B9342F074 /* FirebaseAnalytics */ = { + isa = PBXGroup; + children = ( + 26F6FFAADD8EBDBE1789C5EBDF9FF5D5 /* Frameworks */, + ); + name = FirebaseAnalytics; + path = FirebaseAnalytics; + sourceTree = ""; + }; + 7EFEEDD91F2B5950C9F07F344BAFC504 /* iOS */ = { + isa = PBXGroup; + children = ( + 5F891930020EE03609EADEDCA0FD6F6B /* CFNetwork.framework */, + 26E81988256AD84DCF55B9D84CAF1F27 /* Foundation.framework */, + C24FC54E82667CD883433C507452C248 /* MobileCoreServices.framework */, + 8CD5C008865F5A9168D53CDA45E6740F /* SafariServices.framework */, + E17134467E8954E9AF37025460CAB049 /* Security.framework */, + CB57BCF1E73C7B8A4B2CAE6F512FB8A5 /* SystemConfiguration.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 81E4053A069D2B42C612892AE9755D27 /* Pods-My MindUITests */ = { + isa = PBXGroup; + children = ( + 33559F44AC95540C2B694C8E23DE8148 /* Info.plist */, + B1E8384121EEC4BAB5A9C4A3B415D4E5 /* Pods-My MindUITests.modulemap */, + FDC169456A740BDFC932E5BF9A8BF8E4 /* Pods-My MindUITests-acknowledgements.markdown */, + 90299D1FF6A39A99EC23E75E3780825A /* Pods-My MindUITests-acknowledgements.plist */, + 2ADAA62C81FBD8B8F835FD758F63C282 /* Pods-My MindUITests-dummy.m */, + D85725E49DA341F05193CDB8F70FB05C /* Pods-My MindUITests-frameworks.sh */, + E5225ECE5C504283C697AD841E3C44DD /* Pods-My MindUITests-resources.sh */, + 42561C54B242579DF60913AD632DCB9D /* Pods-My MindUITests-umbrella.h */, + F8482E2E1DB4B525FF0826BAE0A61D59 /* Pods-My MindUITests.debug.xcconfig */, + 50D59C3FF3C181DB023918A1E27B460A /* Pods-My MindUITests.release.xcconfig */, + ); + name = "Pods-My MindUITests"; + path = "Target Support Files/Pods-My MindUITests"; + sourceTree = ""; + }; + 85C13620867B9272E8DBB969552F87A9 /* Network */ = { + isa = PBXGroup; + children = ( + 209C44D7A6CAF9D909AE34A0B3351B8E /* GULMutableDictionary.h */, + D3BF55E62435B01E8C350625673407B2 /* GULMutableDictionary.m */, + 8762AF452D56EBD17C7FA8105C46E226 /* GULNetwork.h */, + 9A41AF52719C366C4E6C2ADA6A8368CD /* GULNetwork.m */, + A70BEAFA51CAAA238419AD526C3A2A20 /* GULNetworkConstants.h */, + 24EAD08A106190E74699EE263115EA87 /* GULNetworkConstants.m */, + 4246B1BF52A26AE14B7A2194FA5E3F47 /* GULNetworkLoggerProtocol.h */, + FB339759EDEDCBAB839541CCC515B825 /* GULNetworkMessageCode.h */, + F1605E61657A7435C9C2AB1893D5E9F9 /* GULNetworkURLSession.h */, + 5F1A41B7E7B1BF73570D4029B7CB70B6 /* GULNetworkURLSession.m */, + ); + name = Network; + sourceTree = ""; + }; + 8B6136160A92775C66650F66F58E7D4B /* Support Files */ = { + isa = PBXGroup; + children = ( + 11273FE951B7033B10D1561060CD8732 /* Info.plist */, + 8CB4ECDE1DB0FA76A4986D8BD55DE75B /* Protobuf.modulemap */, + D32F70B25D7F29D35CFA300BD1BAAE9E /* Protobuf.xcconfig */, + F3CD7429816330A075E23E1CD8A04B36 /* Protobuf-dummy.m */, + 1336CDE7D47BE2947E359E422605C9A9 /* Protobuf-prefix.pch */, + 35E440DDEB88ECB524E3C40C8A379E1E /* Protobuf-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Protobuf"; + sourceTree = ""; + }; + 91ED4E586138A156451D34CD741921DE /* Frameworks */ = { + isa = PBXGroup; + children = ( + 0E9F7376073BEEE255DDF4BEB5C606F9 /* GoogleAppMeasurement.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9A77C0FFDBAE19797B1DF37B4DAAA5C1 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 9F8AF4D22A979411839BEBC0704E14EC /* FirebaseInstanceID.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9E25FC32485114B028E8FFE545289D55 /* Support Files */ = { + isa = PBXGroup; + children = ( + 35465F173726C8791C690CAA5F588804 /* FirebaseDatabase.modulemap */, + D1D80F314DC9DFCAF4DF1930A7FF0432 /* FirebaseDatabase.xcconfig */, + 027F5F2720277F21E85206247776964D /* FirebaseDatabase-dummy.m */, + C08FC41A4A7E8D144554D360A843190E /* FirebaseDatabase-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/FirebaseDatabase"; + sourceTree = ""; + }; + 9F107BD414907565B0964046717DA504 /* Logger */ = { + isa = PBXGroup; + children = ( + BE94296B133418A27910B00D5294FF16 /* GULLogger.h */, + 636106B60C9506E961ADC79797A5739D /* GULLogger.m */, + 44B9DDFF12FCDEFFDA1030DE1B15DA23 /* GULLoggerLevel.h */, + ); + name = Logger; + sourceTree = ""; + }; + A0B2BADB8D528CA49E6F669EAC9F61F1 /* Support Files */ = { + isa = PBXGroup; + children = ( + F08B3446D2D7E79BDED0E749BE1B104A /* FirebaseMessaging.modulemap */, + B9C0F3D003CEE3E5CBD1B6E5C94D1702 /* FirebaseMessaging.xcconfig */, + 1B6C2A21CF5F46F68A65914721B4BC48 /* FirebaseMessaging-dummy.m */, + 8F2B4DAA5BB46220C05E787322CAE960 /* FirebaseMessaging-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/FirebaseMessaging"; + sourceTree = ""; + }; + A3E8C2DDF092554068F18EE61CB4DD08 /* Support Files */ = { + isa = PBXGroup; + children = ( + 4B3CE5E9EDAE6CD0767391FA890B04E0 /* Info.plist */, + 04C06DA974FBB726CBB34C76008CBC29 /* nanopb.modulemap */, + F6680C23E17FDEF739AE9C28CE584837 /* nanopb.xcconfig */, + FED3152358EC24AC1254184016912802 /* nanopb-dummy.m */, + 1CD3422CDCBB98E652719FF98E60523E /* nanopb-prefix.pch */, + 2810E3E1AC8BFA36AB5702CEF85BEE34 /* nanopb-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/nanopb"; + sourceTree = ""; + }; + AA120728779E91B4C3EFA571A3DBAEA1 /* GTMSessionFetcher */ = { + isa = PBXGroup; + children = ( + 3439E5262F178D1F9B4A066615F6D693 /* Core */, + FD063AAB19B259A1887FCB30B707043B /* Support Files */, + ); + name = GTMSessionFetcher; + path = GTMSessionFetcher; + sourceTree = ""; + }; + BB4396FEF0033C1EED9685135AC4A16C /* Support Files */ = { + isa = PBXGroup; + children = ( + 4D1382328266FF86D9122C8BBD6C0C3E /* GoogleUtilities.modulemap */, + 1E8627B6D324325882201B629A767ED8 /* GoogleUtilities.xcconfig */, + FE4B7054E146828925FC005DB56E8904 /* GoogleUtilities-dummy.m */, + 7FBFC1F7E73045485048A8A2FE6C9932 /* GoogleUtilities-prefix.pch */, + AE61849A6A393E9FC1EB0A2778E14C73 /* GoogleUtilities-umbrella.h */, + B6706057DE50E1D3EE4A4008BC96310A /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/GoogleUtilities"; + sourceTree = ""; + }; + C3358E849786CD6629639EFD7EA91A04 /* Protobuf */ = { + isa = PBXGroup; + children = ( + 086B92F32AC12F7847B682F04095440D /* Any.pbobjc.h */, + CC6ADBF7520BE4C24E99069E832C1E44 /* Any.pbobjc.m */, + 05DE1CCF193E0BF6A385C79D1F31920F /* Api.pbobjc.h */, + 31C4337E4E578887B076F5E47A449DCE /* Api.pbobjc.m */, + AEDB6F9859D5D740703FECC548FF4DB1 /* Duration.pbobjc.h */, + 21F133E7C0A2FCB0E03FE38C1D386479 /* Duration.pbobjc.m */, + BC564D3F08952BAF72AA3D8FA599A413 /* Empty.pbobjc.h */, + 501C43E7B305FE3D8E1CDC5276D26E98 /* Empty.pbobjc.m */, + 82DF20A0A666925390FA680456D04F84 /* FieldMask.pbobjc.h */, + 89F5B99A9E0786C553D21D862D2B5827 /* FieldMask.pbobjc.m */, + 3BA38BF03D131A8C606CB78AC6CB85DC /* GPBArray.h */, + 4B850F7DC474EF9A15F3ACEAF70750DA /* GPBArray.m */, + F3084FADD51BE52F8FAD4EDDF5886E44 /* GPBArray_PackagePrivate.h */, + 7D10BD44F431CB676BA0F99531C372EC /* GPBBootstrap.h */, + 056AAEE5687F136583F2D9487DEEA595 /* GPBCodedInputStream.h */, + 634AC4F4C75AE1D5C975FD26D60B8E3E /* GPBCodedInputStream.m */, + 13E8E20280A59FBF3E16ABB61C7F1857 /* GPBCodedInputStream_PackagePrivate.h */, + 16ABBC1602669EF624F71C7D2874005A /* GPBCodedOutputStream.h */, + 54A71EF90151DC4A91CDE20EBE275C1C /* GPBCodedOutputStream.m */, + 80F60B07C2849F8B4E6E25DE44C5FB6E /* GPBCodedOutputStream_PackagePrivate.h */, + C3FFC4ACEC5591F801B1902AB763DA62 /* GPBDescriptor.h */, + A80F78145127A307E9C1096BA11DA24F /* GPBDescriptor.m */, + A096BEDB7EDE65D27A114DBD7937A0BD /* GPBDescriptor_PackagePrivate.h */, + 0547C44086388302572F121590BFF048 /* GPBDictionary.h */, + 672F641C8ED1591333E51751747D9051 /* GPBDictionary.m */, + 5FB080F12F054F57F892AECEA7DFEE41 /* GPBDictionary_PackagePrivate.h */, + 9EE4F1D9B84C172C41E721B213F1707A /* GPBExtensionInternals.h */, + C5D5E994D8F0EFDF52C43C5BA09B95A2 /* GPBExtensionInternals.m */, + E83395DDC37AB2B43925CB22AB834320 /* GPBExtensionRegistry.h */, + FC9BEE8EF9E33D02A8E5B842C4EC1747 /* GPBExtensionRegistry.m */, + BB096EC76A1266B8C0F8E2ACC1A31ED2 /* GPBMessage.h */, + 166AEA29274E16405F538B6E3FB9F341 /* GPBMessage.m */, + 6D031DF463461821CD42F1C393E912D7 /* GPBMessage_PackagePrivate.h */, + 624733EE470333F41A1A1BCC618446EC /* GPBProtocolBuffers.h */, + DE84738710FAC6778EC1FBE3B5235F5D /* GPBProtocolBuffers_RuntimeSupport.h */, + 34A437CCB33E71BF0316EE12908859A5 /* GPBRootObject.h */, + B8B02B5F674C3C2DB98EF004508CFCC3 /* GPBRootObject.m */, + 93B79A48B8E85E3CEFE8C0D22E6F043F /* GPBRootObject_PackagePrivate.h */, + D6BB61D1DB5D35D8FCF2FAC65BB2D959 /* GPBRuntimeTypes.h */, + B6032ED1761DE16D733B707DC6D72F5B /* GPBUnknownField.h */, + 9A3FD15082F1A9ABE77ED609F0DFF1CB /* GPBUnknownField.m */, + 0B5803208593B4D179BEC1EB11FFC53C /* GPBUnknownField_PackagePrivate.h */, + EC2F40DC4BABBA1C34D6609803FED9F1 /* GPBUnknownFieldSet.h */, + 390DD1B08C74A9F68476B754216839F8 /* GPBUnknownFieldSet.m */, + 55151CA7726A3419117D3B576C43A54B /* GPBUnknownFieldSet_PackagePrivate.h */, + F80CC5E45B9D60B0D5733364ECA9F9DF /* GPBUtilities.h */, + 95C84D68BD7EE91EDBA35DD0F59B13E2 /* GPBUtilities.m */, + 4E26ACE066B49256AB80223CB1785409 /* GPBUtilities_PackagePrivate.h */, + 9AEDC13798C85C59C79C212EB9A65441 /* GPBWellKnownTypes.h */, + 1175E03AEA34F51B8C8D46A8448670C0 /* GPBWellKnownTypes.m */, + A338397206C34CAF5CBB48E4D05DCD6D /* GPBWireFormat.h */, + 949FB977FA39EFF38D2F6B5508DF4AAF /* GPBWireFormat.m */, + 71B41FCA331929B285069B056D11187C /* SourceContext.pbobjc.h */, + 9F79D0ADD782AC78C79D540D0AB8B9EB /* SourceContext.pbobjc.m */, + D897AF51D9D53A189E407BC729E743A8 /* Struct.pbobjc.h */, + EBF70370314641E65536A91D17604E7F /* Struct.pbobjc.m */, + B4288F3CD86EF1B904C5B60FF214940B /* Timestamp.pbobjc.h */, + 968C73940E1B097EF26967FA1146655A /* Timestamp.pbobjc.m */, + A88F71BC1A9F943C034BCC009810AD64 /* Type.pbobjc.h */, + EF22EB80F2D3ECF9EA4920E3DCDDFC51 /* Type.pbobjc.m */, + ED57FFADAE2E118F4B39FED169254F9B /* Wrappers.pbobjc.h */, + 8BBC26AF6B9C5D76177286CF09E095BE /* Wrappers.pbobjc.m */, + 8B6136160A92775C66650F66F58E7D4B /* Support Files */, + ); + name = Protobuf; + path = Protobuf; + sourceTree = ""; + }; + C5866185D2A06878CEEA1D425B48D8D0 /* NSData+zlib */ = { + isa = PBXGroup; + children = ( + 2EFCA2B98B8F29A0EC46C45E86B06459 /* GULNSData+zlib.h */, + F09277F67D2CA69E933081A31E0BE2F1 /* GULNSData+zlib.m */, + ); + name = "NSData+zlib"; + sourceTree = ""; + }; + C6309194E8E98243DA592750691DD468 /* FirebaseDatabase */ = { + isa = PBXGroup; + children = ( + 5A78F386367CAE629EB35C78D895997D /* APLevelDB.h */, + 02A902CB224C60C34D9D9D2D0E204BE4 /* APLevelDB.mm */, + CC590D92037B35FC414FF8BCEF4C66B9 /* FAckUserWrite.h */, + 3B7A4B008AB123043A89EBD792C8AF40 /* FAckUserWrite.m */, + D8D66411B1D52F4EEB26FA6AE6A04187 /* FArraySortedDictionary.h */, + F03EAA2EC81A15074DB6D1EA122E97C0 /* FArraySortedDictionary.m */, + F78F642663E7302B237D8578707BB7CA /* FAtomicNumber.h */, + AC38D0BF1D124FC816CFFBC68841C7F7 /* FAtomicNumber.m */, + 693C9B5BD6AC380C76B3E002A24AC9F5 /* FAuthTokenProvider.h */, + 0E52BD389E6CE1A1DA968B1065FE7CEA /* FAuthTokenProvider.m */, + 5E738E7BF1FBC0B364B61BD03515B68F /* fbase64.c */, + 0C5EAA248DD28CE7903CF85278DCF244 /* fbase64.h */, + 203AD3FF7A567A2E94E4B935B88C0A08 /* FCacheNode.h */, + 15436BAF73F24A26CBCCCE13B2C7A5D5 /* FCacheNode.m */, + 3463542860D4D784D0B8FE1164F16844 /* FCachePolicy.h */, + 8AC604D9BBD33F425A70127321354580 /* FCachePolicy.m */, + 74E740E1ED09434A0A93BA9D4953AB65 /* FCancelEvent.h */, + 618C547333D8EAF01B8180DECD81E059 /* FCancelEvent.m */, + 342B0B60E0420CB2ADAE937A53F52CEC /* FChange.h */, + DF89E6C6615E5188CAC12F41A08EA8E4 /* FChange.m */, + A69039FCDFBA2D22C1736491CC27B108 /* FChildChangeAccumulator.h */, + 4AEF839E0EBB783AE6036DF684293321 /* FChildChangeAccumulator.m */, + 044D7841EC141A247D182D1B31F071D8 /* FChildEventRegistration.h */, + 658A768CC068B2D7E13BF84FFC821C7D /* FChildEventRegistration.m */, + BD4117C893A97D98EE31E12226EB41F9 /* FChildrenNode.h */, + DC9B8460FA63820AFA6854A35DA829C6 /* FChildrenNode.m */, + E9F29370AA19CCEBB83FD2748FE606CE /* FClock.h */, + B3F673C51D33F552AA826578B448AF3C /* FClock.m */, + EEECFB49B1C1890C57ED844291FCAD69 /* FCompleteChildSource.h */, + 64D9C3082504A3C076123EC5A427666E /* FCompoundHash.h */, + 3C0CE893E96EBB13E04CA4D4B62030BB /* FCompoundHash.m */, + 9A0C73503D3C9E121AEAD3E5D9965CB2 /* FCompoundWrite.h */, + 31D63EE25A257F5309562EBE3F5BDD37 /* FCompoundWrite.m */, + 3AD4D1243F862167904648922BDAE04D /* FConnection.h */, + 4109A974CBD18486C940B1F1487720A0 /* FConnection.m */, + 0981E2FBA71DA3248061103B90F82F5B /* FConstants.h */, + B462ABAEB07A7435FB7510B120702773 /* FConstants.m */, + 7568B7BB638B453805A7B08112D98D8E /* FDataEvent.h */, + 171F6C7813B27B478AE78B6579E4FBAA /* FDataEvent.m */, + 43CFD5E85EB4EFD2F6AB4506880B8332 /* FEmptyNode.h */, + AFD8CDB02D4D4C89C49C96F058E1B224 /* FEmptyNode.m */, + 7971586793756023D72E620D4BE9E456 /* FEvent.h */, + B5A15BC3357E674F08C9999C7D329D3D /* FEventEmitter.h */, + 1EEE2FAABA3D4CDED41BA149DDCAAC86 /* FEventEmitter.m */, + B057F909F1A17282CBA960CE4A2237B2 /* FEventGenerator.h */, + B323034EAD6CEDCD35A420C6F0EA58C4 /* FEventGenerator.m */, + F5F63D1EB7FA70A254BE597E678D416D /* FEventRaiser.h */, + F9CF71EEB7AF86F89B8AE4EE689AC486 /* FEventRaiser.m */, + E7DD9769669DB7F9E67FC275C3FB7C4B /* FEventRegistration.h */, + 0C7859524A87E234251F0B720F52F719 /* FImmutableSortedDictionary.h */, + 3BB0B1F9F39C57357D2350296EAA5E53 /* FImmutableSortedDictionary.m */, + CCF7C96D9FF6B74D1BB5DD455A95B971 /* FImmutableSortedSet.h */, + 07084E38FA564A667FC64E1BA854553D /* FImmutableSortedSet.m */, + 334A73053CB07EBAD403B0A20B0FB4D1 /* FImmutableTree.h */, + 7DC9FDF211772BFF5911D9544841884F /* FImmutableTree.m */, + 9A55D1EDA7B8213E6AEBB17AE65D2954 /* FIndex.h */, + DAB331FBC7C4E444D49D2095E2B10937 /* FIndex.m */, + 9E84074B8CAC11CFC16E8F61FCDA55D0 /* FIndexedFilter.h */, + 070A02016BB493B1197A81FFEACCC360 /* FIndexedFilter.m */, + DFF02281941C12B08E8712F2DE9DC391 /* FIndexedNode.h */, + 68EDBB86127032AD3CCD427465F5057A /* FIndexedNode.m */, + 0CD5B29065B8C08D5397404B28BD7CDE /* FIRDatabase.h */, + B2A3E3AFFA8F8C86271BA4D6C7F4C875 /* FIRDatabase.m */, + B9B72DC800D477FEA2AC16E17CC60AE1 /* FIRDatabase_Private.h */, + BE0B0BCBB4CAA4C8D82EF4D06A6D1CA9 /* FIRDatabaseComponent.h */, + 3BDBF6A6577932307CBAE680E3C2D0DC /* FIRDatabaseComponent.m */, + EC5CE6854B764CF987743F870A9DD509 /* FIRDatabaseConfig.h */, + 2F023A3AA7B317ABDDFF07E64B3FFE45 /* FIRDatabaseConfig.m */, + D9356AFA47E58DAC25375A606AEBDD04 /* FIRDatabaseConfig_Private.h */, + 368E447E635FC44C3CA4A0F09D50292A /* FIRDatabaseQuery.h */, + 0B51883B5AC0F922A2308C19F60F9664 /* FIRDatabaseQuery.m */, + 7871920E4D29C4D70144578BF057710F /* FIRDatabaseQuery_Private.h */, + F5A2BF62391ECF98F03EB919C5C2380A /* FIRDatabaseReference.h */, + 03EDFA99E6ADFC8587F19A0FD5C27F2A /* FIRDatabaseReference.m */, + 7C67A508BEE66D05F3D060B80EB08B92 /* FIRDatabaseReference_Private.h */, + 0933AC24273A3B8D18961DB556CCFFED /* FIRDataEventType.h */, + A99F776AB4854965623E2157BE844140 /* FIRDataSnapshot.h */, + 12CCC1B4271DDA631C361A6A36F607BC /* FIRDataSnapshot.m */, + 9F156EFA0C6D1FF858F72E0773123B1F /* FIRDataSnapshot_Private.h */, + 4316D686D98DA93A0ADDA9AB857CCFEB /* FirebaseDatabase.h */, + DD8F80849FF142E6CEA8C80A9429B455 /* FIRMutableData.h */, + 1458408B7F7426DFEC2029E33DB82575 /* FIRMutableData.m */, + F13F2E644801D0E3C822FC88E1B1FA6E /* FIRMutableData_Private.h */, + EA86C1C2E7F7812ADB29376757F6DD4F /* FIRNoopAuthTokenProvider.h */, + A383681CA86AE1040605A9AA1AE4E78D /* FIRNoopAuthTokenProvider.m */, + B1FF1C0990CE6DF70B31DBC7140BE404 /* FIRRetryHelper.h */, + B0B5A5553CFB4456F7BC8E2B97CC0644 /* FIRRetryHelper.m */, + 786FC9011A3F7E09EB395D9E4BAC2FA2 /* FIRServerValue.h */, + A3A6CAC7709D278E80B3D80F187CEE79 /* FIRServerValue.m */, + 8F92B73F81BC9043DF09D74636383BD3 /* FIRTransactionResult.h */, + 56DBAB0E527B855D6B1FEA68A8CF3582 /* FIRTransactionResult.m */, + 0E35D7AE2EB7FA03E603D90E7EB4943F /* FIRTransactionResult_Private.h */, + DC5BCCD19D83503611CAFE7CCBF2D059 /* FKeepSyncedEventRegistration.h */, + 080DC43BFB3FA09A4DD2E260312C57F2 /* FKeepSyncedEventRegistration.m */, + 6BA5FFAECDA46681242C8C8C12B8DF75 /* FKeyIndex.h */, + 502015322F13E326A360FF358E29B946 /* FKeyIndex.m */, + CD56393A1C061A90D9EADCAE84B22F19 /* FLeafNode.h */, + D1FBF0A9EE42AF399B2B94CD6809F898 /* FLeafNode.m */, + 4B62BAF73F96F237E93C91E8FDE1A124 /* FLevelDBStorageEngine.h */, + 1F867F22C2B7BAAA7F6FB2880B592586 /* FLevelDBStorageEngine.m */, + 47FA58B556C9302949CF390A13E37DF8 /* FLimitedFilter.h */, + 3DAED226313360A65EAC8D21A34E31EB /* FLimitedFilter.m */, + DEED9B0809AD0BCE53D0943BD7BCD19D /* FListenComplete.h */, + 4F0FDD548581BEE2026C81C115C042B5 /* FListenComplete.m */, + AA51B0829287BFC68D2DA3B4440E6AF6 /* FListenProvider.h */, + 2E2BB3682A63E5E8457BE4392979C216 /* FListenProvider.m */, + C9ADC47D30FF0AAF24724A272E5DEBE8 /* FLLRBEmptyNode.h */, + 09395751F30ACA695886327117B5E571 /* FLLRBEmptyNode.m */, + 1F5AA5097DD6969A0A996849D3ADA0FE /* FLLRBNode.h */, + 08D738374880F7FA49B1EAB508EDEBD0 /* FLLRBValueNode.h */, + 82FDABA5276C7AE2C5B8E81051C68E2F /* FLLRBValueNode.m */, + 5DD690A210A0BA32F0BF15C1E07B4A65 /* FMaxNode.h */, + 246FADA5C8D2648540D64611F12C83F1 /* FMaxNode.m */, + 299DF18554F4A28DFE1C9CEF8D10FDD5 /* FMerge.h */, + BE58957B596510DF2E8953AC74AD5FE3 /* FMerge.m */, + E70889143006716935C52FEB99418BDE /* FNamedNode.h */, + D1BCA22721EC82476AD1ECBFFC47FDE4 /* FNamedNode.m */, + 2C40238EAA192A9251A946077405ABC0 /* FNextPushId.h */, + 3C9B5809B81588128804C82CC7C0A448 /* FNextPushId.m */, + 60DDA174CF0B3BB875E4D2CAF65B71EE /* FNode.h */, + F8EEA04BA35D6AA6DDE2D44BA30C6527 /* FNodeFilter.h */, + EE07AE37AF13904CAE7EB4AFEA96A9DB /* FOperation.h */, + AE72ED507BFAB70E74F0185212CFA468 /* FOperationSource.h */, + C8C7086328E78F3238E42C4FFFF6C84D /* FOperationSource.m */, + CB75ED76F6A5CB316ABCE459B35449B1 /* FOverwrite.h */, + D5FA71E496F7AA410D948D768C02A01C /* FOverwrite.m */, + 471881B25F65AC42DDD5CF446E5F8504 /* FParsedUrl.h */, + 4775A6201BD2BC8E8E2FA8486EF330FB /* FParsedUrl.m */, + 44338CA1F8AA10479C391E3E8D0E9C1C /* FPath.h */, + EBACD6FF2BAF6C98C1E9D96D22E6E633 /* FPath.m */, + 58487CE27CDAA3A239CAED5DA382A40F /* FPathIndex.h */, + FC7C460601A2517E74B240EE306DF439 /* FPathIndex.m */, + C6EA16B802C4C8FC4C6BE6B9A2CBCCC5 /* FPendingPut.h */, + 34FF34F16BEF644F7E4BB840CB508AD2 /* FPendingPut.m */, + 94CB3AC364A3701DC592D22BDF8D4D64 /* FPersistenceManager.h */, + 23FC93A0EF861393C6EEE18DF78305C4 /* FPersistenceManager.m */, + E68A2AA637BDE4FEB94C7CBB17526C5A /* FPersistentConnection.h */, + D4DE91FD1133887F4AAC325B2A16F0FC /* FPersistentConnection.m */, + E4EAF32030EF5CA9819B3EE91BF69845 /* FPriorityIndex.h */, + DEE1195481C3E699963E947E9FDAD7EA /* FPriorityIndex.m */, + 8E6B71DD9A246127CC984BFD6DB3B66D /* FPruneForest.h */, + 11796741226434375F93ED3BA8C0A741 /* FPruneForest.m */, + 4AE4970E0E898EB674A647B25B6DBD64 /* FQueryParams.h */, + C1FAF04CD4B2CBB223911ECA4F6BD75B /* FQueryParams.m */, + 0D611DA4A6D467F635AF0C5C09F9FB74 /* FQuerySpec.h */, + 7AD846363197EE2C3BD4CA30EC8D8C44 /* FQuerySpec.m */, + E2DC2EB959470FCEF39EC7C80F5316B0 /* FRangedFilter.h */, + B1FC0F5D6E265B194170509A9025EED7 /* FRangedFilter.m */, + 39A633CD466937034BA28BBFAC639020 /* FRangeMerge.h */, + 17CD745C9A40F6E344672C2AB3522EE4 /* FRangeMerge.m */, + 3B370A68E87D4F28213B16C705CC3A44 /* FRepo.h */, + 2DDDD71E6DB015FCA8B621580ADC5452 /* FRepo.m */, + EB3595599A6D697943276F3488DD6BEC /* FRepo_Private.h */, + D940987A9FD15F075D87E6F596C88350 /* FRepoInfo.h */, + 127AF1BC36CC21E5614940AA4087D2E9 /* FRepoInfo.m */, + DBEBD39CF1E6349AD5DA85B84BC7DFCF /* FRepoManager.h */, + 1645988A40396F6E30316B284BD585E5 /* FRepoManager.m */, + 5C2A3940C1CF640AD9EB12D78F0AEAF4 /* FServerValues.h */, + 4E654E9A462330D3F03252E972E0DD93 /* FServerValues.m */, + 309BB9290E966976A199C728D934130A /* FSnapshotHolder.h */, + 50630886A093E6270164CC7ECE54E54E /* FSnapshotHolder.m */, + CB84AAF13B2D3F5576311B23B58E94EF /* FSnapshotUtilities.h */, + A04D5EAB5D26B05C5CD5EED00FE954F5 /* FSnapshotUtilities.m */, + 02867E76AFD212132A577D295F36FAFE /* FSparseSnapshotTree.h */, + BD91CFB92703A5598BBF2CC6E38F9678 /* FSparseSnapshotTree.m */, + 919BAE70A809B028A03EE6536029F65C /* FSRWebSocket.h */, + 0C133B09CE3EB5E249AAC9A970FD6D8C /* FSRWebSocket.m */, + 1B1B2B22C6DC5738A70F2F6D590BEA8C /* FStorageEngine.h */, + 6D95EAFED5C6BABDD29651946338BA3C /* FStringUtilities.h */, + AE210630843BC4F35C085C2F50BD731E /* FStringUtilities.m */, + BDA8D286B82FAEEDBA4BB4A834E41412 /* FSyncPoint.h */, + E8777028A6004E068FD4E41BDFD48861 /* FSyncPoint.m */, + C3276A2BFA726F605D0020C6E3F30F22 /* FSyncTree.h */, + 3BB0171D3D054B9A887BDABC219FDED3 /* FSyncTree.m */, + 2073FD9AA334017E0E90D8197D3A84B8 /* FTrackedQuery.h */, + 8C931CB859E88BFAED40B1C16793FB9A /* FTrackedQuery.m */, + 4A4825168FBBF46A0CF64FF8808816E3 /* FTrackedQueryManager.h */, + 0904C46A7FA089C66B87D70AF0688AA8 /* FTrackedQueryManager.m */, + 999ADEBF7B61A4065079C381CE6B7DE2 /* FTransformedEnumerator.h */, + 28C219F26C922F496FB2CDC879FA9079 /* FTransformedEnumerator.m */, + CECD1A2BFBF0E479DFBB774F092537C4 /* FTree.h */, + 614B59B42151155D33BBF932D5542E46 /* FTree.m */, + F36514100428C5491F827F9CB81CEA6F /* FTreeNode.h */, + D4B06DF0BDF7821D048B9478C5F9D97B /* FTreeNode.m */, + 60F0F5A859C55E91E94D4D5F10B28B92 /* FTreeSortedDictionary.h */, + 160B2A098D6BE7E4FB1B11DD186189BB /* FTreeSortedDictionary.m */, + 78440266C0C83884693EF81EF27A2251 /* FTreeSortedDictionaryEnumerator.h */, + 7419C5FA3F1E39B79BC98148F8B303C2 /* FTreeSortedDictionaryEnumerator.m */, + 1A80624208D997D30C2C97FF658187DF /* FTupleBoolBlock.h */, + 47E32935FDCB1ACFE19F4A621AA5D7AF /* FTupleBoolBlock.m */, + F58D16C5FBEE3D3C9EE7D4F75929C633 /* FTupleCallbackStatus.h */, + 39F2F32A7DA93B047FC2CD83E02E59B2 /* FTupleCallbackStatus.m */, + E921EE2F6E50B2B950BD43A6A6862162 /* FTupleFirebase.h */, + 8DDFE81B108DE6221D7C65724942FB0F /* FTupleFirebase.m */, + DC4966A882229EFA017144185FF21757 /* FTupleNodePath.h */, + 65ACC8103EBC8FC94891C616DFB37168 /* FTupleNodePath.m */, + E332EF6637191BA88B5B349CBC134581 /* FTupleObjectNode.h */, + C52EC904B0F3150B87E3EA668BEAD512 /* FTupleObjectNode.m */, + B5C3F4B78DF3673687E6F9E9D5672781 /* FTupleObjects.h */, + 8200BDBCECE4B63C77D401E6C30EF965 /* FTupleObjects.m */, + 7404327BB8BA8D0F2BE2231D7D1349BF /* FTupleOnDisconnect.h */, + CBF3C805C4BA2351F7663FC5BBB51446 /* FTupleOnDisconnect.m */, + 2FF4A55D674F3F971478CE8C9D07E621 /* FTuplePathValue.h */, + D81F978D0BA4662DD96F6F62D35FC8C3 /* FTuplePathValue.m */, + A47C3AB0A9B76782489F5945F55343BB /* FTupleRemovedQueriesEvents.h */, + 951C9C763F8BC13991737A8CD8FFF4AA /* FTupleRemovedQueriesEvents.m */, + 2BF6BAA9454971A57DABB6CA9CD25AD5 /* FTupleSetIdPath.h */, + B48C76A23EF0571C6D82D31226FE2B77 /* FTupleSetIdPath.m */, + EF2565BF522E6ED879327B1704A108DC /* FTupleStringNode.h */, + 2C6CDE0E1371445EF3780F7C3AF3CA55 /* FTupleStringNode.m */, + 73E2B0654C8EA0F00AB43543CBD124F7 /* FTupleTransaction.h */, + DC9216026608FFA44A02C2E8BF9A9E3C /* FTupleTransaction.m */, + 1534655F96C2C7D96E3632B7C1979994 /* FTupleTSN.h */, + 38121C21810D6FCA9108041FC4F8FEDA /* FTupleTSN.m */, + E7FB12B47C9D60E0AF8953271C31107A /* FTupleUserCallback.h */, + 69B1781DA481AC22CFA714AD4D223D72 /* FTupleUserCallback.m */, + BC4A443A1DF1810B7A9803C462DADFEB /* FTypedefs.h */, + 8D26ADA472AEBC9DE9C44BEB18259C0E /* FTypedefs_Private.h */, + CEE1E52025454E30EC0E6663FF8E2467 /* FUtilities.h */, + A3AF2B4F082D56E9F3B5C36EC9CA1ACD /* FUtilities.m */, + E4ECDD1348A475B5ADCE6B521AF2DAF0 /* FValidation.h */, + 1929AA13F6B9C086778B2797199BBB2B /* FValidation.m */, + E5C19961FA70611535C5C36236F23D9C /* FValueEventRegistration.h */, + C647DA2D0CD5FB0B7BF0E68188DC9A02 /* FValueEventRegistration.m */, + EA129F6051473738DE8F6680613B7386 /* FValueIndex.h */, + 27D9867266FC937A80456C5B2C28AF13 /* FValueIndex.m */, + 9D6AD1B68D19CD2237E034D672CD3455 /* FView.h */, + 52989DBD560D819C3DAE5CD912033DD8 /* FView.m */, + 7F9F88FADC98B9224D1E76814149FA28 /* FViewCache.h */, + CF3A590F142F7E04CFCCE40F7894F3ED /* FViewCache.m */, + E0216286990A5FC34839E3F80B8D6C96 /* FViewProcessor.h */, + 757B37187411893E58EA0016D7EA32AD /* FViewProcessor.m */, + 880A5D3DF4E4D6D8C3FE7C96B0B2BCAA /* FViewProcessorResult.h */, + B6553318BF52F3BEAC785032DE0A7878 /* FViewProcessorResult.m */, + 3A76E7B0DE462D4F237E12CB0F74930D /* FWebSocketConnection.h */, + 95F2B1C34657348ECD42CC43E037DC68 /* FWebSocketConnection.m */, + A8679585BD7F5289E37359EA461A0848 /* FWriteRecord.h */, + FE464DE5F2ADF86CCC4FBA2E5749B1F9 /* FWriteRecord.m */, + 977804E7E131595293C9F752303CEC88 /* FWriteTree.h */, + 275E67D0B7860BEB886BA56746C86448 /* FWriteTree.m */, + FEC70A46FDF74AF507252CDF69F4337C /* FWriteTreeRef.h */, + 4DE03466C662D0024DF6BEFBB58CB658 /* FWriteTreeRef.m */, + B950CCF786F09E70D271B41775C47615 /* NSData+SRB64Additions.h */, + AE8A0C83E51D1224B0CFB2B9112CD50F /* NSData+SRB64Additions.m */, + 9E25FC32485114B028E8FFE545289D55 /* Support Files */, + ); + name = FirebaseDatabase; + path = FirebaseDatabase; + sourceTree = ""; + }; + C6DCA632A0241403E8C2B63C226E3FDE /* GoogleAppMeasurement */ = { + isa = PBXGroup; + children = ( + 91ED4E586138A156451D34CD741921DE /* Frameworks */, + ); + name = GoogleAppMeasurement; + path = GoogleAppMeasurement; + sourceTree = ""; + }; + CB24FEA7C77F0ED6800218317257EF06 /* FirebaseStorage */ = { + isa = PBXGroup; + children = ( + 4A0E3FCADDEE6AF41C98BE9C52E8C2D4 /* FirebaseStorage.h */, + 4FB98B53519A3F306A0403D5C63DEFAC /* FIRStorage.h */, + 3D44B58D46428E682FE8499CC2C0604A /* FIRStorage.m */, + BF633D289C9053169D2324C32B3F5AEE /* FIRStorage_Private.h */, + E71A396EC91191A023047F9E295CDCC4 /* FIRStorageComponent.h */, + F6B33E27089631C018426D12DE3BF2B1 /* FIRStorageComponent.m */, + 449CF3BAB6CA50258AE9DDCCF5354BB9 /* FIRStorageConstants.h */, + 316D8A7A00F10D77D5E5B7F79B7770D2 /* FIRStorageConstants.m */, + 5383E534FCBF0988CDB5DE655E026D79 /* FIRStorageConstants_Private.h */, + 45163B0967987CC35BE8D9091891B40E /* FIRStorageDeleteTask.h */, + 28202CE327903B58CDB7331A14E79DC1 /* FIRStorageDeleteTask.m */, + CD292B336F5C12C67D9382555FB39F84 /* FIRStorageDownloadTask.h */, + 211B6DE1BBF8897513531B6D7D842C3A /* FIRStorageDownloadTask.m */, + 3EBE5619F4ACC24E1B1CE208BACAECC8 /* FIRStorageDownloadTask_Private.h */, + 338F8FAD90ACCD0679A61D9BF3376DAB /* FIRStorageErrors.h */, + CE0A99214530B0FAF71E7F69ADE4F9B5 /* FIRStorageErrors.m */, + 190C6A526425A5A9EF0976A2C466B402 /* FIRStorageGetDownloadURLTask.h */, + 2546E3E1838E0C58EBD972F9CB875E1B /* FIRStorageGetDownloadURLTask.m */, + 5C23BD54A2D7173A773BCF67F06B63BD /* FIRStorageGetDownloadURLTask_Private.h */, + 87B8DEE29C9DF557484295F12A135E87 /* FIRStorageGetMetadataTask.h */, + D56EDA2992910A82DF34AF0EDB0669B2 /* FIRStorageGetMetadataTask.m */, + CEA0478245F572D019A39A44DE52A3A4 /* FIRStorageMetadata.h */, + 789F71E8E85917ED0CBB539BF3DB75AE /* FIRStorageMetadata.m */, + 9213B9E77E41B0F09DE4A6DEF4605354 /* FIRStorageMetadata_Private.h */, + FDB044D43FDB91C9E18B19954C2084C4 /* FIRStorageObservableTask.h */, + 738805EF3840CA94F81C79BA9A95D52F /* FIRStorageObservableTask.m */, + E0B1B26588D39F632E7FAE741113153C /* FIRStorageObservableTask_Private.h */, + 37516AA7CF7594EF2A97EECB3F648BC3 /* FIRStoragePath.h */, + 2D9B0086B87D0C228A92B242FCD33B3C /* FIRStoragePath.m */, + CDDE3270485F6BA958F0E5A5253C05C9 /* FIRStorageReference.h */, + AC39528D9EF5C627E843B230297D8360 /* FIRStorageReference.m */, + 360F34FFDB1C719C8DE28092E5639368 /* FIRStorageReference_Private.h */, + 880603C3679A606EFFF7E1252ED39621 /* FIRStorageTask.h */, + 682F99F9C42A5FE4D526C915C7792F54 /* FIRStorageTask.m */, + CE58A9D71591B0BDA8F839EF6D8E13F8 /* FIRStorageTask_Private.h */, + E317B12D5F902A2C6E951A9FCCC59530 /* FIRStorageTaskSnapshot.h */, + 904EFB6F9F30701EA342E10A83813F45 /* FIRStorageTaskSnapshot.m */, + 0EF8CB17A97DBCD11218204027BB21FD /* FIRStorageTaskSnapshot_Private.h */, + 379E5B5FBE6395CCCDF717529007F6C8 /* FIRStorageTokenAuthorizer.h */, + 5535B79D79A1DB6E12BED6FEEA04B485 /* FIRStorageTokenAuthorizer.m */, + BB4A6AB1B3EAD07AD843777C90166F83 /* FIRStorageUpdateMetadataTask.h */, + 2FD045A1CC7371C425615013DF560B51 /* FIRStorageUpdateMetadataTask.m */, + 102344473F65983D56F8C4612A41F57E /* FIRStorageUploadTask.h */, + 8583A2B8E76D50FAD075A623EF4D16DD /* FIRStorageUploadTask.m */, + D5EB1CBA1D1666D7B3560FAA3427A1C9 /* FIRStorageUploadTask_Private.h */, + C7B4E1AC707BFEC7671666CC0530312A /* FIRStorageUtils.h */, + 17B0C073D7E0610CB87572DA00D591D7 /* FIRStorageUtils.m */, + 4BB017215827D6A750B79B7C5BE87947 /* Support Files */, + ); + name = FirebaseStorage; + path = FirebaseStorage; + sourceTree = ""; + }; + CB80E732D1B59BC1BFD500644F76E62A /* GoogleUtilities */ = { + isa = PBXGroup; + children = ( + 3C2A3F24A3209A37991B966325EEC297 /* AppDelegateSwizzler */, + E873026CF11D0FD8EF2326591E3D2485 /* Environment */, + 9F107BD414907565B0964046717DA504 /* Logger */, + 1E007DA9363BD8C7AD6B460292D110EC /* MethodSwizzler */, + 85C13620867B9272E8DBB969552F87A9 /* Network */, + C5866185D2A06878CEEA1D425B48D8D0 /* NSData+zlib */, + 22BE2ED4240A362CBE3E6DDFA1EE4CFE /* Reachability */, + BB4396FEF0033C1EED9685135AC4A16C /* Support Files */, + F65A0434A74383C5704A0AFE3106CC42 /* UserDefaults */, + ); + name = GoogleUtilities; + path = GoogleUtilities; + sourceTree = ""; + }; + CF655F1E3635CC44708BD6E2C3BB86C9 /* FirebaseAnalyticsInterop */ = { + isa = PBXGroup; + children = ( + 3D1F68AB0DEB0CF2DB6829D440B69E95 /* FIRAnalyticsInterop.h */, + BC4C2E22EF2E783BAC029A803B491668 /* FIRInteropEventNames.h */, + 55F0AD247ED58C88A9CA3DFACE27D5B4 /* FIRInteropParameterNames.h */, + ); + name = FirebaseAnalyticsInterop; + path = FirebaseAnalyticsInterop; + sourceTree = ""; + }; + DC5AFC953EBD7FA261B9BB7B25ED5441 /* leveldb-library */ = { + isa = PBXGroup; + children = ( + 7334FFB579A1884B99237373A09774DD /* arena.cc */, + D17AC93D8B3ED45BD0F5116710A62D29 /* arena.h */, + 33210CB84E7E2EA9F5357F167D658407 /* atomic_pointer.h */, + 75F85C975C09185C0E84A04DA191DF1A /* block.cc */, + 0CA1BD6CB3A1AE01107FD8F8FDCA3D2E /* block.h */, + 6A978CCB0F810856629565567CB0B1DC /* block_builder.cc */, + A75B42E8622D5215381457494A951D5F /* block_builder.h */, + 71A5CCCB943C336F5BFE3C9B27E25543 /* bloom.cc */, + C2E41B74D9C1720A05CE0AB191067AFE /* builder.cc */, + 2BC27000ADAE777180D767021286CA2C /* builder.h */, + D64CE5DB6A98F389176B81AB143A03A1 /* c.cc */, + 238B69F72D2635F7E099540FEBAE969A /* c.h */, + 7AA64C916741F0BA7ADBC05AC52D974A /* cache.cc */, + D54AF9EA9805ABF27B6EE19DE73292C9 /* cache.h */, + 2120AEB3891B803C5271166BBAB0F0A5 /* coding.cc */, + E0F5DF31EC2E62475823F5669748B32A /* coding.h */, + B50A16C7653FEFB535C922A6E394F409 /* comparator.cc */, + 9BB01893708828A80056288891EE9E01 /* comparator.h */, + F6A56D57F7830EB35CBFC515C582CF0A /* crc32c.cc */, + 31997DF23B7B7028628BAB1A7A4AFD8B /* crc32c.h */, + F7EADE67FC960214F7DED9045D807108 /* db.h */, + A60901D38929C0E04817F7B345B30999 /* db_impl.cc */, + A5C0809DAC4098C4DCA572A7499E9116 /* db_impl.h */, + 6C021F5E4C2CF0638FF24E140E7DCA92 /* db_iter.cc */, + 42BCBB4A4FDF6D8CDE4DFB7454B6BFD5 /* db_iter.h */, + F1D8CB7DF2E46250C1C43220C97810B6 /* dbformat.cc */, + 52DDE7C94F2CFD1F4B7D89EAD53BDA16 /* dbformat.h */, + 0F561C68BAE176C5D0E278CE58FDDCD5 /* dumpfile.cc */, + 54B748CB1F4B495705943806D14E57CD /* dumpfile.h */, + 250424226E3E1252246D83E4302FCF23 /* env.cc */, + 44976CFF5764982B4FF99FC51761D657 /* env.h */, + 2CE2AFE0717F5787756256BC9B37CCDE /* env_posix.cc */, + 1C9262B336C315B62E2E2BBCB9ECB143 /* env_posix_test_helper.h */, + 76BF777E514F1D6AA78DE3FA6FE1E13B /* filename.cc */, + BBA75DF8FF00F58C0B862CFBFDE225AE /* filename.h */, + E09ECF63E89195F26D272FC3BD8C7044 /* filter_block.cc */, + 0E028BD0ED8BAF09AF89450487F80927 /* filter_block.h */, + 7861ACAB61D863B75747C507485CF5FF /* filter_policy.cc */, + A3BF85E75A6FABE9D104B8E0255D2E0F /* filter_policy.h */, + 976DAE361FF6DA77BD3EF2CEB5B24754 /* format.cc */, + 0D945B5FCAFD829D8E4CB0BC446F5263 /* format.h */, + 11018727FC836C957AB749559F7845ED /* hash.cc */, + 5CB11A8A37A78CD677212D20B4EC9A5E /* hash.h */, + 58F22BD1F34CA15EC75B42909369C0E6 /* histogram.cc */, + D97D7500FF14C5EC413647CED0DE06EB /* histogram.h */, + 273588F88459B6EE9873ADA94B13FC66 /* iterator.cc */, + 1F32152C8DD47543CFEEE86EC20A8D54 /* iterator.h */, + B71F9CA1A6DFC5C710C50B9AFA31CBAF /* iterator_wrapper.h */, + 62B3DC5F0A104BF4ACF3B85C55D99BC4 /* log_format.h */, + A6CBDE68609CD2D3C103DAA433F2C60F /* log_reader.cc */, + 32549BEEF6A49D7F0A9E0210E5889C34 /* log_reader.h */, + AC67F7B153F19CD9D494C50213CC1B3E /* log_writer.cc */, + 2C2266A871A0E4A996895C0A6B5F65CF /* log_writer.h */, + 48B55CE7E259B813481B4F6DC1EDA605 /* logging.cc */, + EBAFE747641CFE19EA7DD3E3143DC52C /* logging.h */, + 160AC27B2B81C1CFF9884A32DEDBD736 /* memtable.cc */, + 676357AD124D2145D88CF5C3AEDE005C /* memtable.h */, + A7AA5196BC9D9746048C578C41EB5941 /* merger.cc */, + 2AD6C8F4DFB8B09F9C4C1273793725ED /* merger.h */, + 9E06E73DF47291251ABD36E38BBA14B3 /* mutexlock.h */, + 814BDBAAB7D6AF52DD7C730CB57ED235 /* options.cc */, + 069EEE870762C0F433A706FFB665A283 /* options.h */, + 6AD51002F5F86EBA67F6340027B559A1 /* port.h */, + 484F43D7839874BA43FC7287627443B2 /* port_example.h */, + 178235193981793B5A1306D65CC58041 /* port_posix.cc */, + F7526F869857A24835B865B3FC4871E3 /* port_posix.h */, + 2EC536F0C78D7F592760BB1B26CEE026 /* port_posix_sse.cc */, + 4A3870091C969EE33FC9862E0AC8182F /* posix_logger.h */, + 721B542A1F80BE1951DE5AB8C5CECDF4 /* random.h */, + A28ABD321652444E5617923C7C375319 /* repair.cc */, + E53EA631D6B0E9EEA7B2FADB660D1EEA /* skiplist.h */, + 72AA3FD7FCFBF9B31AE268CA36CDF564 /* slice.h */, + E9ABDE6BBA1A94C280712138E8C978C7 /* snapshot.h */, + E6913AC5D85713434F74209FB9DF8190 /* status.cc */, + A0FC5CBCA095CB6ADDF78AB6763964C3 /* status.h */, + 33D03EFE889DEDA5D7BB31722B237A80 /* table.cc */, + CC6154B7CE684A1970FFE54F20E8392F /* table.h */, + EAEE4CEDCD6C42826ACDDFADE4DF0FB2 /* table_builder.cc */, + 7E14FE7B650352A45172263EB07521FA /* table_builder.h */, + AB16085037ACA0EF2DB981B3C7993C4E /* table_cache.cc */, + 7D69CF64D7DD9D1CB88D623B60BFA93C /* table_cache.h */, + 2873E606F0C6C216CEF364B6C5008F42 /* testharness.cc */, + F22610E4772184F5CBC2C803828100CA /* testharness.h */, + 2A66497EBD1AB3737D5005944AF2A938 /* testutil.cc */, + 551DE73F29DCBD088E26B78CC09409E8 /* testutil.h */, + 93FE8C81279E09B8344D4D4F5873DEA8 /* thread_annotations.h */, + 68676BA36D0C984D720E7033B11A06E5 /* two_level_iterator.cc */, + 3F10F5BDFF54C0E2F5A47075F3A05D23 /* two_level_iterator.h */, + 935886C7F3E7579A7743B85BFAB68601 /* version_edit.cc */, + 2CF857CEF2CDC86922BA2271E25A7A13 /* version_edit.h */, + 94934014090548D4B93291C3A35A43BA /* version_set.cc */, + E56C14A11112A55CF82997DF7D888028 /* version_set.h */, + 5223757BD175F800FD48E7DE0E939530 /* write_batch.cc */, + 7E04F48A3C2F6EC156E49CC1BD8AFA0D /* write_batch.h */, + 7220181B4FADE1BE7B6FDD9CA2FF21E6 /* write_batch_internal.h */, + 23D865198669DB6537255F32D5E5D385 /* Support Files */, + ); + name = "leveldb-library"; + path = "leveldb-library"; + sourceTree = ""; + }; + E873026CF11D0FD8EF2326591E3D2485 /* Environment */ = { + isa = PBXGroup; + children = ( + 48F3B5DB6993BBECE9BD46E853AB5B02 /* GULAppEnvironmentUtil.h */, + 453054BE5330275352B536CFAF6B76CF /* GULAppEnvironmentUtil.m */, + ); + name = Environment; + sourceTree = ""; + }; + ECC5ECB8EA94143AAEFF4F5C8C384B79 /* decode */ = { + isa = PBXGroup; + children = ( + ); + name = decode; + sourceTree = ""; + }; + ECE75CA4E7E40274859412AB3EC76863 /* Products */ = { + isa = PBXGroup; + children = ( + CADBF9EAB8E6375218D133DE8EC36296 /* FirebaseAuth.framework */, + 03FA546BF26C2C92243ACD81C404B4DF /* FirebaseCore.framework */, + D1B6EF52D08A5CB66B19509A9FA26392 /* FirebaseDatabase.framework */, + 81E8A3CD852063E84294E4611723E4AE /* FirebaseMessaging.framework */, + E35D272AECCFDD36EEA858CFE9754389 /* FirebaseStorage.framework */, + 6E31586DA53A4DBE99F094125C8BEF15 /* GoogleUtilities.framework */, + 9BF758753C1447148E55B242D5A8D189 /* GTMSessionFetcher.framework */, + 50E2D1A1F604F7B2D4C65D599DB5CFF4 /* leveldb.framework */, + C22FFA05A12B4D3BDF4C4307840FD4E6 /* nanopb.framework */, + 7D37B39157C7D0EC71A0F813C9CFC9AA /* Pods_My_Mind.framework */, + B662A5489E41A07B7B8124D85511A255 /* Pods_My_MindTests.framework */, + EBF8441A787609A9C03B1FAB585F4CCF /* Pods_My_MindUITests.framework */, + 4EB8204C84A0257A6B1C9421827E0260 /* Protobuf.framework */, + 47A0DD80F32294AC8CB5952EC5A56807 /* SwiftForms.framework */, + ); + name = Products; + sourceTree = ""; + }; + F65A0434A74383C5704A0AFE3106CC42 /* UserDefaults */ = { + isa = PBXGroup; + children = ( + A4A441974FF8146A16F5356A074A3BBA /* GULUserDefaults.h */, + 6440D16966C799ADA6FF8B1D0F21716D /* GULUserDefaults.m */, + ); + name = UserDefaults; + sourceTree = ""; + }; + FD063AAB19B259A1887FCB30B707043B /* Support Files */ = { + isa = PBXGroup; + children = ( + 7C28C0FC58ECA858722F32BCA5B0E6A6 /* GTMSessionFetcher.modulemap */, + 1F8914247BC8981046DD3254E6EED8BF /* GTMSessionFetcher.xcconfig */, + 34E37E86AAAB7B5AB34F165B3C259058 /* GTMSessionFetcher-dummy.m */, + 01A02543DE15ABC24361250045BD11C3 /* GTMSessionFetcher-prefix.pch */, + A9CFB4A25C1A9163B43C9569A6776AF5 /* GTMSessionFetcher-umbrella.h */, + 4843041F19E32C7DB2152854218E02B7 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/GTMSessionFetcher"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 18421998863481230011ABC9E1034D8D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DF6A56F3870DE4F3EEA68AF1AB07AA70 /* FIRActionCodeSettings.h in Headers */, + 7A66B535FB8849FA7756968A8D6365F4 /* FIRAdditionalUserInfo.h in Headers */, + 239677F29755CB7B79AAFD1DC0C0BE21 /* FIRAdditionalUserInfo_Internal.h in Headers */, + 0FF066790A34A0E5FB53156289E72ED5 /* FIRAuth.h in Headers */, + BA43D9004D1FBF13D712CED11E18F955 /* FIRAuth_Internal.h in Headers */, + 2AC4DDC97C6C03DD5E1FB6ABC99A70A7 /* FIRAuthAPNSToken.h in Headers */, + A49EE8F519A4DABE52EF46452FB7F803 /* FIRAuthAPNSTokenManager.h in Headers */, + 50249165DA81FE6C81E2442E760B9727 /* FIRAuthAPNSTokenType.h in Headers */, + 36A05411E4D438C3DA2E581DF59F0849 /* FIRAuthAppCredential.h in Headers */, + 290511839CF8EC8F00D125AE26FE9282 /* FIRAuthAppCredentialManager.h in Headers */, + ED5BE623D35FDF173B5ECDA62FF7107E /* FIRAuthAppDelegateProxy.h in Headers */, + 63C08B25B83392876349B76A01EF0DD0 /* FIRAuthBackend.h in Headers */, + 84F1BF568E29D9E470BDFB6F5293CE71 /* FIRAuthCredential.h in Headers */, + C8DD81A987EDF071FB3CDBBC1F189B0A /* FIRAuthCredential_Internal.h in Headers */, + 49E0AB27080431FB15F998CA1BCA1576 /* FIRAuthDataResult.h in Headers */, + 553E38FF0ACED6BC66D13E2945569047 /* FIRAuthDataResult_Internal.h in Headers */, + F9557F9BF6B95D2A3E544BA4C41327E4 /* FIRAuthDefaultUIDelegate.h in Headers */, + 52697DFB887B66F1584354631B6AD292 /* FIRAuthDispatcher.h in Headers */, + DA30B636C4FE2B431A9D764A2ED0466C /* FIRAuthErrors.h in Headers */, + 5A722AD0805D4F276B9C095E0EC8D124 /* FIRAuthErrorUtils.h in Headers */, + C8EC2232444A2D67721770383755671C /* FIRAuthExceptionUtils.h in Headers */, + 17CB0ABF89CAAAB627292A00AA3529A4 /* FIRAuthGlobalWorkQueue.h in Headers */, + C7B13BA4CCC6367AC048F334FEC48E52 /* FIRAuthInternalErrors.h in Headers */, + 43E1FAA95D071540F70FAFDC5C4CC382 /* FIRAuthKeychain.h in Headers */, + DBA22EFE562C00D58CA8117752A4CCBE /* FIRAuthNotificationManager.h in Headers */, + EA2E05FBD13050A1F79569643446DA92 /* FIRAuthOperationType.h in Headers */, + 0FED15ECB6105F4BFF5D25CCE3C9187F /* FIRAuthRequestConfiguration.h in Headers */, + A97D5FA330E8D8311C8DC1F83E488399 /* FIRAuthRPCRequest.h in Headers */, + BD9233CB33E367ACBEF919FAD239E6AB /* FIRAuthRPCResponse.h in Headers */, + 763C2599457CD314F0C23C47F36A2416 /* FIRAuthSerialTaskQueue.h in Headers */, + A21506AC3CE435A3EAF0FB9DC704EB92 /* FIRAuthSettings.h in Headers */, + 8BDCED39B9876A9F1EA296FB800F2CF6 /* FIRAuthTokenResult.h in Headers */, + 146B6E3071A34E0CE9E70DE8F3A24A4C /* FIRAuthTokenResult_Internal.h in Headers */, + E3B57C5EEEB965CFF615E2F7060931B1 /* FIRAuthUIDelegate.h in Headers */, + 4F5C0502F5B6F412856A310E9147EA5F /* FIRAuthURLPresenter.h in Headers */, + BE22C23DDEBA277761380609E3368B64 /* FIRAuthUserDefaultsStorage.h in Headers */, + 25E2893DF36B4A33430D1644D82D6511 /* FIRAuthWebUtils.h in Headers */, + 473FDAF90CFC14D382A966C4AEAFB148 /* FIRAuthWebView.h in Headers */, + E5C91F7822F2E9F9804F8F317750F22E /* FIRAuthWebViewController.h in Headers */, + 7ED9F2FE61D3658C2E275F0C27B3A1B8 /* FIRCreateAuthURIRequest.h in Headers */, + B9EAE81286BDB8C5C9FD40BA7568F1F6 /* FIRCreateAuthURIResponse.h in Headers */, + 1AA4FEE4489E142E7CC8BACE93717E53 /* FIRDeleteAccountRequest.h in Headers */, + C6692625E63BC08E12CD9A7D370FF3B1 /* FIRDeleteAccountResponse.h in Headers */, + 157ADD76801911EB580A646FC171A1B0 /* FirebaseAuth-umbrella.h in Headers */, + 2453BE02814DD5B74DBC558A2987C561 /* FirebaseAuth.h in Headers */, + 435E994C1DF537D573EF0434A08684D1 /* FirebaseAuthVersion.h in Headers */, + 878AEA6C8AD7E00E72103A5E6936A453 /* FIREmailAuthProvider.h in Headers */, + 2CB575E4C500A3E3F74B4B45B527AA15 /* FIREmailLinkSignInRequest.h in Headers */, + CB527332638B18AED5B739BE840683F1 /* FIREmailLinkSignInResponse.h in Headers */, + 1214F2AD192C812AAFB9DF123B1BD468 /* FIREmailPasswordAuthCredential.h in Headers */, + 81EA084F84E2E5B4ABC637DB30572EE1 /* FIRFacebookAuthCredential.h in Headers */, + A3FFC56572F14E7EE1C87216816949D8 /* FIRFacebookAuthProvider.h in Headers */, + DC25ED33ED42D631129F8AA17F3E1A29 /* FIRGameCenterAuthCredential.h in Headers */, + C6AF34A3108D017F82436A59455898C2 /* FIRGameCenterAuthProvider.h in Headers */, + C1484F17304997F3ED1FD80A60801310 /* FIRGetAccountInfoRequest.h in Headers */, + 840DE54F14AA85F6A6C4D8E1B50ED26C /* FIRGetAccountInfoResponse.h in Headers */, + B181110C59D8DD6EFE5BD1F6078FD500 /* FIRGetOOBConfirmationCodeRequest.h in Headers */, + D1C5A46153BF21B07533D5E47B7FC491 /* FIRGetOOBConfirmationCodeResponse.h in Headers */, + D3C89629225077014D01F1F1337842F9 /* FIRGetProjectConfigRequest.h in Headers */, + 032A4184AEB5DEA1C6084C79403BAE15 /* FIRGetProjectConfigResponse.h in Headers */, + D7001F1A9D396BDC44E5A05ED159AFEE /* FIRGitHubAuthCredential.h in Headers */, + BB50D1AEFD09F9A1DDA8B02A0FEB3060 /* FIRGitHubAuthProvider.h in Headers */, + 0B21E5E6E330CDE16FFDDD34F8019159 /* FIRGoogleAuthCredential.h in Headers */, + 6F412D7A91AD823FDA1C065278498790 /* FIRGoogleAuthProvider.h in Headers */, + BB31B856BA4B23746DBCBB3AD1A60495 /* FIRIdentityToolkitRequest.h in Headers */, + F8BC2ECF624CA7138AE7A07D218E6C1B /* FIROAuthCredential.h in Headers */, + 71AF98FE4A9F2469CD72D0E52B094E6F /* FIROAuthProvider.h in Headers */, + 7B3A1CE76FFD6E2CE6F4173E9F0B69BF /* FIRPhoneAuthCredential.h in Headers */, + 1407E6CE7062308AA0AD23777CE4BFF8 /* FIRPhoneAuthCredential_Internal.h in Headers */, + 0DF749F7328C60E4278B1239EC1723A3 /* FIRPhoneAuthProvider.h in Headers */, + 6C7FA07C60CC029BD2F5B26EC7F2F5BC /* FIRResetPasswordRequest.h in Headers */, + 0F96D1FE9E7489E5AB0F86B88CBE287D /* FIRResetPasswordResponse.h in Headers */, + 6C6AA46BD8DD2F1898EA7CFCB187CF98 /* FIRSecureTokenRequest.h in Headers */, + 520A5B3D5988C02C62DD9F3267E32741 /* FIRSecureTokenResponse.h in Headers */, + 70A01A282869906039CB23CF00ECD937 /* FIRSecureTokenService.h in Headers */, + 765C0471539D9719322CF5A40F8E2E01 /* FIRSendVerificationCodeRequest.h in Headers */, + 8C7F928C34AB0956E676286DA6C311C1 /* FIRSendVerificationCodeResponse.h in Headers */, + 975BDD38E28039F408D52877FC0B5C5E /* FIRSetAccountInfoRequest.h in Headers */, + FEBD7EB9CF0EF3CDFCF0459CBD5861EA /* FIRSetAccountInfoResponse.h in Headers */, + FA32B2D2522593F2C5B102F0413A6689 /* FIRSignInWithGameCenterRequest.h in Headers */, + 3B08F067675402CD040A3B50963BB89C /* FIRSignInWithGameCenterResponse.h in Headers */, + 8F88D609AAE1440DF35C6B69EE7DDD85 /* FIRSignUpNewUserRequest.h in Headers */, + 7D2FF6C5681390D838D3573E87D4B361 /* FIRSignUpNewUserResponse.h in Headers */, + 591ACFC16CD41AB896025845CCED21B3 /* FIRTwitterAuthCredential.h in Headers */, + 5BCA23A778D7A6821961EB7BB7F920BE /* FIRTwitterAuthProvider.h in Headers */, + 89E71F9B92E1779978E3E5E70FB06712 /* FIRUser.h in Headers */, + BB051BF78681E74C549656CBE3D890A8 /* FIRUser_Internal.h in Headers */, + 2C8913832BC7EBA24435CB2D582F142F /* FIRUserInfo.h in Headers */, + 887D3EFAD17964D20F8A8FB8FFB43040 /* FIRUserInfoImpl.h in Headers */, + B254C3FDDF65B8AF8E5E3B17630A4109 /* FIRUserMetadata.h in Headers */, + 4B64E08275123F6FF3AD8FEB6E826A5C /* FIRUserMetadata_Internal.h in Headers */, + A446713CB33544D018DDBE488AC1D07B /* FIRVerifyAssertionRequest.h in Headers */, + C37C956AFAF1B1D8067CFD3EBBA2B249 /* FIRVerifyAssertionResponse.h in Headers */, + B563D3BC17F883C4BE12BA863FCFD367 /* FIRVerifyClientRequest.h in Headers */, + BFD1527384C8AB7685D3DADCC9ACEBF0 /* FIRVerifyClientResponse.h in Headers */, + 095B92373278C10C8A3B1F4A1F73A2B3 /* FIRVerifyCustomTokenRequest.h in Headers */, + 5106A9BB8CFD5B5D0E2B82CBAC345D80 /* FIRVerifyCustomTokenResponse.h in Headers */, + 378285C697294CA4BD74927E4D4CFE43 /* FIRVerifyPasswordRequest.h in Headers */, + F54AC8827E2AC4FFE1CD250808FDAF0D /* FIRVerifyPasswordResponse.h in Headers */, + 34142FD524815DEABD01ACF275DA650A /* FIRVerifyPhoneNumberRequest.h in Headers */, + B42B2F1D39576EDD7807959618872CE6 /* FIRVerifyPhoneNumberResponse.h in Headers */, + 8F555CAD99E7161E53D7A26980C0D3FF /* NSData+FIRBase64.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1FE6BE7F2771B9FB3C962850E327CB9F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E5712C3099F002299B386BD7333BD664 /* SwiftForms-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 29EC56FBA7129F938D405973B6BAC2E6 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 7D2F7644BDE6BA8F764458C0C552CCCD /* FirebaseMessaging-umbrella.h in Headers */, + 8138F4D72CEA3E79F7A430C8BC9EC924 /* FirebaseMessaging.h in Headers */, + E762BE2516FB3427F3E7C94A0F0385FC /* FirebaseMessaging.h in Headers */, + 9F948E3271D72EC2693934AB4E5E36BA /* FIRMessaging.h in Headers */, + 3C864CBB8AF42464DE35B28C4EB51D03 /* FIRMessaging_Private.h in Headers */, + 434050B360E1A4F6AB30179C4625918A /* FIRMessagingAnalytics.h in Headers */, + 9FCC9812B2708EAA4AEE1F9832BBD40E /* FIRMessagingCheckinService.h in Headers */, + 6126B1178651B0EF339AC7E877DE8A11 /* FIRMessagingClient.h in Headers */, + 6EEBB3F1EA4A7A467A6576A4CCC55149 /* FIRMessagingCodedInputStream.h in Headers */, + 50A1ADE7CEE872200E1B26909524AE5C /* FIRMessagingConnection.h in Headers */, + FAF542DED3A09F832A9151FA54D9EED0 /* FIRMessagingConstants.h in Headers */, + 1CC2CDE924AE5455F04D90BB06D7A0DA /* FIRMessagingContextManagerService.h in Headers */, + 713D2EA92B582AD4DCEBB17CCF150CEA /* FIRMessagingDataMessageManager.h in Headers */, + 73D033AAF2CE93E62837589F0E1FF63B /* FIRMessagingDefines.h in Headers */, + FDF22C2100DFCFEB404085E621538E91 /* FIRMessagingDelayedMessageQueue.h in Headers */, + 4EFCA2B3A6F4C260B8507E5E3929DE24 /* FIRMessagingInternalUtilities.h in Headers */, + CE6EA5939A431EAE565CEB678A197405 /* FIRMessagingLogger.h in Headers */, + E643D91DB349AA0E8ADCD7135864FF4F /* FIRMessagingPacketQueue.h in Headers */, + 19E00149B83420B657999688A62BCC38 /* FIRMessagingPendingTopicsList.h in Headers */, + 260F8F5BECA192212B30CBAD2B769318 /* FIRMessagingPersistentSyncMessage.h in Headers */, + AD09EE334BCFD006DBAAAB20ABC6F409 /* FIRMessagingPubSub.h in Headers */, + F3380784E1501976922E124A89DAD92E /* FIRMessagingPubSubRegistrar.h in Headers */, + 1B53A90973A83551E91EBC14158FBDFE /* FIRMessagingReceiver.h in Headers */, + A08534D62B21CF083053FF3C5EE924D3 /* FIRMessagingRegistrar.h in Headers */, + 20E481DB22BC2EEF19A3665138F52A43 /* FIRMessagingRemoteNotificationsProxy.h in Headers */, + 392995C8A9ED047B31DB8591BBEED101 /* FIRMessagingRmq2PersistentStore.h in Headers */, + 6A3F7C46330A4EA69D0CA257CB60EB00 /* FIRMessagingRmqManager.h in Headers */, + 2ADFE23A360FDEA4354624A928476953 /* FIRMessagingSecureSocket.h in Headers */, + A86906AF6244D8C1CE33A822BC26683A /* FIRMessagingSyncMessageManager.h in Headers */, + 73FD120EAE9F35FEFB94B717EE5591E8 /* FIRMessagingTopicOperation.h in Headers */, + 2DAE9E974339ECC5237F52641C71959E /* FIRMessagingTopicsCommon.h in Headers */, + 1EF5C377ECDD43466DE5D1046392982B /* FIRMessagingUtilities.h in Headers */, + 508089242A216167AACF79AD1749B6EE /* FIRMessagingVersionUtilities.h in Headers */, + 9C38E60FA057D6D1B48890C3B4DC09F4 /* FIRMMessageCode.h in Headers */, + C300176A27337A7100CAEF0C46090DCE /* GtalkCore.pbobjc.h in Headers */, + 4BDEE48FEDC02A8A6FAB51BFF149534F /* GtalkExtensions.pbobjc.h in Headers */, + 3A6ECB640C1ED73B97C6E905515A88AC /* NSDictionary+FIRMessaging.h in Headers */, + 09C7FC923342D1439EFEC22810BA44D0 /* NSError+FIRMessaging.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3261BA1F995ABA893077E5C3EC39AF7D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2998970FE1A48BFB569225CF4642EE05 /* APLevelDB.h in Headers */, + 735084A830606575362DE447148BF143 /* FAckUserWrite.h in Headers */, + 9EC35AE5E263F48B43222C73F9569F21 /* FArraySortedDictionary.h in Headers */, + A421534A2448E72CE68FC47F85063620 /* FAtomicNumber.h in Headers */, + 13B9008DAA3745EC8EC09C2058ADF32C /* FAuthTokenProvider.h in Headers */, + 349FEA4C6FDAB3C48BED3982115746D0 /* fbase64.h in Headers */, + AD713AD4352D0437F392D8A81D71F4DA /* FCacheNode.h in Headers */, + A73A021178D0B3E28768A85ECDA4D236 /* FCachePolicy.h in Headers */, + C8A8AA89B97E1F1AFED2DF787DEF26D9 /* FCancelEvent.h in Headers */, + 1CFA298A847AA9B4CECCA93F2F85DE1B /* FChange.h in Headers */, + 261A729A04060A4BD9FE7A598E7DA6B6 /* FChildChangeAccumulator.h in Headers */, + 4FB925DB731A1DE38CB4DBE7179E89D9 /* FChildEventRegistration.h in Headers */, + 245C416D912CB79A158CE6C0BBA5709C /* FChildrenNode.h in Headers */, + AAB20FC52EF9A97F915B8AC9EAF2B5B8 /* FClock.h in Headers */, + 3DE16070D4BDD2E4BA4E2124D9888788 /* FCompleteChildSource.h in Headers */, + 9E645C345766689851360BC3C0A36CBC /* FCompoundHash.h in Headers */, + E6FA0DEE717893F584A33FE8D4D366D9 /* FCompoundWrite.h in Headers */, + 0CC702C8F99E23DE8D41425BFDD4240D /* FConnection.h in Headers */, + DD387E81AFD93294E3F4959E64B99520 /* FConstants.h in Headers */, + 875AAF41A3BA5D50E41DA8B2CE16119F /* FDataEvent.h in Headers */, + 13537D802C50BE4E1351903E9A85CD38 /* FEmptyNode.h in Headers */, + C8CB64DBC662A8F8B98E23357939C9A6 /* FEvent.h in Headers */, + C73D787DF2524203C4A652518756B232 /* FEventEmitter.h in Headers */, + 77FB82CD991CECCD4CC9A4389500E93E /* FEventGenerator.h in Headers */, + BBF82F880B8E1C735B7E428ED3663BCB /* FEventRaiser.h in Headers */, + 4DF2768338C463B587094F8994E9089E /* FEventRegistration.h in Headers */, + C09BD9A434F0B43F74D694B7F96E55A1 /* FImmutableSortedDictionary.h in Headers */, + 36B8264FD3ADAC365EF136BEE736C2D3 /* FImmutableSortedSet.h in Headers */, + ABAB683C7C96985D3D17CAC333385688 /* FImmutableTree.h in Headers */, + FB21241BABCD81B33CCB0849CE0AB8F4 /* FIndex.h in Headers */, + D6A236A02392872BA73D7269B648406E /* FIndexedFilter.h in Headers */, + C7E3BA8A222F6E68E31AC841439CAF79 /* FIndexedNode.h in Headers */, + 96F0D37AE2A4F7A32F02D12FE6E299D4 /* FIRDatabase.h in Headers */, + 3A808D849F138AA9661808DA3A132E80 /* FIRDatabase_Private.h in Headers */, + F23EC9ABF478F6040F1B87825D6EBFAA /* FIRDatabaseComponent.h in Headers */, + 1BD022E15D93903A246A7B62D9F45CE7 /* FIRDatabaseConfig.h in Headers */, + B24AE7B91624027EA6971C6EB6154423 /* FIRDatabaseConfig_Private.h in Headers */, + 0056238FBF1C6575CB347D7D083078C5 /* FIRDatabaseQuery.h in Headers */, + FBE5BE393815441AF36A8F9C8F262863 /* FIRDatabaseQuery_Private.h in Headers */, + 57F1E9867374A80EBFAFAC44909AC754 /* FIRDatabaseReference.h in Headers */, + 32CC39E48764CA3467393DCEF2151A08 /* FIRDatabaseReference_Private.h in Headers */, + 31CE24A1215D3B4FC23D539976017CF5 /* FIRDataEventType.h in Headers */, + 5E6FD62B18705C3005EE326D28E9EFBA /* FIRDataSnapshot.h in Headers */, + 9AE3332394CB4E7A85A09470B6274737 /* FIRDataSnapshot_Private.h in Headers */, + 1430115FF4C5E3993B9CD7178956D80E /* FirebaseDatabase-umbrella.h in Headers */, + 199B7124BD04C34D3152530AF2E35F1D /* FirebaseDatabase.h in Headers */, + 5C6C4CB13D6035CEE07E31F934D0941A /* FIRMutableData.h in Headers */, + 501CECD12940FFABF8BABF5653093243 /* FIRMutableData_Private.h in Headers */, + 64A0467CEE2AD508778F414973069ED9 /* FIRNoopAuthTokenProvider.h in Headers */, + 96A71A9CF82ED4CBBAC6303434D5D498 /* FIRRetryHelper.h in Headers */, + BDD9828847D4DD7EF971F67C68418B64 /* FIRServerValue.h in Headers */, + 850F2E13D548D0AF42396FCD31A351F7 /* FIRTransactionResult.h in Headers */, + E975D999A07849EFCEB864F5E8CCA78E /* FIRTransactionResult_Private.h in Headers */, + D51F6B9C6F3F7F6BCEA88A7C45F34C44 /* FKeepSyncedEventRegistration.h in Headers */, + 225738FCD97CAC58948F5C69D6EAD994 /* FKeyIndex.h in Headers */, + A6FBD16911AB017EE6CEBDF5043B0039 /* FLeafNode.h in Headers */, + 1F411F60AC433B7A8CF2AD16BB33548D /* FLevelDBStorageEngine.h in Headers */, + FC9D70C36569D43D58C336C316C14DB0 /* FLimitedFilter.h in Headers */, + 5062061C7B762AC028651A7F1F0E9897 /* FListenComplete.h in Headers */, + 865C218C9BA8FC209F49CA669AD1B1A1 /* FListenProvider.h in Headers */, + 16FC08D09F195371ED8C012975BA4B31 /* FLLRBEmptyNode.h in Headers */, + 8A4F7161E986EDB276A57244550E928B /* FLLRBNode.h in Headers */, + 64508C76C9A29C3339CB874458118BDF /* FLLRBValueNode.h in Headers */, + C6116CF8DF725EF3D2EF5D8C64793D94 /* FMaxNode.h in Headers */, + B42296DE72D116C0C1A22BA451DC4E39 /* FMerge.h in Headers */, + D6C4BDBDDC3A5DEB9FB340D9F4B6E0CC /* FNamedNode.h in Headers */, + A9B7AC3DAF79567C8F883352BFED17D7 /* FNextPushId.h in Headers */, + 3FDBCD14B143183DC6700C737B7D9A3A /* FNode.h in Headers */, + 8C3007FAE540957E0E0F64DF2AD19C6E /* FNodeFilter.h in Headers */, + C9E1CE53DAC98165EABA11D880683996 /* FOperation.h in Headers */, + 947145C319107C75FAA9C3EB5B270862 /* FOperationSource.h in Headers */, + E49CD8F1F3A61D8519D13384789B2581 /* FOverwrite.h in Headers */, + 0C9039605A7D3D5FDF983ABB650C79D3 /* FParsedUrl.h in Headers */, + B5E3E3FA315D33B21B5F3344B6C824A0 /* FPath.h in Headers */, + 53247BF34F23D44161C4204A8F7C8170 /* FPathIndex.h in Headers */, + E44EF4970A6E5604A2E961E572A607A2 /* FPendingPut.h in Headers */, + 942EBF353D5E23BD696F9F84B5A70FDF /* FPersistenceManager.h in Headers */, + 92220B096BAC953985661BC5F2DFDD85 /* FPersistentConnection.h in Headers */, + 4B181EF02099871204BA6BF5E3BC9C52 /* FPriorityIndex.h in Headers */, + 82BCAEF7C2862BA98A71099327735F46 /* FPruneForest.h in Headers */, + 30AEA30323297A18293A0E09E7301849 /* FQueryParams.h in Headers */, + 52B3F7169F4B7F43F6A51AF8A971F740 /* FQuerySpec.h in Headers */, + D85EF192B8C1D8E9B6A7E06815055652 /* FRangedFilter.h in Headers */, + 1A4E6AEEB9E0813B460A54A99A2FBC2C /* FRangeMerge.h in Headers */, + E1358AA48B67E967CDC5DAFAA273C3AC /* FRepo.h in Headers */, + 48EA0FD567ED01C39C97DC756B22C8AB /* FRepo_Private.h in Headers */, + 3576DF3E4D39649AB921933ABB67E18D /* FRepoInfo.h in Headers */, + B431A77F62F1714B3B3A47FF0BB3B237 /* FRepoManager.h in Headers */, + 9E867CE47128CBA81E3C374B352E3324 /* FServerValues.h in Headers */, + 7AFB98C382890FEB5AEBDCD32B333180 /* FSnapshotHolder.h in Headers */, + 4E6ADE78C8281AB1ABECC5104C3B47A6 /* FSnapshotUtilities.h in Headers */, + 02FA9DA67EC27D7D1635AE5DCB37D33E /* FSparseSnapshotTree.h in Headers */, + 1288967993058DD01F2D4C9C6748467C /* FSRWebSocket.h in Headers */, + C40F384DBB2B9953A9563C0F62A061AC /* FStorageEngine.h in Headers */, + D25EA3543993A4580FC33176E8012D79 /* FStringUtilities.h in Headers */, + 3CBB46EE875BF2548D6A79249CBDF4E6 /* FSyncPoint.h in Headers */, + 7EC3F0AA877A53269B037F1BE0209189 /* FSyncTree.h in Headers */, + 771DFEE8279979F5DD28AF0B96E58F4D /* FTrackedQuery.h in Headers */, + 65C31895EDBF3B201F3502DC47C639C3 /* FTrackedQueryManager.h in Headers */, + AFAA7A560C7373F44A9AD71CA491F37A /* FTransformedEnumerator.h in Headers */, + 933173512B68474ABA0E4F17835A9DA0 /* FTree.h in Headers */, + CEC8D863FA449477FD7C4F059DCEF51C /* FTreeNode.h in Headers */, + 7090E26A73C33E7E67F24A2E2B7CDF96 /* FTreeSortedDictionary.h in Headers */, + 204A5511FB6690E4F1831E36524FF7E6 /* FTreeSortedDictionaryEnumerator.h in Headers */, + AC5D118A0E6B91C906A8703307E999ED /* FTupleBoolBlock.h in Headers */, + 97EA9C429A2CE5E073DBEB7C3C5BCF86 /* FTupleCallbackStatus.h in Headers */, + 8D9DF1B959B1568D8BBED3D1CB537190 /* FTupleFirebase.h in Headers */, + 651797C6171EE641B79B4D1D62C6948D /* FTupleNodePath.h in Headers */, + AB591B4E27F0CF1798470C369A571673 /* FTupleObjectNode.h in Headers */, + 873F96538D0A120CF789640F9FE17FB1 /* FTupleObjects.h in Headers */, + 53F08143DEE1B6C401D309E74D58ED0D /* FTupleOnDisconnect.h in Headers */, + BED2AE2940B5BDFEED8DC328B94EDBF8 /* FTuplePathValue.h in Headers */, + C414B72AA07E409F1966DCD4F1D0467B /* FTupleRemovedQueriesEvents.h in Headers */, + 4E4888066B96C7590EC2E190A05B0FD8 /* FTupleSetIdPath.h in Headers */, + 5B38F49250D27082A85CB88879DA87EA /* FTupleStringNode.h in Headers */, + 96A46134A41459ECD851507FE82A2396 /* FTupleTransaction.h in Headers */, + A0BD2298246D382B3E5968BD5C1EC331 /* FTupleTSN.h in Headers */, + 96FDB687B22BD267A70D769F7073DE52 /* FTupleUserCallback.h in Headers */, + 1FDCEB6A40916796A1FBC79CD126FD23 /* FTypedefs.h in Headers */, + 431A3EDD24915839AF1415F635EAD7BE /* FTypedefs_Private.h in Headers */, + E81BCE081CF5DFE385E67C8CAA7F34AB /* FUtilities.h in Headers */, + 4AEBE32218F94AFB62AED4DD9161F927 /* FValidation.h in Headers */, + D2743BEAE5054ECA336FC2A9F7C7B4D0 /* FValueEventRegistration.h in Headers */, + F5B6A5BAB050DF49F8A8139F56CD22F2 /* FValueIndex.h in Headers */, + 4624A630AA3033609770704E8BD14B8A /* FView.h in Headers */, + DB7C28FA169A53CB692D201570BDB3A4 /* FViewCache.h in Headers */, + 47CBCEF5F276212C0C9B11722D45C78C /* FViewProcessor.h in Headers */, + C66864565E46E811E7201FE5D59030FB /* FViewProcessorResult.h in Headers */, + 7220E34740A20FCEAE61B1495AB18900 /* FWebSocketConnection.h in Headers */, + 3B1B26729BC1D60B397D5DBC08BD35B9 /* FWriteRecord.h in Headers */, + 72DA26C341C046F3DA66200B1B4C0754 /* FWriteTree.h in Headers */, + BCDA8D479323B300327EB434562109DE /* FWriteTreeRef.h in Headers */, + 55149D5C67CA2EAA3AFC17BFD0655A28 /* NSData+SRB64Additions.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4234DC53A2151EE74A18DB251F11BA7C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A20ACDAF3DC4F1E98BF027414AC64852 /* GTMSessionFetcher-umbrella.h in Headers */, + 7CC1B63E46109E535FB4F13084CAAD77 /* GTMSessionFetcher.h in Headers */, + 539D30616085B7F81713D6E533E60A49 /* GTMSessionFetcherLogging.h in Headers */, + FD88A998DAF3046F11F621ED4E5B85F7 /* GTMSessionFetcherService.h in Headers */, + A4301C4471C45F2A9A4F6BF8C65E0139 /* GTMSessionUploadFetcher.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 461E772F8F3FC0BD38003BAAB4AE1D5C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3F4A4BEAC4EA288A2EDD82306B56C489 /* Pods-My MindTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4A34A8C4C4BFB14D6E0504833C9159DA /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 0A4C5C81804C50CBDF57EF842DE97ED0 /* nanopb-umbrella.h in Headers */, + 47F644862D2F3FA7ACAC9AC409E11C83 /* pb.h in Headers */, + 427799CB422851F585C02C74820C0463 /* pb_common.h in Headers */, + D143A48E638AFDBD788EBFDC833E04BC /* pb_decode.h in Headers */, + C6AAA96E9F95646F5B19AA8CA8C82D96 /* pb_encode.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 57C52AF6FB1F0C7A84FE2907C89FAD18 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 218670777B0EE4D273341CF28057FC15 /* Pods-My MindUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8D0A1668A59890BC1718C45DA1EEBB11 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B8A03A7705827133E13713A22F2A0A31 /* FirebaseStorage-umbrella.h in Headers */, + AA774751DE26F15002F827034BBBE630 /* FirebaseStorage.h in Headers */, + DF4756064E353805E0B51B5505EC70E8 /* FIRStorage.h in Headers */, + 416A7760890657DBACC2BF6F6E3242EB /* FIRStorage_Private.h in Headers */, + 99281102B79D0A64554BF80FEA49FDEF /* FIRStorageComponent.h in Headers */, + 4E35A890B3744A22CB3195E4038B2150 /* FIRStorageConstants.h in Headers */, + B8581A8BE59EACD6AA0CCF0325A7A449 /* FIRStorageConstants_Private.h in Headers */, + 7A142B968132692D56E2EA79E38FBF1A /* FIRStorageDeleteTask.h in Headers */, + 2708BCEE56FB1ACEFF6608A821C20962 /* FIRStorageDownloadTask.h in Headers */, + A9390FDBA96ACA53CE8F2868305C8EAE /* FIRStorageDownloadTask_Private.h in Headers */, + 1906CE819DDF2BA7989489B4B6D70313 /* FIRStorageErrors.h in Headers */, + BA29BEDDAA424A73FEDA03DB0EBA8F35 /* FIRStorageGetDownloadURLTask.h in Headers */, + 4BC6A1B6066445EB017E2DA76F14C2D4 /* FIRStorageGetDownloadURLTask_Private.h in Headers */, + ABBB08E9C12864DD9EFBDD0A37E90A34 /* FIRStorageGetMetadataTask.h in Headers */, + C7158D53D2369C16BE87D63F2DF69FA4 /* FIRStorageMetadata.h in Headers */, + 91B3761046884D4CEFD906383EB65E6B /* FIRStorageMetadata_Private.h in Headers */, + A34E0C1DD34D7A2614616C7AD405E735 /* FIRStorageObservableTask.h in Headers */, + 56A8245C093F7D791D9E7F1B132FEE84 /* FIRStorageObservableTask_Private.h in Headers */, + AA72A358E0E8274E8D3A7702789E4259 /* FIRStoragePath.h in Headers */, + 1E35F6BFC09BD06406C29176322A6C61 /* FIRStorageReference.h in Headers */, + 8656E4214A0B1D14B8131B9719943DF8 /* FIRStorageReference_Private.h in Headers */, + 0A0160BC832D6FF67F17DA09C069069B /* FIRStorageTask.h in Headers */, + 1BB86F06F8AAE20B17524BB5294D0592 /* FIRStorageTask_Private.h in Headers */, + F2ECE7A7EADE045435246A5E2E913095 /* FIRStorageTaskSnapshot.h in Headers */, + 40EBFB526EFE2237051550143B403E77 /* FIRStorageTaskSnapshot_Private.h in Headers */, + 0DA255473FD9473B5FBFC73EC16165A7 /* FIRStorageTokenAuthorizer.h in Headers */, + 45EC8A519B567D6E0D643253BBC6BD8C /* FIRStorageUpdateMetadataTask.h in Headers */, + A70170FC8C111DB64EE4B07287A49DA2 /* FIRStorageUploadTask.h in Headers */, + 58DF46A85BFCF7D10D1FD611592AD711 /* FIRStorageUploadTask_Private.h in Headers */, + D5EE07D6222CD052D449B12A82AD2660 /* FIRStorageUtils.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B5C2C9A521EC90CF270CCCF52808B52D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 657959D98D454DE5B75535323418897A /* Pods-My Mind-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DE2487C6BD5252B0CD439F0590C7C2CA /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 93F2CC4E4B63982B1E8BE7F812B261F1 /* FIRAnalyticsConfiguration+Internal.h in Headers */, + 67117B627E97D17BB8EE22297BE609C8 /* FIRAnalyticsConfiguration.h in Headers */, + ED400B3FF772E27EAFDE40C8B63B9B2E /* FIRApp.h in Headers */, + 4E5122842FC952CB1E9F3BC88B0F0C6C /* FIRAppAssociationRegistration.h in Headers */, + DD8964C5E56F3CFBBF201C19257D69B0 /* FIRAppInternal.h in Headers */, + B5AA7832115EB1F7CD229933A9EF6DEF /* FIRBundleUtil.h in Headers */, + 038F9D42B1874E7571006B01D193236A /* FIRComponent.h in Headers */, + 4E6779841CEEC7E062C3DDBC2C1A8E30 /* FIRComponentContainer.h in Headers */, + 0EF1FF5F99EE2A59390ECCBD150F9B2F /* FIRComponentContainerInternal.h in Headers */, + FD7F72040DB7EC368013484D68BCB390 /* FIRComponentRegistrant.h in Headers */, + 9573A39A5B2D8120844A1A22A909A7E9 /* FIRComponentType.h in Headers */, + FB5815E73AE7D2F30F2A1F6DA536F734 /* FIRConfiguration.h in Headers */, + 0BA4942A6786CA873CC79CCF36D9DA7A /* FIRCoreConfigurable.h in Headers */, + B97715B074DD015049F7C6056713E29B /* FIRDependency.h in Headers */, + 9E03B75725537F8412899567BA9394E4 /* FirebaseCore-umbrella.h in Headers */, + D63B77317FAD75B5F54E67E7E04FF9EA /* FirebaseCore.h in Headers */, + 8B43C59858DED237E3786E5F3AB70D6A /* FIRErrorCode.h in Headers */, + 46E2E6FD4716F8A87899ABEDB1D0FFAB /* FIRErrors.h in Headers */, + 113D9C1ABD48861DCDD18601A45FF94D /* FIRLogger.h in Headers */, + 63C19BC1145BB84720BEF7EE79153EC2 /* FIRLoggerLevel.h in Headers */, + 6CF756C57C23BF6F5A1FAB3F1B431644 /* FIROptions.h in Headers */, + 0933B8143BA9B7E6C7D01554FCAF47CE /* FIROptionsInternal.h in Headers */, + BAE01E725AF8874AE1DB20B03A6203A2 /* FIRVersion.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EDF83EF5EB518076A330E170CD623C28 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1C3E3391EF8586FB2143ACAF7B1566CF /* arena.h in Headers */, + 1C13280129B885038A3834521227F59F /* atomic_pointer.h in Headers */, + 325607B89D32DD326199802A96BA7FDC /* block.h in Headers */, + F50BA6C5F68F87995ADA06093066BC83 /* block_builder.h in Headers */, + 9CFEAE301C59570D6D3DA95230320489 /* builder.h in Headers */, + 8AE5B4E76F36101F229C99A8FE310AF6 /* c.h in Headers */, + 924C93CD57FD4D8B0BB521D029C213C8 /* cache.h in Headers */, + 17076EA730EE24E55BAE34DD6E396981 /* coding.h in Headers */, + 486CCCA59EF8A90677252B35E81D55A0 /* comparator.h in Headers */, + 8CE510C277C94E23FBE508EF8A8647E1 /* crc32c.h in Headers */, + E1FB6E47F4DA786A554ECABEFF0C2C92 /* db.h in Headers */, + 768E4C922333EE473BCDB6A61A9A8A66 /* db_impl.h in Headers */, + 6223F9434C725407774B4930C2660A26 /* db_iter.h in Headers */, + 0E35A626E81D71D3E50DF441EE4F64C6 /* dbformat.h in Headers */, + 4F7E93244E6EBA9F51F04339DD737073 /* dumpfile.h in Headers */, + CF5531D76E8EAB68B67F2DAD7DAB2ECC /* env.h in Headers */, + 9D082A4BAD5FFDC3251EF756CA1D2416 /* env_posix_test_helper.h in Headers */, + 89EBDC231BA2B1DF7AD7DFA458D17BC9 /* filename.h in Headers */, + 74A73562EB95A5EEFFFF917305018EBE /* filter_block.h in Headers */, + BDDA69765D87A7963F202AE241B89763 /* filter_policy.h in Headers */, + 8F8C9875A9F9F8D337FF5199CAA68C72 /* format.h in Headers */, + 69FFEB2C81454309F26E72BD9A13C52B /* hash.h in Headers */, + F8AEC5CF8A3C66AA46D007EC1978499C /* histogram.h in Headers */, + B29B2FF52E45F040E233DBE345D93C3C /* iterator.h in Headers */, + 628145EF2395C53BB600EA8641CE1C20 /* iterator_wrapper.h in Headers */, + 301398C5A141B873CFFFC2BC58D9554E /* leveldb-library-umbrella.h in Headers */, + 3BCBDCDEE41BEB8D092EF0F443C31939 /* log_format.h in Headers */, + 12A87352FBA9C701F1DE64327348E88B /* log_reader.h in Headers */, + 8A1743A0B92B4BC98B48E7B6BC53BE72 /* log_writer.h in Headers */, + CDBA72F70214E97B05B346571C061516 /* logging.h in Headers */, + CCA187E70B5B329E24221A04EAA3D921 /* memtable.h in Headers */, + 8E21CA3FA72F455B14BEA2C693801F30 /* merger.h in Headers */, + D148E6E258FC6F12CB003213A394CC27 /* mutexlock.h in Headers */, + 2B8D115E3E217504C48E7FA4FC0EDA21 /* options.h in Headers */, + A73F734767E6743486C676B21E73248F /* port.h in Headers */, + 0E44BBAFC10FC09254CCE56198907BC0 /* port_example.h in Headers */, + E0364B3BCCA113AE22C7DCE6C699E270 /* port_posix.h in Headers */, + 6433C81AF0C5DA546C3CB18178217D51 /* posix_logger.h in Headers */, + 4E6490103AD4C01FEEDEB1492F50E7ED /* random.h in Headers */, + 098D39DE9C26B96FF172AB259D640933 /* skiplist.h in Headers */, + 5B1DC8529230CE7C22BA6D8A25E6C00E /* slice.h in Headers */, + 291689F2D49EF325CEE2B90FF45A455F /* snapshot.h in Headers */, + 4054A9F1886D80E232E7F8A23BAC7723 /* status.h in Headers */, + 3AE2C846212FDE3A0D35AEBD9634F435 /* table.h in Headers */, + 8F405808BD87E3BBE378B0603B4D40C3 /* table_builder.h in Headers */, + 5A0505E2BCD1A56DDE9240ECBC8E5B6C /* table_cache.h in Headers */, + C7283CB7A4B5D66F5A00DD9461455EA9 /* testharness.h in Headers */, + 7F3966E4CADB8FDDCEB38E84FCBA9624 /* testutil.h in Headers */, + 57D471726EB811900977AB76D0707B5B /* thread_annotations.h in Headers */, + EC7D5D576BA9442D32662E04DC89C376 /* two_level_iterator.h in Headers */, + 64720DDC437A6AFF98E03E4171BD2DA0 /* version_edit.h in Headers */, + 02AF93487363E896109B3F58B61028F3 /* version_set.h in Headers */, + BBD97223BD1446C5294CFD97217EB9C8 /* write_batch.h in Headers */, + D44C4FB4CA27374589D832296CDA9E24 /* write_batch_internal.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F149A53EC56795B8FA49252280713E2C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 8179683A38863728D22BED491ACCE9EB /* GoogleUtilities-umbrella.h in Headers */, + 3BAF57213FACE87FE0C29899BED430B2 /* GULAppDelegateSwizzler.h in Headers */, + 1D0568C93F531DD88D40C1D41F3104F2 /* GULAppDelegateSwizzler_Private.h in Headers */, + 1142CEB92FD7C6973C88BFF238734F0D /* GULAppEnvironmentUtil.h in Headers */, + 21C6416C31381FB9A488704B9630974C /* GULLogger.h in Headers */, + 175DA115BFD549B441954D52D8AAAC64 /* GULLoggerCodes.h in Headers */, + 56CE3CA5B155BFDAAA493A3D4A3EF23E /* GULLoggerLevel.h in Headers */, + A5EA29A17C261ED07A110CB9A173F935 /* GULMutableDictionary.h in Headers */, + 20EF9D10AB576BC24251E96085D7F62E /* GULNetwork.h in Headers */, + 11A6111284FE6C233703C63342B7EC9E /* GULNetworkConstants.h in Headers */, + DA1FF83D60E6D712581112569DD294A8 /* GULNetworkLoggerProtocol.h in Headers */, + 59C56D1D7201D9B5B8CE9E54AF9B2E95 /* GULNetworkMessageCode.h in Headers */, + 5E2F59B3A8B8FDDF66FF0F68422A1E3F /* GULNetworkURLSession.h in Headers */, + B62A8D5961AD2F9A03B21D323C62ECCE /* GULNSData+zlib.h in Headers */, + 5852CD41D79618A1A99D420BBADD0582 /* GULOriginalIMPConvenienceMacros.h in Headers */, + DC40B66CE40C4E3B04D2F68C8209D1B6 /* GULReachabilityChecker+Internal.h in Headers */, + 89D795ED6041C05C9DDF850DD49F8917 /* GULReachabilityChecker.h in Headers */, + B08F493AB57C446D1EC511CEB2C7C7F4 /* GULReachabilityMessageCode.h in Headers */, + 7826535FD4DABDA421D8C6E7CD42ECAC /* GULSwizzler.h in Headers */, + B399205633C66F3A49FA4FEF210EF899 /* GULUserDefaults.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F1F9F9531B1344EBEE9E3F109DE5C2BF /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B50F7E98D2795259EF39E7E44FECDA83 /* Any.pbobjc.h in Headers */, + 340AF0D010C3FBE18AC80F6970AA75A4 /* Api.pbobjc.h in Headers */, + 3AED228769079FB813068D1107E25600 /* Duration.pbobjc.h in Headers */, + C8313C281C9825C9EABE1DBF7B3F2C2A /* Empty.pbobjc.h in Headers */, + A5725DFB68A04C2F41E1F4C706BB9AA9 /* FieldMask.pbobjc.h in Headers */, + 9D1F78E0A3A1BFF5C718B1DFA231C34B /* GPBArray.h in Headers */, + EDBB097C0CEB77890B6959D4F3030453 /* GPBArray_PackagePrivate.h in Headers */, + 852964614DD810C12A603E75C40BA3B0 /* GPBBootstrap.h in Headers */, + CFDA8C7A2776F27B257992ACFA1185DE /* GPBCodedInputStream.h in Headers */, + 3C27259E4A251B723DB260F8E8B093C2 /* GPBCodedInputStream_PackagePrivate.h in Headers */, + 7C9EBC2B228C85FDAC569E808C145AC7 /* GPBCodedOutputStream.h in Headers */, + 542F9065606868FD1C4D3B037C23AAEA /* GPBCodedOutputStream_PackagePrivate.h in Headers */, + E3EBD4580C136F8662DEF6C0AF183E92 /* GPBDescriptor.h in Headers */, + E8F98280A695BFA4DC61848984B6331D /* GPBDescriptor_PackagePrivate.h in Headers */, + A849D47CADC35E2A18350D030F91517C /* GPBDictionary.h in Headers */, + 1C9B3629CD3832E8A80E399A9092C67B /* GPBDictionary_PackagePrivate.h in Headers */, + 97256A880C9E1703AE973ACB6C876D11 /* GPBExtensionInternals.h in Headers */, + 6D84BA31BCA85CED9BBE25DF9E0E7F62 /* GPBExtensionRegistry.h in Headers */, + F9B47D5D75BD7001B20EFFEBDC0B9405 /* GPBMessage.h in Headers */, + 2EFF484EE070D8D5ADFA763EE9AA7A25 /* GPBMessage_PackagePrivate.h in Headers */, + DACBFF3914E67388390A40ABFBA75E9F /* GPBProtocolBuffers.h in Headers */, + 5EE3238F838EA583FB7B86B771BDD2E5 /* GPBProtocolBuffers_RuntimeSupport.h in Headers */, + 354F3E70D371F81CBE9E65D860DD86DA /* GPBRootObject.h in Headers */, + D4AD505B3781844D264770E4100919DD /* GPBRootObject_PackagePrivate.h in Headers */, + 0BB00BA9640DB56A47581FF4BA450A91 /* GPBRuntimeTypes.h in Headers */, + 6EB593B56B0ECD3102EA3AC011BE3EFE /* GPBUnknownField.h in Headers */, + ACC05312D7A505AD2942AC3A9DE928E5 /* GPBUnknownField_PackagePrivate.h in Headers */, + 168F962D694946E2CD87CF2C579C02F4 /* GPBUnknownFieldSet.h in Headers */, + 7A9F1AD0FFE9227575A38C84A461D201 /* GPBUnknownFieldSet_PackagePrivate.h in Headers */, + 40EACB0ABE34F98A1888FCFF5BBD896C /* GPBUtilities.h in Headers */, + 33153F8D6F74310F412A8F8916D03CEE /* GPBUtilities_PackagePrivate.h in Headers */, + DFDCA2C1D1E4735F104BD9503325207A /* GPBWellKnownTypes.h in Headers */, + 8EF46D58696F4E6DFFD3D1EEA14296DB /* GPBWireFormat.h in Headers */, + E44E5222DF7101874E3C9AAA08364171 /* Protobuf-umbrella.h in Headers */, + A21B7401B0E0A0135B948EDCE3282E0B /* SourceContext.pbobjc.h in Headers */, + 94CB139653C686BBA6278C82D68FC7E9 /* Struct.pbobjc.h in Headers */, + 3C63E9595463B8F3754AAE476EAFF25A /* Timestamp.pbobjc.h in Headers */, + 9DC8CFAA009F051AACF5CB1CAE2BFF4E /* Type.pbobjc.h in Headers */, + ACFA8328FABDD65ED17C942F663AC616 /* Wrappers.pbobjc.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 02D15C1D5707E16044A2D3B6345FDAA6 /* Pods-My MindUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9ABF9020C478812FA9F1FF75678AA4F4 /* Build configuration list for PBXNativeTarget "Pods-My MindUITests" */; + buildPhases = ( + 57C52AF6FB1F0C7A84FE2907C89FAD18 /* Headers */, + 05B159CDF5C61B7C0F3EE72A8ADD17DA /* Sources */, + 4E6529B2B4149EC8AFC03CF39D542F5B /* Frameworks */, + 92E4CF7EAB23EA05AFCE3B303C9F3E42 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D0579349E04C228BAA8781C0DD90DC82 /* PBXTargetDependency */, + ); + name = "Pods-My MindUITests"; + productName = "Pods-My MindUITests"; + productReference = EBF8441A787609A9C03B1FAB585F4CCF /* Pods_My_MindUITests.framework */; + productType = "com.apple.product-type.framework"; + }; + 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */ = { + isa = PBXNativeTarget; + buildConfigurationList = 08BEB47E01CCCC54133E9FD5806B7A24 /* Build configuration list for PBXNativeTarget "FirebaseCore" */; + buildPhases = ( + DE2487C6BD5252B0CD439F0590C7C2CA /* Headers */, + B7E6C01410DFF20EF40D216396A2738B /* Sources */, + D5F6CCE4A47F38EFF44ABEC022EA2AB6 /* Frameworks */, + 8F381B08A55CD241B6186756249C4D2F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 837D1036EB37E1FD7CE11AEEFE789A07 /* PBXTargetDependency */, + ); + name = FirebaseCore; + productName = FirebaseCore; + productReference = 03FA546BF26C2C92243ACD81C404B4DF /* FirebaseCore.framework */; + productType = "com.apple.product-type.framework"; + }; + 079E4F97855B7901F483AA030B2B7C5C /* FirebaseAuth */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8F61149C31EE7C6C9D64D111695E794B /* Build configuration list for PBXNativeTarget "FirebaseAuth" */; + buildPhases = ( + 18421998863481230011ABC9E1034D8D /* Headers */, + D58FC9A6E4BBCA83BF88118CB1332325 /* Sources */, + B5AA29F197F968B04B5A425EF066C65A /* Frameworks */, + CD4E27BB7F7A6DB80D29CC0140AE5860 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 871AB9E9665D6EF6C869BEE3D1B36E66 /* PBXTargetDependency */, + 4127704CC0ED1A600673DBBB09B2ABC5 /* PBXTargetDependency */, + B697592FD3A1CF6A07F0F8DABF4DC74E /* PBXTargetDependency */, + ); + name = FirebaseAuth; + productName = FirebaseAuth; + productReference = CADBF9EAB8E6375218D133DE8EC36296 /* FirebaseAuth.framework */; + productType = "com.apple.product-type.framework"; + }; + 1D9FB04B52C841F3FC0250CBC62A374F /* GTMSessionFetcher */ = { + isa = PBXNativeTarget; + buildConfigurationList = B593C18D2023F49F69D7184CC2DC4396 /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */; + buildPhases = ( + 4234DC53A2151EE74A18DB251F11BA7C /* Headers */, + BE6A47E0C76E94D1CE3E04BCC48BD237 /* Sources */, + 9B08098DF508E32B908F1F589E4B8AF4 /* Frameworks */, + 2BA5B697DACA81AFAD97BA94415AA7B7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GTMSessionFetcher; + productName = GTMSessionFetcher; + productReference = 9BF758753C1447148E55B242D5A8D189 /* GTMSessionFetcher.framework */; + productType = "com.apple.product-type.framework"; + }; + 263F7002FD4F2FB368F105A900F31A18 /* FirebaseStorage */ = { + isa = PBXNativeTarget; + buildConfigurationList = B936FBFBA98BB09A0992AC486F0255C8 /* Build configuration list for PBXNativeTarget "FirebaseStorage" */; + buildPhases = ( + 8D0A1668A59890BC1718C45DA1EEBB11 /* Headers */, + 7DDF797B5F9A0B9E6142E81723FD18D5 /* Sources */, + CE33C54DF5DB61D9669BEB4C03781675 /* Frameworks */, + 722BC1394BD1A91D2BEDA512C0BEDD24 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 66B98059846202D9D21951DFB44D3ADD /* PBXTargetDependency */, + CA6F8130F959B3A83104E6BEE0135093 /* PBXTargetDependency */, + 430336A65140D8EE34E616534122C702 /* PBXTargetDependency */, + ); + name = FirebaseStorage; + productName = FirebaseStorage; + productReference = E35D272AECCFDD36EEA858CFE9754389 /* FirebaseStorage.framework */; + productType = "com.apple.product-type.framework"; + }; + 8364BB258018143B83798DE31C13546D /* nanopb */ = { + isa = PBXNativeTarget; + buildConfigurationList = A54B95AC2E23BB0947B35EFE5E1F0EFB /* Build configuration list for PBXNativeTarget "nanopb" */; + buildPhases = ( + 4A34A8C4C4BFB14D6E0504833C9159DA /* Headers */, + 12D3F587AEF7D8BD85FB723377576392 /* Sources */, + 6E984081A095D70D07D998B48BC38F15 /* Frameworks */, + FFEE618D0ABA9FE323734237056FF21F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = nanopb; + productName = nanopb; + productReference = C22FFA05A12B4D3BDF4C4307840FD4E6 /* nanopb.framework */; + productType = "com.apple.product-type.framework"; + }; + 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */ = { + isa = PBXNativeTarget; + buildConfigurationList = 557DBB73FFE1746960D722CA99CD0144 /* Build configuration list for PBXNativeTarget "GoogleUtilities" */; + buildPhases = ( + F149A53EC56795B8FA49252280713E2C /* Headers */, + 8AD5B0D0121E233A26B05140AB645AC4 /* Sources */, + 143A6B1F015B3C428A965831E8D28387 /* Frameworks */, + 67479063FCDC81E6DAE5B7498FA1545C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GoogleUtilities; + productName = GoogleUtilities; + productReference = 6E31586DA53A4DBE99F094125C8BEF15 /* GoogleUtilities.framework */; + productType = "com.apple.product-type.framework"; + }; + 93AB79BD5DB2C6B4F890C0F391AE1FBC /* Protobuf */ = { + isa = PBXNativeTarget; + buildConfigurationList = 50E9A67E65D93CA129312A07FA3346B5 /* Build configuration list for PBXNativeTarget "Protobuf" */; + buildPhases = ( + F1F9F9531B1344EBEE9E3F109DE5C2BF /* Headers */, + D4269F4AE4A01A17E4D0123D71A7F27A /* Sources */, + CECA8FCA1D8F6F5CD8AE4C60FC35F5CB /* Frameworks */, + 5413078A8BD4EBC3187A7F9D5E1C63FD /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Protobuf; + productName = Protobuf; + productReference = 4EB8204C84A0257A6B1C9421827E0260 /* Protobuf.framework */; + productType = "com.apple.product-type.framework"; + }; + B01DE4F80FFD6ECD3AC72050910AF61D /* SwiftForms */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4D9DDDAED363D608DA18A16151BCB212 /* Build configuration list for PBXNativeTarget "SwiftForms" */; + buildPhases = ( + 1FE6BE7F2771B9FB3C962850E327CB9F /* Headers */, + 1E5A4CD61D15CD357597E4019E51E6CB /* Sources */, + 09566CECE9666F15B9F3099A22879D47 /* Frameworks */, + 0DFEA004D266C4A8D9620AE2BF761629 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftForms; + productName = SwiftForms; + productReference = 47A0DD80F32294AC8CB5952EC5A56807 /* SwiftForms.framework */; + productType = "com.apple.product-type.framework"; + }; + B9B45D12C08E85F7863BC9EB04B3A850 /* FirebaseDatabase */ = { + isa = PBXNativeTarget; + buildConfigurationList = 92C2657A497FE026F77D23DB42524144 /* Build configuration list for PBXNativeTarget "FirebaseDatabase" */; + buildPhases = ( + 3261BA1F995ABA893077E5C3EC39AF7D /* Headers */, + CB25C5103E605129988479F5CD3CE5B3 /* Sources */, + C37D2CEF682C0259FB70478168453E22 /* Frameworks */, + 16EC8CDEB3BE048395F5601D9CA91BA5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + F39EE1E73FC9AE481222451099AF18F7 /* PBXTargetDependency */, + 905C20FDA684048F8B39FD0449C6158D /* PBXTargetDependency */, + FC8B52D7ABE4D1C5342D0619AF8DEE80 /* PBXTargetDependency */, + ); + name = FirebaseDatabase; + productName = FirebaseDatabase; + productReference = D1B6EF52D08A5CB66B19509A9FA26392 /* FirebaseDatabase.framework */; + productType = "com.apple.product-type.framework"; + }; + C100612F1EDBD55A1B6D1E3E77D14080 /* Pods-My MindTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = D74A910542F89F47C850C6BFE968F24F /* Build configuration list for PBXNativeTarget "Pods-My MindTests" */; + buildPhases = ( + 461E772F8F3FC0BD38003BAAB4AE1D5C /* Headers */, + 88A9F2A1D5309F081C8B45876961DEB7 /* Sources */, + A28F455D6452C719007E7AE725EACC1D /* Frameworks */, + CF8653170A6F153CC4FB6AAE50F6DCB4 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 1EFDE9DFEF9103FCD9FD939C5D26838F /* PBXTargetDependency */, + ); + name = "Pods-My MindTests"; + productName = "Pods-My MindTests"; + productReference = B662A5489E41A07B7B8124D85511A255 /* Pods_My_MindTests.framework */; + productType = "com.apple.product-type.framework"; + }; + CFE9294A3948C71B6B365E1AE070CDA5 /* Pods-My Mind */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8DFE20DD733100533E2F990F4FCD4267 /* Build configuration list for PBXNativeTarget "Pods-My Mind" */; + buildPhases = ( + B5C2C9A521EC90CF270CCCF52808B52D /* Headers */, + D9E95E66FF76FB26D79C608230A20C24 /* Sources */, + AF423F5CC7B9F0D02502F027B8E03B23 /* Frameworks */, + AC7289DB55FE8890F4DC044A9D8822D7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 51D9E709DC9B2BEA7F6F56D14161EC7E /* PBXTargetDependency */, + 4CE1EA8EA3E9AE16AFD64E6B41A715F0 /* PBXTargetDependency */, + B3CF748C58ED214D1830FFABE0C7B911 /* PBXTargetDependency */, + F2A7D8DA002A61EF46E91D3891B43841 /* PBXTargetDependency */, + 4550D193C6A5942BAC22632DD446BD55 /* PBXTargetDependency */, + 1AECE3B54B15BF525F138226524AD755 /* PBXTargetDependency */, + 7023D1567CED3A6565F1C371BC795C12 /* PBXTargetDependency */, + ADE25216AABFBB6F0BB28A0C34A44BC2 /* PBXTargetDependency */, + E3D1B24BC63633CB96F20F27D0499E8D /* PBXTargetDependency */, + 0B2617E2A7F0C5BE2543532EECF94DB9 /* PBXTargetDependency */, + BD7B3AFBBF75058104A9AC2095407131 /* PBXTargetDependency */, + ); + name = "Pods-My Mind"; + productName = "Pods-My Mind"; + productReference = 7D37B39157C7D0EC71A0F813C9CFC9AA /* Pods_My_Mind.framework */; + productType = "com.apple.product-type.framework"; + }; + F7293FA58AFAF74ECAAB1C4796C45F5B /* FirebaseMessaging */ = { + isa = PBXNativeTarget; + buildConfigurationList = 710E05D74490C1F833687AF1F4D76EBD /* Build configuration list for PBXNativeTarget "FirebaseMessaging" */; + buildPhases = ( + 29EC56FBA7129F938D405973B6BAC2E6 /* Headers */, + F5EAE135ABECBFA7F3037A131EE462A3 /* Sources */, + 048B27D4FC4365B1E9007F9DA49AC3CB /* Frameworks */, + 43D30E4DFD6C1466BDBEC19E2EA295EA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + D17F192BFDAF5950EDDE420D885C8599 /* PBXTargetDependency */, + 647C630C1C5AC7E5D27EC72B3B68617B /* PBXTargetDependency */, + ACFF71D3652B637314D4B716E2A0146F /* PBXTargetDependency */, + ); + name = FirebaseMessaging; + productName = FirebaseMessaging; + productReference = 81E8A3CD852063E84294E4611723E4AE /* FirebaseMessaging.framework */; + productType = "com.apple.product-type.framework"; + }; + FE47F11E708D633621DB136BD3CD0034 /* leveldb-library */ = { + isa = PBXNativeTarget; + buildConfigurationList = 36174492661C12BE4B7835554F9731EA /* Build configuration list for PBXNativeTarget "leveldb-library" */; + buildPhases = ( + EDF83EF5EB518076A330E170CD623C28 /* Headers */, + C6E2BE0860C0E435748B4ECC7B80508B /* Sources */, + 0655C48C728F73F99BC5AB1B11AB5EC3 /* Frameworks */, + 70B63B9A4FAD4236F524554C3149149F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "leveldb-library"; + productName = "leveldb-library"; + productReference = 50E2D1A1F604F7B2D4C65D599DB5CFF4 /* leveldb.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = ECE75CA4E7E40274859412AB3EC76863 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 079E4F97855B7901F483AA030B2B7C5C /* FirebaseAuth */, + 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */, + B9B45D12C08E85F7863BC9EB04B3A850 /* FirebaseDatabase */, + F7293FA58AFAF74ECAAB1C4796C45F5B /* FirebaseMessaging */, + 263F7002FD4F2FB368F105A900F31A18 /* FirebaseStorage */, + 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */, + 1D9FB04B52C841F3FC0250CBC62A374F /* GTMSessionFetcher */, + FE47F11E708D633621DB136BD3CD0034 /* leveldb-library */, + 8364BB258018143B83798DE31C13546D /* nanopb */, + CFE9294A3948C71B6B365E1AE070CDA5 /* Pods-My Mind */, + C100612F1EDBD55A1B6D1E3E77D14080 /* Pods-My MindTests */, + 02D15C1D5707E16044A2D3B6345FDAA6 /* Pods-My MindUITests */, + 93AB79BD5DB2C6B4F890C0F391AE1FBC /* Protobuf */, + B01DE4F80FFD6ECD3AC72050910AF61D /* SwiftForms */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 0DFEA004D266C4A8D9620AE2BF761629 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 16EC8CDEB3BE048395F5601D9CA91BA5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2BA5B697DACA81AFAD97BA94415AA7B7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 43D30E4DFD6C1466BDBEC19E2EA295EA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5413078A8BD4EBC3187A7F9D5E1C63FD /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 67479063FCDC81E6DAE5B7498FA1545C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 70B63B9A4FAD4236F524554C3149149F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 722BC1394BD1A91D2BEDA512C0BEDD24 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8F381B08A55CD241B6186756249C4D2F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 92E4CF7EAB23EA05AFCE3B303C9F3E42 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AC7289DB55FE8890F4DC044A9D8822D7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD4E27BB7F7A6DB80D29CC0140AE5860 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CF8653170A6F153CC4FB6AAE50F6DCB4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FFEE618D0ABA9FE323734237056FF21F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 05B159CDF5C61B7C0F3EE72A8ADD17DA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9A441035833444784D7509CA2274A15D /* Pods-My MindUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 12D3F587AEF7D8BD85FB723377576392 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AAA6A3680C85C31B477E4C906DE9815A /* nanopb-dummy.m in Sources */, + 3552218D2E421ECA1909B93DE2FB959A /* pb_common.c in Sources */, + E1331724A7D92526AA8714A62C353932 /* pb_decode.c in Sources */, + C46B7BDE25252D8EB990DEB9FE7CD98A /* pb_encode.c in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1E5A4CD61D15CD357597E4019E51E6CB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C1579705A30E8A4283F5EDC8FF17E722 /* FormBaseCell.swift in Sources */, + 5CC6E195CEB090320F1043908AB8230F /* FormButtonCell.swift in Sources */, + 576B780EB0F264CCD3F1CE5ACA2BF735 /* FormCheckCell.swift in Sources */, + D53F8A96A3A82548FA5B748DED22E71F /* FormDateCell.swift in Sources */, + 129D0B6856747307C78384677F0EA9A8 /* FormDescriptor.swift in Sources */, + C9C0B4BB9BA06272DB368B8614330EBF /* FormErrorType.swift in Sources */, + 2D416CF9647A1D41764FC0B641EC3680 /* FormLabelCell.swift in Sources */, + DF15FDB3F4D296543616C1E6A56095AD /* FormOptionsViewController.swift in Sources */, + 67896D50B905AD4D1CF1CDBB4C45B69E /* FormPickerCell.swift in Sources */, + C9F9E263A24E8AE7BF2935B7ABACC1A0 /* FormRowDescriptor.swift in Sources */, + 8930870A3F0B1CA5E2B0A8AE0FC85E65 /* FormSectionDescriptor.swift in Sources */, + 1B911D16F99091B023C6540EA1D32429 /* FormSegmentedControlCell.swift in Sources */, + 18FC768873FF702F8DB65711690D44B8 /* FormSelector.swift in Sources */, + 2F7ED73B8E278D8E2567BAB379F45E29 /* FormSelectorCell.swift in Sources */, + AD37135DC0DB285AFC99A22A3F897490 /* FormSliderCell.swift in Sources */, + 348369D5DA54EAB1F012E5CF19D8B977 /* FormStepperCell.swift in Sources */, + B430087BF184C63ABD230D79C25CD2AA /* FormSwitchCell.swift in Sources */, + 134B54AFE31E2FA28DFE3E62CCBCB5E8 /* FormTextFieldCell.swift in Sources */, + 50BD3989AE60FFA4765A541B33E12CEB /* FormTextViewCell.swift in Sources */, + AB3D618502A72118FD94B77559972F94 /* FormTitleCell.swift in Sources */, + 0C01DD7C812E040851CB1CC9460D7395 /* FormValueCell.swift in Sources */, + 3DF871716311E62315A34CD7C8F9C33F /* FormViewController.swift in Sources */, + 9F93A98552CEFCF21E07766F5EAEA70C /* SwiftForms-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7DDF797B5F9A0B9E6142E81723FD18D5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F8203C8632BDE999A4E00CB2889D8335 /* FirebaseStorage-dummy.m in Sources */, + A7FD3C6C20D1B714EECB1AB525B644CC /* FIRStorage.m in Sources */, + 3BD76326DB9C201D468A25CE8FA76385 /* FIRStorageComponent.m in Sources */, + C158CEB5D86B674A8465E4E728AF8B07 /* FIRStorageConstants.m in Sources */, + AD63FBD4D1294275A34F7BCCA484DAFB /* FIRStorageDeleteTask.m in Sources */, + F14821044B905357952ED2C034E4EFE2 /* FIRStorageDownloadTask.m in Sources */, + B68DE0A647FBC539D64F54CEEB48457E /* FIRStorageErrors.m in Sources */, + DAB46EECC9CD909B9D94A99C5199B404 /* FIRStorageGetDownloadURLTask.m in Sources */, + 33DB72BBA56DA8E1C805ED2E2E4B54F2 /* FIRStorageGetMetadataTask.m in Sources */, + 487D4FA6D383090AF1FDFA2788750733 /* FIRStorageMetadata.m in Sources */, + 4F27DEC670F58C1CDE0DEF1A7980FF61 /* FIRStorageObservableTask.m in Sources */, + 3C1068790CF9D585AD77DF3E1315A0CE /* FIRStoragePath.m in Sources */, + 841D495A62791DC4B0466079DC984B7D /* FIRStorageReference.m in Sources */, + B15FAD9698A196CC3BB3AF6C8667174F /* FIRStorageTask.m in Sources */, + 3854182705A3B78779D0647C64563A5C /* FIRStorageTaskSnapshot.m in Sources */, + C5E18F0229FECB6A224E9BB84B24D01B /* FIRStorageTokenAuthorizer.m in Sources */, + FC8F9A024980EE037EF01526DE755F73 /* FIRStorageUpdateMetadataTask.m in Sources */, + C844AE38BDC6715DD6EE51E916387384 /* FIRStorageUploadTask.m in Sources */, + AFCA0EFE9E8B6485C7A8F7CA43D602BF /* FIRStorageUtils.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 88A9F2A1D5309F081C8B45876961DEB7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E1438306E11939418AD03177AABF914B /* Pods-My MindTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8AD5B0D0121E233A26B05140AB645AC4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 989072EAAF89F56C19082F03F44BC651 /* GoogleUtilities-dummy.m in Sources */, + 3CBF93EAA1696DDB4018A4C62F998BAD /* GULAppDelegateSwizzler.m in Sources */, + B75837C0F6C779AC4282214C006E2216 /* GULAppEnvironmentUtil.m in Sources */, + 70928302085AE04DB9746B001674CE27 /* GULLogger.m in Sources */, + 9F8F2160FBFD10AE2A50392D7790174A /* GULMutableDictionary.m in Sources */, + FCB071251982ECB470039552530F1929 /* GULNetwork.m in Sources */, + AFAEE5182834B4C8EFA6D64690E031AF /* GULNetworkConstants.m in Sources */, + 5B5196373311E7FE070DA0D6FCB350F4 /* GULNetworkURLSession.m in Sources */, + 7696AE486EF953B157CA394CA58038F6 /* GULNSData+zlib.m in Sources */, + BFD9303E479CEC6B0B47F68FD2B27D8A /* GULReachabilityChecker.m in Sources */, + 8174236DC749231BF30A02C9AC3AC6B7 /* GULSwizzler.m in Sources */, + 7869B64F2F6316126593CD189194BD7C /* GULUserDefaults.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B7E6C01410DFF20EF40D216396A2738B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 85FBEBEB3DB2EAC5E24917BD74E59A0F /* FIRAnalyticsConfiguration.m in Sources */, + 21842223F770DB476AFE71048612A2E6 /* FIRApp.m in Sources */, + B51FB50D2F16065E0790C48862B3F57C /* FIRAppAssociationRegistration.m in Sources */, + CBD9D9FEF949FE5836428B658521B61F /* FIRBundleUtil.m in Sources */, + 3AB59DB71D3090FADB8183AE459C74CA /* FIRComponent.m in Sources */, + 4BFD85854D4CC225E5D0E0C02AB1F970 /* FIRComponentContainer.m in Sources */, + 3EC4BE7BB60B0244BAFF076A8AE4433E /* FIRComponentType.m in Sources */, + 3F3C9BDE53A474F9FC7F868981B2CEB6 /* FIRConfiguration.m in Sources */, + 0BBD78F0EFC19D7ADA110339ECCCBE66 /* FIRDependency.m in Sources */, + 21FB0279FB718F75BA6BF98940DE1583 /* FirebaseCore-dummy.m in Sources */, + 92E42418FF51A6A36710FA1E194477CA /* FIRErrors.m in Sources */, + 29F9CCFDD78C5672F24E811CD3B0E2F4 /* FIRLogger.m in Sources */, + 90DF1C506A6C5A5FA346CCD9865D768F /* FIROptions.m in Sources */, + 93CC152EEB0129345190C43B718BF810 /* FIRVersion.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BE6A47E0C76E94D1CE3E04BCC48BD237 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C618198B2C60599D8145F46F099AA22C /* GTMSessionFetcher-dummy.m in Sources */, + 2CF6B039692393B64EFF5E324CE42D4A /* GTMSessionFetcher.m in Sources */, + 70FFEA217864AEC22E6C5044CD8A056D /* GTMSessionFetcherLogging.m in Sources */, + 4C5B18F99A500A35BBBBD1334A2B6B41 /* GTMSessionFetcherService.m in Sources */, + 3F1CBF3B83300E405EC2DE2B6AE39D23 /* GTMSessionUploadFetcher.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C6E2BE0860C0E435748B4ECC7B80508B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 930F2FF02203E6CB571BED9D9F09A1F6 /* arena.cc in Sources */, + 275030A0CA31B8AE5264A0C7EBDDDEC6 /* block.cc in Sources */, + C61F7E477F6279C45916FF4B21980000 /* block_builder.cc in Sources */, + 50F013648DC688B8B20C32505EA6C382 /* bloom.cc in Sources */, + D8221A14E706A3DB0A85E793A99374E2 /* builder.cc in Sources */, + D2E54B77503C52E26575B9DE2827DF2A /* c.cc in Sources */, + 6D8156FE32B106DF6B8857CAAB6B2223 /* cache.cc in Sources */, + 0A6FB62F43961D9D35D2867BB2105AB7 /* coding.cc in Sources */, + AFCE1D5598585C68B9343DB5D8EF6399 /* comparator.cc in Sources */, + 8F1C879CDF4B7467D7A14BEFD9A9CC7B /* crc32c.cc in Sources */, + 3CEAE8A4C8D8D58A5757E8E796EF3B53 /* db_impl.cc in Sources */, + DDE08ACF73840138341000C61CA4490C /* db_iter.cc in Sources */, + 0011998EDFF4EB77434BF209F237B958 /* dbformat.cc in Sources */, + CE4956F0A78784911D47BCD2DAD84623 /* dumpfile.cc in Sources */, + 438954B88A790ADEE370D7ED0BDEBE3A /* env.cc in Sources */, + D3AA9A65A800E8DD3170DD6258E922F9 /* env_posix.cc in Sources */, + 4F542E826FD21DDBA4C681804A65CD3A /* filename.cc in Sources */, + 1D88B103F90AC866D7DFE9B729D62F9E /* filter_block.cc in Sources */, + C98E0142CB91C34E929C9DE9FBF6D224 /* filter_policy.cc in Sources */, + E481B67B47D0D361698D7C25E5F37CE0 /* format.cc in Sources */, + 2D2C6D574E05173015E9564AF9EB5BFC /* hash.cc in Sources */, + 8F76064E137E3BA77FCA80B7D6158CD1 /* histogram.cc in Sources */, + 57D927E77D3F889440C8501AAE5DE1BF /* iterator.cc in Sources */, + E6B0529A710641111B7037A5A537E08F /* leveldb-library-dummy.m in Sources */, + 8F75852BB36E50EC5729B5B80EC4CD57 /* log_reader.cc in Sources */, + C48EB465AA17C95088814EFE0393D6BD /* log_writer.cc in Sources */, + 282648B588909BEEB93E033E2A7443A4 /* logging.cc in Sources */, + 638C0C0DD7C4929D902A92E254DC9499 /* memtable.cc in Sources */, + F82A5AC366CFE91701ACFD28EC220BCE /* merger.cc in Sources */, + ABBC5BE4B6A2CED9BFAC186DC0BE2906 /* options.cc in Sources */, + BCC43130C0575C0965175C4991E243E7 /* port_posix.cc in Sources */, + 3CAE8FEFEB344131C119530AFA591C69 /* port_posix_sse.cc in Sources */, + 9764C1B0913596D2CAB3162CE8E3C80C /* repair.cc in Sources */, + 80E37C99D8494655FC0ECEE03AE770CF /* status.cc in Sources */, + B5CE7589714FE2CD21F1D0B1BDFDA65A /* table.cc in Sources */, + DAEF6555B3B845FF7E1B17D126042F58 /* table_builder.cc in Sources */, + 32E6AFBABCDED50BD6674ADBF424A37E /* table_cache.cc in Sources */, + C4CC507BAD9328C705A2DD380EF7A743 /* testharness.cc in Sources */, + 5D3898F2B928E1836E8B005976695D62 /* testutil.cc in Sources */, + 0E75CBCE786C601A95861E47EFE43715 /* two_level_iterator.cc in Sources */, + 0BCF71114FA90D213BD09C4FCFBDACC7 /* version_edit.cc in Sources */, + 103B007712D7064A80989956B39C24F9 /* version_set.cc in Sources */, + BE8A86EADE6F55060A34AC780AA02110 /* write_batch.cc in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CB25C5103E605129988479F5CD3CE5B3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 426B07E572AE6BF3E73255E49A2AF5CE /* APLevelDB.mm in Sources */, + F9753EFE72DDA05B378A06869B06ACAB /* FAckUserWrite.m in Sources */, + 75F0BAEEAD9FA0C4B6A66F321E0B7E12 /* FArraySortedDictionary.m in Sources */, + 52071618C875E64E6D9194CE746A3C69 /* FAtomicNumber.m in Sources */, + D3DDF4ADB4EF49D92A32F6FC0E73C7CF /* FAuthTokenProvider.m in Sources */, + 28DB01DD6197B670D9B130A13F94C658 /* fbase64.c in Sources */, + 233B83B7F18D89E2529AA35E16AECC0B /* FCacheNode.m in Sources */, + FC45C279B8E52737EB95338D19C80A4B /* FCachePolicy.m in Sources */, + 4F27D04843A818AB2497F7B5E9940FB7 /* FCancelEvent.m in Sources */, + 6823BAB245286F703E96AEEF63B43FB9 /* FChange.m in Sources */, + 05B6D642BDBCB1168280F41EF68EA73E /* FChildChangeAccumulator.m in Sources */, + AB784186ECECAD178AD4C783CA5741A4 /* FChildEventRegistration.m in Sources */, + 2FE3E801B2DAC1823806BAFC895D0198 /* FChildrenNode.m in Sources */, + 904CB05DACC3D79481020A50AAE68E53 /* FClock.m in Sources */, + CD88C338FCBD71DF4640CB6ABDD89991 /* FCompoundHash.m in Sources */, + CD6C33BFBA4C3D155C2072F77FCD1FD2 /* FCompoundWrite.m in Sources */, + 93539082357CC56383E343DD7CAB9593 /* FConnection.m in Sources */, + 299A3A3BEAF3D0864955CA19E44C03A8 /* FConstants.m in Sources */, + 5582C24E7FA2D33481052628B91FFFBA /* FDataEvent.m in Sources */, + 453547D27DE8FE05B1E58BA16E43DFE8 /* FEmptyNode.m in Sources */, + D10ED50CAAF3832782ACF3AAD6D75E6C /* FEventEmitter.m in Sources */, + CD8B4B5DE997B41ABF856CD0BE8F6E44 /* FEventGenerator.m in Sources */, + 9DFA58FE5A84DF7925398E88CB2DD709 /* FEventRaiser.m in Sources */, + 9D9834578E28BF7E6BEA2422E9549B2E /* FImmutableSortedDictionary.m in Sources */, + 242FE609A5EDD5ED5E277D18691D773C /* FImmutableSortedSet.m in Sources */, + CF0D114993D521DB3B8DD3B313094F2D /* FImmutableTree.m in Sources */, + A5DF4177C85DB26614437E811E08FE87 /* FIndex.m in Sources */, + 12B88AB4B994635043A01E9CAAC78CFA /* FIndexedFilter.m in Sources */, + 1837B48509DD924AEB4F9AF8F374F019 /* FIndexedNode.m in Sources */, + 0BF462EC03EDCD8D42388A5AC89DA392 /* FIRDatabase.m in Sources */, + B0B91BFE07C9B52AEBDACBED9628E033 /* FIRDatabaseComponent.m in Sources */, + AEBA9FAD26195F4E46488F4A9D3B9A81 /* FIRDatabaseConfig.m in Sources */, + 977EA5854B5A4B76BC701A3A35BACBD8 /* FIRDatabaseQuery.m in Sources */, + A5A407C2729A90B75C962AF9BD33E9EB /* FIRDatabaseReference.m in Sources */, + 4A046A1D4CA6086E42794466D8E23BFF /* FIRDataSnapshot.m in Sources */, + AB8DDFE38D7B5293556C7A56CACB3CEB /* FirebaseDatabase-dummy.m in Sources */, + 0DFC6F43F874D2811BECEB7FDB15CC44 /* FIRMutableData.m in Sources */, + 2D02C1023D85C1462E5A83DD9AEE07CF /* FIRNoopAuthTokenProvider.m in Sources */, + DAB5C35644D90288ED1E80678F3FACDF /* FIRRetryHelper.m in Sources */, + 5E0104BFDBD44C748BAA576F4F444BAA /* FIRServerValue.m in Sources */, + 60497C5696879AE4F608DFED412C5623 /* FIRTransactionResult.m in Sources */, + 24C421100ECFE5936F377CA9005BC9F4 /* FKeepSyncedEventRegistration.m in Sources */, + 8C6BFF3CC31374AA158690844968F3E9 /* FKeyIndex.m in Sources */, + 65EF330A8AB7B7D638912E2E2BC1EAE7 /* FLeafNode.m in Sources */, + C1C5D1578131CB36F40DA4CD491FDEEA /* FLevelDBStorageEngine.m in Sources */, + 6C6AA17056A60A466B776DB74B5DAB3D /* FLimitedFilter.m in Sources */, + 88739CEF4AE0A08CE3DFAF1BE8E250F3 /* FListenComplete.m in Sources */, + 25149580AEC71D7F9773870BBD217ACA /* FListenProvider.m in Sources */, + 43332954BA84B54F3F6B5DFBA2EB46AE /* FLLRBEmptyNode.m in Sources */, + E0BE0E6CF6153C214D47E6C2217B9781 /* FLLRBValueNode.m in Sources */, + C6566B15A07342D13697FF1A12CA5C13 /* FMaxNode.m in Sources */, + B42C14815D5EAB949909816B361D918D /* FMerge.m in Sources */, + CF8A6FCAE3F7F5BF198B3F0B06884918 /* FNamedNode.m in Sources */, + 3B15CBA64BA1D735A7B945E03414E057 /* FNextPushId.m in Sources */, + 42B789CC191942A3436F0FA69BCEE805 /* FOperationSource.m in Sources */, + 0EA5E387DB55D1696950CF955C845EE5 /* FOverwrite.m in Sources */, + 457FDEBB956179777CBAF1347EA4836E /* FParsedUrl.m in Sources */, + 88B6FAD0644DED6B950AFB1B76FA5018 /* FPath.m in Sources */, + 7A999870D9DD45A47B8EBB3934B8A233 /* FPathIndex.m in Sources */, + 43ED2695655E0A26CA8B1A8F6909512A /* FPendingPut.m in Sources */, + D11731E80E979B54DE4D0EAE75A0BB31 /* FPersistenceManager.m in Sources */, + 50E0465D8A40B80F2887CBEBD3A7AD5E /* FPersistentConnection.m in Sources */, + C7A1DE80ACB2BD2D4B21508AF225D665 /* FPriorityIndex.m in Sources */, + 6831D5B934B5F86075416045FAAAB367 /* FPruneForest.m in Sources */, + D712BA1D63DCA52787FB6295E04FC41A /* FQueryParams.m in Sources */, + 209B69B53B2BB5A3C90A8A4B78AA795C /* FQuerySpec.m in Sources */, + 826D06D193CA64611D6D06C812D3D46D /* FRangedFilter.m in Sources */, + 58B75A9A952041F4ED689E4E407F2C06 /* FRangeMerge.m in Sources */, + D6D8C68D73E2EB24ABDA9142B60AD773 /* FRepo.m in Sources */, + C91E8F780C2E6979A0801F1B1073842D /* FRepoInfo.m in Sources */, + 0C34B37D48EF02073D940540E2422EA8 /* FRepoManager.m in Sources */, + 245636798D7598BEC4AC14A8C3F59195 /* FServerValues.m in Sources */, + D27539497AD3B159A1D756D9EE24295C /* FSnapshotHolder.m in Sources */, + 4786208953DE313FDF22E414A560099D /* FSnapshotUtilities.m in Sources */, + 6038EAE5EB6503D4F653AAF9471C5420 /* FSparseSnapshotTree.m in Sources */, + ADACD46FA2F947B04FB1B64459ABC9C6 /* FSRWebSocket.m in Sources */, + 6A6F222550CBE1E6762EB4510149335B /* FStringUtilities.m in Sources */, + 59F14E693F57E7BBD18663D234CBF833 /* FSyncPoint.m in Sources */, + 1F5C01F68004EE6E9652798667250024 /* FSyncTree.m in Sources */, + 292EA27E39216AE851ED7F5AF1F3572F /* FTrackedQuery.m in Sources */, + C4CFD31500D821D8CC4057DD4A6FCCE5 /* FTrackedQueryManager.m in Sources */, + 23BEFE2651CBC5E150DE1F05D090F45A /* FTransformedEnumerator.m in Sources */, + FDD9ADF8C9013FF0A79F04C417A3D474 /* FTree.m in Sources */, + 6AA49C7F2581024D3EFA2E1B9E9EB400 /* FTreeNode.m in Sources */, + 04C0284B8DDB1B5AC6778E52655985B5 /* FTreeSortedDictionary.m in Sources */, + 86F2C692B0DA27165AF8B605060C7A56 /* FTreeSortedDictionaryEnumerator.m in Sources */, + 37778510DDB7DD80291094F60C9C8F23 /* FTupleBoolBlock.m in Sources */, + 99654F2630D639F8BB9425F2954D1739 /* FTupleCallbackStatus.m in Sources */, + 427395F3BCF94DD6BA4C6B8BE6637FA9 /* FTupleFirebase.m in Sources */, + 92B58251896AF2A43D3388B4A7A17375 /* FTupleNodePath.m in Sources */, + 4D2A872B89ED6C1A04FA6EF3C7DA90D1 /* FTupleObjectNode.m in Sources */, + 580AF023192269BFA7E9C89BD127CA15 /* FTupleObjects.m in Sources */, + 8918C62D9BA2A846F28835E34CF13BCE /* FTupleOnDisconnect.m in Sources */, + 4AA67CFD56CDA29826E6FECC21760563 /* FTuplePathValue.m in Sources */, + FFB3372E37D70F2510BD949401462C3B /* FTupleRemovedQueriesEvents.m in Sources */, + 53A23AD6460539C93133E5936F8878D1 /* FTupleSetIdPath.m in Sources */, + 352E9C87F64C84CB7C0A6822544063AB /* FTupleStringNode.m in Sources */, + 8CC773AB211833FD012BC0D0E35F7415 /* FTupleTransaction.m in Sources */, + 2B0EB7AD0CE60D98D92D569E3FFCE97F /* FTupleTSN.m in Sources */, + 9D03AA38BAF46392D554CE759E1F90A2 /* FTupleUserCallback.m in Sources */, + 5EAE46F6A7B0831FE652C16EE6BAB775 /* FUtilities.m in Sources */, + C1891F0068E50A3CE1F4CA9773FC1106 /* FValidation.m in Sources */, + FD2D2A017203DD92A4E33539B8BBDEA6 /* FValueEventRegistration.m in Sources */, + 04D1E6C33139E1AF51B425DF61C3102E /* FValueIndex.m in Sources */, + 2845EFC8CEFA1BBBAA5A84F48525909E /* FView.m in Sources */, + A0F2AA5DDBC3926C7E50469751856B38 /* FViewCache.m in Sources */, + 36312D21067D49E3BDAAE12074705FF4 /* FViewProcessor.m in Sources */, + FF627246354B21BD8FF0684F0B9355F8 /* FViewProcessorResult.m in Sources */, + 8B4FEAEDB442AD4F795C07DC80BDCDAF /* FWebSocketConnection.m in Sources */, + 935DD97ACE2BAB32DDF07A0EAD752744 /* FWriteRecord.m in Sources */, + D90EECF6F36681386D534D5FAB0C9F10 /* FWriteTree.m in Sources */, + 9384AD4385F02852B227C892AC19E375 /* FWriteTreeRef.m in Sources */, + D7891EA68730A4A28A184B6A99571723 /* NSData+SRB64Additions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D4269F4AE4A01A17E4D0123D71A7F27A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 844D85F12F42AE3E04D67D32DCA5CFE8 /* Any.pbobjc.m in Sources */, + 2681467B53A9411E0F36DCA09C46FF84 /* Api.pbobjc.m in Sources */, + E6091E62FEF3773979C6AD65A44D6F82 /* Duration.pbobjc.m in Sources */, + 108AE1F200637096FD3EF529F95E8826 /* Empty.pbobjc.m in Sources */, + 283F5343FDCC1331A387D87617651F19 /* FieldMask.pbobjc.m in Sources */, + 9864F86F2DB43C52AC4459180299AD40 /* GPBArray.m in Sources */, + DC7AA6521AA6E9CC4AA32E2114E65896 /* GPBCodedInputStream.m in Sources */, + 22419CF604E5F4E71B191A573477E765 /* GPBCodedOutputStream.m in Sources */, + BDBE450803852671A91A066EE21DF6D0 /* GPBDescriptor.m in Sources */, + 84724F50CD690FBE29DC07D60DA57CE3 /* GPBDictionary.m in Sources */, + 323478A277D2734E5E5A1AC46E3EDD10 /* GPBExtensionInternals.m in Sources */, + 85B5BFB63EB47EED1A89513B6D16B77D /* GPBExtensionRegistry.m in Sources */, + B21554D5A36CBBD9B6CC65BF5A87DED0 /* GPBMessage.m in Sources */, + A15C9B6672D8D0F2E252C09899E096FB /* GPBRootObject.m in Sources */, + 27D03B988D6269D5BB0099E89EB85EFB /* GPBUnknownField.m in Sources */, + 15D82D0D27D718FEDA039C5A056BA0A7 /* GPBUnknownFieldSet.m in Sources */, + 0EBFA9CC46A6D7AE5E8789A4A46D3464 /* GPBUtilities.m in Sources */, + 20E6EA2D2351FC5C0694846164D50BDB /* GPBWellKnownTypes.m in Sources */, + D57E07440AC52FDA7F5AF53332978343 /* GPBWireFormat.m in Sources */, + C356F7ED55C844AEA0454B1C20F115F8 /* Protobuf-dummy.m in Sources */, + 1827E4B261CF18BAD9BAB4A23F31E33A /* SourceContext.pbobjc.m in Sources */, + 4D1A1A40FD9B72988A1FF9AD957F6B29 /* Struct.pbobjc.m in Sources */, + 18F2A93904BE47E327F6772BC92391EE /* Timestamp.pbobjc.m in Sources */, + 4D0F373D0B5CBD860671BF9E9A2AC8B5 /* Type.pbobjc.m in Sources */, + E241F0D140E0679637775F22FF7DD50A /* Wrappers.pbobjc.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D58FC9A6E4BBCA83BF88118CB1332325 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 591C8DF910D247F9E9229069DC861077 /* FIRActionCodeSettings.m in Sources */, + CC1D74CF5040C22FCAE1EF11D747F41E /* FIRAdditionalUserInfo.m in Sources */, + ABA504F9416B705404F4395F56FD924E /* FIRAuth.m in Sources */, + 4A5C18EEA9A51189379141AFDE4C24D0 /* FIRAuthAPNSToken.m in Sources */, + B010D7EA72F68E5C8800E592430EB6D6 /* FIRAuthAPNSTokenManager.m in Sources */, + 2F1272ED0F06E548CF4C7B00A695B4D1 /* FIRAuthAppCredential.m in Sources */, + BA9174F13BB2ED25C493244D3B03611C /* FIRAuthAppCredentialManager.m in Sources */, + F9C4D8D0356D72D09040AFB2EAC8D34F /* FIRAuthAppDelegateProxy.m in Sources */, + 48C766964B4CE36CD80FF8D7220D1B8A /* FIRAuthBackend.m in Sources */, + 181D017519ED05CC259043741928943C /* FIRAuthCredential.m in Sources */, + 521F7FDEAB38511C5575D288BB7CC0B1 /* FIRAuthDataResult.m in Sources */, + 391CCF70D8CC77B7086E64C34809FFCE /* FIRAuthDefaultUIDelegate.m in Sources */, + A131243C5128195EE4686EBA911EC770 /* FIRAuthDispatcher.m in Sources */, + 8141044D91C61B567A792FA1E8938B11 /* FIRAuthErrorUtils.m in Sources */, + 2DE5C6BFD8C35D3343A840DFC3CD718B /* FIRAuthExceptionUtils.m in Sources */, + 96DED265BD66E66313D96701C5BE76DA /* FIRAuthGlobalWorkQueue.m in Sources */, + 74EE0DFE076866675923FA31C5EEFDA7 /* FIRAuthKeychain.m in Sources */, + 0124EE669FBEDC523BD6DDE9ED8F2122 /* FIRAuthNotificationManager.m in Sources */, + D552F099EE8DD72F421E7285F72EB7D3 /* FIRAuthProvider.m in Sources */, + 8C3B89BC8A2DA18385A402DB2664EE76 /* FIRAuthRequestConfiguration.m in Sources */, + 3C7F3BFB04BFF90E6FCCCC736BA094EC /* FIRAuthSerialTaskQueue.m in Sources */, + 7833221C662C83CE83BEC6024C116D10 /* FIRAuthSettings.m in Sources */, + BD773A6159443E6B37BE7F5BAA306EC5 /* FIRAuthTokenResult.m in Sources */, + 1BDAB2FEFFFF8CE4DAA690ED3293D1E9 /* FIRAuthURLPresenter.m in Sources */, + D069528278DA1D52E3EBE5F869D0C486 /* FIRAuthUserDefaultsStorage.m in Sources */, + E7732A95963EEA06D112EC28CE34B1ED /* FIRAuthWebUtils.m in Sources */, + 286EF599E7C3659EE0EB0929BAF9C43F /* FIRAuthWebView.m in Sources */, + 79E6F10B00F9218719B94CE73F6EFD74 /* FIRAuthWebViewController.m in Sources */, + 7B9F461598C44240C924C220394DBA29 /* FIRCreateAuthURIRequest.m in Sources */, + 1493703C0821CA137EA4FF9D4610B992 /* FIRCreateAuthURIResponse.m in Sources */, + 4E358E0171A6DB00E2E78F86BE035BD1 /* FIRDeleteAccountRequest.m in Sources */, + 6FCC648764C27AFDB436D809C75FA066 /* FIRDeleteAccountResponse.m in Sources */, + 5851C12C82D4C280F06DD5FBD8BB6FCA /* FirebaseAuth-dummy.m in Sources */, + 820E8B73383B6DF22E7D1CA538025161 /* FirebaseAuthVersion.m in Sources */, + BD60DDDA106B830D0D232D3348316B40 /* FIREmailAuthProvider.m in Sources */, + E0EFDB770FB7300A3E9F9F90EC4D84A8 /* FIREmailLinkSignInRequest.m in Sources */, + 5C349011CBE212534C3F6F0F99FBC78D /* FIREmailLinkSignInResponse.m in Sources */, + 84913A4683DA41F54915D2F08B4F366C /* FIREmailPasswordAuthCredential.m in Sources */, + 9FD03A6F2B880A75B4CD25D166571D98 /* FIRFacebookAuthCredential.m in Sources */, + E2A71207B5A59E4FA86C0457AE5B43E0 /* FIRFacebookAuthProvider.m in Sources */, + 6B804651E0974E119607E4AE34A941FC /* FIRGameCenterAuthCredential.m in Sources */, + 691FCECA0451BF9E483BE682A51F7509 /* FIRGameCenterAuthProvider.m in Sources */, + F8D3BA67EDCBDE29232A5ED3A6D500B6 /* FIRGetAccountInfoRequest.m in Sources */, + B88F11FC4243CEB0EE2B1416FEE6706A /* FIRGetAccountInfoResponse.m in Sources */, + 20D2F5063CB675E0C06A42363149F916 /* FIRGetOOBConfirmationCodeRequest.m in Sources */, + 86AE3929EB07E9757E3B6A750C0E51DD /* FIRGetOOBConfirmationCodeResponse.m in Sources */, + 6CE03A50870B92C6F8992DAF20A34B99 /* FIRGetProjectConfigRequest.m in Sources */, + 432117374790242BA5EDD0991F56DA2E /* FIRGetProjectConfigResponse.m in Sources */, + 221F3C7C12FC8F748753545E4962BE80 /* FIRGitHubAuthCredential.m in Sources */, + B39394809F93B95B0CE1A2827815FCD1 /* FIRGitHubAuthProvider.m in Sources */, + 584755500362FD0430BE76FB456C7FE5 /* FIRGoogleAuthCredential.m in Sources */, + E94FECF2AD90CCAA6A4E00868582FD37 /* FIRGoogleAuthProvider.m in Sources */, + 685770FAAC666DDED9C233D77A7207EB /* FIRIdentityToolkitRequest.m in Sources */, + DCCDE080BF1C3B4EF73A04E20D49E718 /* FIROAuthCredential.m in Sources */, + F7EB151471656A6A938C14F8D6E2A1C7 /* FIROAuthProvider.m in Sources */, + 4FB6987074A7C231A430E1A9DC1F0073 /* FIRPhoneAuthCredential.m in Sources */, + 1E1F2D849C58DEE61BEC26F3E5D18428 /* FIRPhoneAuthProvider.m in Sources */, + 8FB1FF9F99D0CB549EEFF34119B70067 /* FIRResetPasswordRequest.m in Sources */, + EE2B235989A82885B60FC78F9F360676 /* FIRResetPasswordResponse.m in Sources */, + 2E9C9C5138F8FC9593825B2FE0B115D4 /* FIRSecureTokenRequest.m in Sources */, + 951697EDC6A3E9876F3EDA4678EB737B /* FIRSecureTokenResponse.m in Sources */, + B15FC1F8F8DC423C1D1B589E60F544F1 /* FIRSecureTokenService.m in Sources */, + FB904116F1994ED9ECE269B4BE319C27 /* FIRSendVerificationCodeRequest.m in Sources */, + B6E33D8A116746907694A0611DF86F3C /* FIRSendVerificationCodeResponse.m in Sources */, + 92CBC09B402DA90BDF70F383755086EC /* FIRSetAccountInfoRequest.m in Sources */, + A85D8986FAC7FA0189C8B305AFF68BE9 /* FIRSetAccountInfoResponse.m in Sources */, + 73A4176EE589467648540DEBF49464A5 /* FIRSignInWithGameCenterRequest.m in Sources */, + 7469BBC99ABDE48CB24BD5CB637FCC27 /* FIRSignInWithGameCenterResponse.m in Sources */, + 3F57A292C689577986C789440912ABB4 /* FIRSignUpNewUserRequest.m in Sources */, + FB399B131887623311B039D2B888BA2E /* FIRSignUpNewUserResponse.m in Sources */, + 3B4D5805A6152892B36CFEC08FF30F82 /* FIRTwitterAuthCredential.m in Sources */, + FF37D53055EF084C1F52B2D829EBB720 /* FIRTwitterAuthProvider.m in Sources */, + D402A12D3ED43E23EFC437DDEE012F6D /* FIRUser.m in Sources */, + 900C205CED5C47387337EDEA70EBA6CF /* FIRUserInfoImpl.m in Sources */, + 9378AA360EB8BF7A318BF4D3DD1FD98A /* FIRUserMetadata.m in Sources */, + F9280ED8A50744EBDC19248A06B631BE /* FIRVerifyAssertionRequest.m in Sources */, + E519B657A4BE06FFB6AC67AC43275A8C /* FIRVerifyAssertionResponse.m in Sources */, + 6E81A7EC383CC06F435C7955BF35D8D7 /* FIRVerifyClientRequest.m in Sources */, + 13B7E538A0B31929B6940CC11AF2D3DD /* FIRVerifyClientResponse.m in Sources */, + 2830CF875793D7780A11081310937635 /* FIRVerifyCustomTokenRequest.m in Sources */, + 1A8227B02B0D98E83CECC24E8373F9B5 /* FIRVerifyCustomTokenResponse.m in Sources */, + F8E193666E5BFB1DE7DF4879D1B1E092 /* FIRVerifyPasswordRequest.m in Sources */, + C0CA1713C205A48A4C2899559F1E7322 /* FIRVerifyPasswordResponse.m in Sources */, + 5659D031556A9E3AB0B6362CEEAAFEB3 /* FIRVerifyPhoneNumberRequest.m in Sources */, + A1EA5EFB715B6F66031D21C96A5235E6 /* FIRVerifyPhoneNumberResponse.m in Sources */, + 56EF0203603BA1650103D79F0D2FC7E3 /* NSData+FIRBase64.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D9E95E66FF76FB26D79C608230A20C24 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D8FC1484177D763EA88D86B00BDB808F /* Pods-My Mind-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F5EAE135ABECBFA7F3037A131EE462A3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 515BED0BC89E9B645BB0729F1A47E689 /* FirebaseMessaging-dummy.m in Sources */, + CD3B6B02BA77A60B2D345BFDF78DF43E /* FIRMessaging.m in Sources */, + 25E17FDF9EC685B33382856C071EFB2B /* FIRMessagingAnalytics.m in Sources */, + AE067235520EF8E2FA01D07CCE0B123F /* FIRMessagingCheckinService.m in Sources */, + CDA69EC5212E7212B91D944E86567F53 /* FIRMessagingClient.m in Sources */, + DC4AB5B5940C35B49EB39971AB70704A /* FIRMessagingCodedInputStream.m in Sources */, + 131D1E3ED0BA8A75817D5A9D7A5BD9E4 /* FIRMessagingConnection.m in Sources */, + E6107CF6B58A77B36C037AED8052064C /* FIRMessagingConstants.m in Sources */, + C90D9A2FF2967943932118B78E7A9CCC /* FIRMessagingContextManagerService.m in Sources */, + 95CB107FD47710D82AADCF796739E487 /* FIRMessagingDataMessageManager.m in Sources */, + 2B8C51B8B260D2DF686041D4A040B8B6 /* FIRMessagingDelayedMessageQueue.m in Sources */, + C9533158E00437EDEA876FC9E8D84752 /* FIRMessagingLogger.m in Sources */, + F82397B7C59337533C88DDD77F92ACD7 /* FIRMessagingPacketQueue.m in Sources */, + EE512B0AE1A87FDDB404BACD12065820 /* FIRMessagingPendingTopicsList.m in Sources */, + 9CA9D429B06966E8603F3FDBAB52E773 /* FIRMessagingPersistentSyncMessage.m in Sources */, + 3E8BE1FD810218E8619F39BF30938D66 /* FIRMessagingPubSub.m in Sources */, + 507DF3AE9C550952EEFA4145A520D8FC /* FIRMessagingPubSubRegistrar.m in Sources */, + E5900F8440944CEC31ED3763D5DB95B9 /* FIRMessagingReceiver.m in Sources */, + 0D87C3509B6F6D2FE145F8D87165F4F2 /* FIRMessagingRegistrar.m in Sources */, + E8226DBEF9EB493C1BC1A6B06F2A195A /* FIRMessagingRemoteNotificationsProxy.m in Sources */, + 8979C58492296D7F06A1AEAEFC8F399A /* FIRMessagingRmq2PersistentStore.m in Sources */, + E2B864CF5FCD00BBDB5A6B615BF2D2ED /* FIRMessagingRmqManager.m in Sources */, + B32809CB22D971969762CAE8E96DF24E /* FIRMessagingSecureSocket.m in Sources */, + 0CD1DDB7D4CBEEEB3A9ED1782F27822A /* FIRMessagingSyncMessageManager.m in Sources */, + 4B2D0C0BF003527375687E0912D8BA98 /* FIRMessagingTopicOperation.m in Sources */, + B212A3AF5AE14BC07F01E56C6081367E /* FIRMessagingUtilities.m in Sources */, + 88B698FD87FCF4DA1BAF4ABC7AC85FFA /* FIRMessagingVersionUtilities.m in Sources */, + 748BF578B84FBBA94B37372C12873CA1 /* GtalkCore.pbobjc.m in Sources */, + 5FA7C8E2A1BCBB52B3E108EE54E362D4 /* GtalkExtensions.pbobjc.m in Sources */, + B877236992FA436C2E0BD5B6D1FE24C2 /* NSDictionary+FIRMessaging.m in Sources */, + 7C085F2F10CD608EA786560E45EE24C1 /* NSError+FIRMessaging.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0B2617E2A7F0C5BE2543532EECF94DB9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "leveldb-library"; + target = FE47F11E708D633621DB136BD3CD0034 /* leveldb-library */; + targetProxy = F0E1BA2C273B26FEEDCD79E9EAF8F955 /* PBXContainerItemProxy */; + }; + 1AECE3B54B15BF525F138226524AD755 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMSessionFetcher; + target = 1D9FB04B52C841F3FC0250CBC62A374F /* GTMSessionFetcher */; + targetProxy = B80AEEE4D10B31DDDEBDF136764269D7 /* PBXContainerItemProxy */; + }; + 1EFDE9DFEF9103FCD9FD939C5D26838F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-My Mind"; + target = CFE9294A3948C71B6B365E1AE070CDA5 /* Pods-My Mind */; + targetProxy = 509F57F7F365E2F9DE456FADFE3F6603 /* PBXContainerItemProxy */; + }; + 4127704CC0ED1A600673DBBB09B2ABC5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMSessionFetcher; + target = 1D9FB04B52C841F3FC0250CBC62A374F /* GTMSessionFetcher */; + targetProxy = F128F2484F841C12F5C1EC4068D756FC /* PBXContainerItemProxy */; + }; + 430336A65140D8EE34E616534122C702 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = B218F71BCB3FC159BEA6E328B5A8E5F6 /* PBXContainerItemProxy */; + }; + 4550D193C6A5942BAC22632DD446BD55 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseStorage; + target = 263F7002FD4F2FB368F105A900F31A18 /* FirebaseStorage */; + targetProxy = 4606C2E5A0E2A00E10E8CD332CFEFD29 /* PBXContainerItemProxy */; + }; + 4CE1EA8EA3E9AE16AFD64E6B41A715F0 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseCore; + target = 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */; + targetProxy = 8558F8BE6C58B2E54D57B5EA7350BDE7 /* PBXContainerItemProxy */; + }; + 51D9E709DC9B2BEA7F6F56D14161EC7E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseAuth; + target = 079E4F97855B7901F483AA030B2B7C5C /* FirebaseAuth */; + targetProxy = D8812642019028E623ACE66D311D3E26 /* PBXContainerItemProxy */; + }; + 647C630C1C5AC7E5D27EC72B3B68617B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = 506EFD2624A592FE9D141F58142722C0 /* PBXContainerItemProxy */; + }; + 66B98059846202D9D21951DFB44D3ADD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseCore; + target = 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */; + targetProxy = 32DE737A738CB51799F86D98E6F4B5F7 /* PBXContainerItemProxy */; + }; + 7023D1567CED3A6565F1C371BC795C12 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = 1D1A6C516B8735CFABACA3F9AFBFD852 /* PBXContainerItemProxy */; + }; + 837D1036EB37E1FD7CE11AEEFE789A07 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = 435CC24916E3408C00C8E0452BE92378 /* PBXContainerItemProxy */; + }; + 871AB9E9665D6EF6C869BEE3D1B36E66 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseCore; + target = 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */; + targetProxy = 07DB35DD87B60D92B772971B805E3593 /* PBXContainerItemProxy */; + }; + 905C20FDA684048F8B39FD0449C6158D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = C8A47A2E4639CEF70BF7AB3DE0E4BC06 /* PBXContainerItemProxy */; + }; + ACFF71D3652B637314D4B716E2A0146F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Protobuf; + target = 93AB79BD5DB2C6B4F890C0F391AE1FBC /* Protobuf */; + targetProxy = 69E3D4B82ADB9777ECE78BE0A63D70E6 /* PBXContainerItemProxy */; + }; + ADE25216AABFBB6F0BB28A0C34A44BC2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Protobuf; + target = 93AB79BD5DB2C6B4F890C0F391AE1FBC /* Protobuf */; + targetProxy = FD55D6B51C431D8A664C1312CBA9344D /* PBXContainerItemProxy */; + }; + B3CF748C58ED214D1830FFABE0C7B911 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseDatabase; + target = B9B45D12C08E85F7863BC9EB04B3A850 /* FirebaseDatabase */; + targetProxy = D21F2F60CC3475DD221E35CF29CA182D /* PBXContainerItemProxy */; + }; + B697592FD3A1CF6A07F0F8DABF4DC74E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GoogleUtilities; + target = 8630D8884A33BA1097586BCBB1114CA7 /* GoogleUtilities */; + targetProxy = A20E62201BBF39DA8ABBE0A91DE28F7C /* PBXContainerItemProxy */; + }; + BD7B3AFBBF75058104A9AC2095407131 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = nanopb; + target = 8364BB258018143B83798DE31C13546D /* nanopb */; + targetProxy = C642C6142D782A0453520E3BFE7D5D1F /* PBXContainerItemProxy */; + }; + CA6F8130F959B3A83104E6BEE0135093 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMSessionFetcher; + target = 1D9FB04B52C841F3FC0250CBC62A374F /* GTMSessionFetcher */; + targetProxy = 48B79CA3E37AA085E6280AF28B6908B8 /* PBXContainerItemProxy */; + }; + D0579349E04C228BAA8781C0DD90DC82 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-My Mind"; + target = CFE9294A3948C71B6B365E1AE070CDA5 /* Pods-My Mind */; + targetProxy = 7DA088ECDD2B33776686F56A593667FD /* PBXContainerItemProxy */; + }; + D17F192BFDAF5950EDDE420D885C8599 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseCore; + target = 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */; + targetProxy = 0254BA8A0A5A6E25F93FA0481D336BE4 /* PBXContainerItemProxy */; + }; + E3D1B24BC63633CB96F20F27D0499E8D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftForms; + target = B01DE4F80FFD6ECD3AC72050910AF61D /* SwiftForms */; + targetProxy = 849B13920E45C874D68FC5643BE7CA2F /* PBXContainerItemProxy */; + }; + F2A7D8DA002A61EF46E91D3891B43841 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseMessaging; + target = F7293FA58AFAF74ECAAB1C4796C45F5B /* FirebaseMessaging */; + targetProxy = FF85B2D26CDE57EBE7AA71DC4E38EEB3 /* PBXContainerItemProxy */; + }; + F39EE1E73FC9AE481222451099AF18F7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FirebaseCore; + target = 0514F4F103BE5B9B50E766A321993C20 /* FirebaseCore */; + targetProxy = 46800726BF8809483EB1EFF7DB5948EA /* PBXContainerItemProxy */; + }; + FC8B52D7ABE4D1C5342D0619AF8DEE80 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "leveldb-library"; + target = FE47F11E708D633621DB136BD3CD0034 /* leveldb-library */; + targetProxy = 85D8DF7EB572D40C2680BF9930748E9A /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 0AA3B91655AF95B1F49159CD8085CD89 /* 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; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + 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 = 12.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 = 4.2; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 0C99AAFC17C4480B504D23E1331B99B5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 45A06472A76E939B327F33F87CB8F5AA /* SwiftForms.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/SwiftForms/SwiftForms-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftForms/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/SwiftForms/SwiftForms.modulemap"; + PRODUCT_MODULE_NAME = SwiftForms; + PRODUCT_NAME = SwiftForms; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 1D785F4D8BAE1422236E85CA187C714A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 50D59C3FF3C181DB023918A1E27B460A /* Pods-My MindUITests.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-My MindUITests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My MindUITests/Pods-My MindUITests.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; + }; + 2A52C31D49B59703F03072E88CE89446 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 14C8ECD8310E798246C725B33683BD31 /* Pods-My MindTests.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-My MindTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My MindTests/Pods-My MindTests.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; + }; + 3324A10FAA1DF836B002C8B1DB0B6380 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B9C0F3D003CEE3E5CBD1B6E5C94D1702 /* FirebaseMessaging.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseMessaging/FirebaseMessaging.modulemap"; + PRODUCT_MODULE_NAME = FirebaseMessaging; + PRODUCT_NAME = FirebaseMessaging; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3E54C925E38597ED245235E86E26193E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F6680C23E17FDEF739AE9C28CE584837 /* nanopb.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/nanopb/nanopb-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/nanopb/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/nanopb/nanopb.modulemap"; + PRODUCT_MODULE_NAME = nanopb; + PRODUCT_NAME = nanopb; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 457C9468889932073281926F7EEC5976 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 441DBA22AFAC3463555CEA3C57697304 /* Pods-My Mind.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-My Mind/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My Mind/Pods-My Mind.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; + }; + 59303CF720F3C6C6EA930B48C27A1F0E /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B042774A378BD6A6A47CAF43D174D354 /* FirebaseCore.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseCore/FirebaseCore.modulemap"; + PRODUCT_MODULE_NAME = FirebaseCore; + PRODUCT_NAME = FirebaseCore; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 655A6AF7563649C5C8E66850D557A8E0 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EAFA346294A42DC00BC37D078709B709 /* Pods-My Mind.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-My Mind/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My Mind/Pods-My Mind.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; + }; + 66355A5C40F30E214391FC47B6096CC0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D32F70B25D7F29D35CFA300BD1BAAE9E /* Protobuf.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/Protobuf/Protobuf-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Protobuf/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/Protobuf/Protobuf.modulemap"; + PRODUCT_MODULE_NAME = Protobuf; + PRODUCT_NAME = Protobuf; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6C037E8DF262511366EC3625F6E9861F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EF9B0B817B564DEA1E062086A289548D /* FirebaseAuth.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseAuth/FirebaseAuth.modulemap"; + PRODUCT_MODULE_NAME = FirebaseAuth; + PRODUCT_NAME = FirebaseAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6ED2524E110A98DC1E25AFC00509D12A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EF9B0B817B564DEA1E062086A289548D /* FirebaseAuth.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseAuth/FirebaseAuth.modulemap"; + PRODUCT_MODULE_NAME = FirebaseAuth; + PRODUCT_NAME = FirebaseAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7F1894137D99E498A4B9781F09144EF3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1F8914247BC8981046DD3254E6EED8BF /* GTMSessionFetcher.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/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/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/GTMSessionFetcher/GTMSessionFetcher.modulemap"; + PRODUCT_MODULE_NAME = GTMSessionFetcher; + PRODUCT_NAME = GTMSessionFetcher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8000995DA02063BF3777393CD52061DD /* 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; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + 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 = 12.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 = 4.2; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + 8A449B151337A3303B048723E4DC975C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D32F70B25D7F29D35CFA300BD1BAAE9E /* Protobuf.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/Protobuf/Protobuf-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Protobuf/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/Protobuf/Protobuf.modulemap"; + PRODUCT_MODULE_NAME = Protobuf; + PRODUCT_NAME = Protobuf; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9109FED563FAF56C4EBD1C07855E6CA0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1E8627B6D324325882201B629A767ED8 /* GoogleUtilities.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/GoogleUtilities/GoogleUtilities-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GoogleUtilities/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/GoogleUtilities/GoogleUtilities.modulemap"; + PRODUCT_MODULE_NAME = GoogleUtilities; + PRODUCT_NAME = GoogleUtilities; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 98D61CFA7B04588BCFC6566EEEF90FD8 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F6680C23E17FDEF739AE9C28CE584837 /* nanopb.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/nanopb/nanopb-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/nanopb/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/nanopb/nanopb.modulemap"; + PRODUCT_MODULE_NAME = nanopb; + PRODUCT_NAME = nanopb; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9B5764CC950D1CE5E950F2A37A530E45 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 532A60C333164404D23A05ACB55C6E71 /* leveldb-library.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/leveldb-library/leveldb-library-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/leveldb-library/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/leveldb-library/leveldb-library.modulemap"; + PRODUCT_MODULE_NAME = leveldb; + PRODUCT_NAME = leveldb; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + A163499350D2D1F183B386D2FFEA3716 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1E8627B6D324325882201B629A767ED8 /* GoogleUtilities.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/GoogleUtilities/GoogleUtilities-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GoogleUtilities/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/GoogleUtilities/GoogleUtilities.modulemap"; + PRODUCT_MODULE_NAME = GoogleUtilities; + PRODUCT_NAME = GoogleUtilities; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AF42C735A0504D11ACF8157298358A84 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1FB8225F6A8837C1B29AA8D1503478F1 /* FirebaseStorage.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseStorage/FirebaseStorage.modulemap"; + PRODUCT_MODULE_NAME = FirebaseStorage; + PRODUCT_NAME = FirebaseStorage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BCD603B3ED2EB4B49E0C88CDF53A1D7D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B042774A378BD6A6A47CAF43D174D354 /* FirebaseCore.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseCore/FirebaseCore.modulemap"; + PRODUCT_MODULE_NAME = FirebaseCore; + PRODUCT_NAME = FirebaseCore; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D132C1192B6B32A889548140E8596356 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AC29AD359CB65A16BC601242EC2BC78F /* Pods-My MindTests.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-My MindTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My MindTests/Pods-My MindTests.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; + }; + DC733B2C732786A7EE2692027FD1F265 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 532A60C333164404D23A05ACB55C6E71 /* leveldb-library.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/leveldb-library/leveldb-library-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/leveldb-library/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/leveldb-library/leveldb-library.modulemap"; + PRODUCT_MODULE_NAME = leveldb; + PRODUCT_NAME = leveldb; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + E5699E5C75AFB19102220E0E16307DD7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F8482E2E1DB4B525FF0826BAE0A61D59 /* Pods-My MindUITests.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-My MindUITests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-My MindUITests/Pods-My MindUITests.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; + }; + ED830FC38B7FE7D6E4CD23E1DC92D1F2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B9C0F3D003CEE3E5CBD1B6E5C94D1702 /* FirebaseMessaging.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseMessaging/FirebaseMessaging.modulemap"; + PRODUCT_MODULE_NAME = FirebaseMessaging; + PRODUCT_NAME = FirebaseMessaging; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + EDE1B8A8A09D1683938C02EF5C0F5D58 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1F8914247BC8981046DD3254E6EED8BF /* GTMSessionFetcher.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/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/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/GTMSessionFetcher/GTMSessionFetcher.modulemap"; + PRODUCT_MODULE_NAME = GTMSessionFetcher; + PRODUCT_NAME = GTMSessionFetcher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + EFEE3C23D62444F78E6EC0B877BA3996 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D1D80F314DC9DFCAF4DF1930A7FF0432 /* FirebaseDatabase.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseDatabase/FirebaseDatabase.modulemap"; + PRODUCT_MODULE_NAME = FirebaseDatabase; + PRODUCT_NAME = FirebaseDatabase; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F52CA57C507354816B69C67BF58AF87C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1FB8225F6A8837C1B29AA8D1503478F1 /* FirebaseStorage.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseStorage/FirebaseStorage.modulemap"; + PRODUCT_MODULE_NAME = FirebaseStorage; + PRODUCT_NAME = FirebaseStorage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F5F3F00D5FF8AE1128490460EC04EC6E /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 45A06472A76E939B327F33F87CB8F5AA /* SwiftForms.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/SwiftForms/SwiftForms-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftForms/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/SwiftForms/SwiftForms.modulemap"; + PRODUCT_MODULE_NAME = SwiftForms; + PRODUCT_NAME = SwiftForms; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FD4DCAF80CC5DCCA97BB0F13C4DFF87E /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D1D80F314DC9DFCAF4DF1930A7FF0432 /* FirebaseDatabase.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"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + 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/FirebaseDatabase/FirebaseDatabase.modulemap"; + PRODUCT_MODULE_NAME = FirebaseDatabase; + PRODUCT_NAME = FirebaseDatabase; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 08BEB47E01CCCC54133E9FD5806B7A24 /* Build configuration list for PBXNativeTarget "FirebaseCore" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 59303CF720F3C6C6EA930B48C27A1F0E /* Debug */, + BCD603B3ED2EB4B49E0C88CDF53A1D7D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0AA3B91655AF95B1F49159CD8085CD89 /* Debug */, + 8000995DA02063BF3777393CD52061DD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 36174492661C12BE4B7835554F9731EA /* Build configuration list for PBXNativeTarget "leveldb-library" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9B5764CC950D1CE5E950F2A37A530E45 /* Debug */, + DC733B2C732786A7EE2692027FD1F265 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4D9DDDAED363D608DA18A16151BCB212 /* Build configuration list for PBXNativeTarget "SwiftForms" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F5F3F00D5FF8AE1128490460EC04EC6E /* Debug */, + 0C99AAFC17C4480B504D23E1331B99B5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 50E9A67E65D93CA129312A07FA3346B5 /* Build configuration list for PBXNativeTarget "Protobuf" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 66355A5C40F30E214391FC47B6096CC0 /* Debug */, + 8A449B151337A3303B048723E4DC975C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 557DBB73FFE1746960D722CA99CD0144 /* Build configuration list for PBXNativeTarget "GoogleUtilities" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9109FED563FAF56C4EBD1C07855E6CA0 /* Debug */, + A163499350D2D1F183B386D2FFEA3716 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 710E05D74490C1F833687AF1F4D76EBD /* Build configuration list for PBXNativeTarget "FirebaseMessaging" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + ED830FC38B7FE7D6E4CD23E1DC92D1F2 /* Debug */, + 3324A10FAA1DF836B002C8B1DB0B6380 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8DFE20DD733100533E2F990F4FCD4267 /* Build configuration list for PBXNativeTarget "Pods-My Mind" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 457C9468889932073281926F7EEC5976 /* Debug */, + 655A6AF7563649C5C8E66850D557A8E0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8F61149C31EE7C6C9D64D111695E794B /* Build configuration list for PBXNativeTarget "FirebaseAuth" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6C037E8DF262511366EC3625F6E9861F /* Debug */, + 6ED2524E110A98DC1E25AFC00509D12A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 92C2657A497FE026F77D23DB42524144 /* Build configuration list for PBXNativeTarget "FirebaseDatabase" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FD4DCAF80CC5DCCA97BB0F13C4DFF87E /* Debug */, + EFEE3C23D62444F78E6EC0B877BA3996 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9ABF9020C478812FA9F1FF75678AA4F4 /* Build configuration list for PBXNativeTarget "Pods-My MindUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E5699E5C75AFB19102220E0E16307DD7 /* Debug */, + 1D785F4D8BAE1422236E85CA187C714A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A54B95AC2E23BB0947B35EFE5E1F0EFB /* Build configuration list for PBXNativeTarget "nanopb" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 98D61CFA7B04588BCFC6566EEEF90FD8 /* Debug */, + 3E54C925E38597ED245235E86E26193E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B593C18D2023F49F69D7184CC2DC4396 /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7F1894137D99E498A4B9781F09144EF3 /* Debug */, + EDE1B8A8A09D1683938C02EF5C0F5D58 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B936FBFBA98BB09A0992AC486F0255C8 /* Build configuration list for PBXNativeTarget "FirebaseStorage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F52CA57C507354816B69C67BF58AF87C /* Debug */, + AF42C735A0504D11ACF8157298358A84 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D74A910542F89F47C850C6BFE968F24F /* Build configuration list for PBXNativeTarget "Pods-My MindTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D132C1192B6B32A889548140E8596356 /* Debug */, + 2A52C31D49B59703F03072E88CE89446 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseAuth.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseAuth.xcscheme new file mode 100644 index 0000000..16c18a3 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseAuth.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseCore.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseCore.xcscheme new file mode 100644 index 0000000..6d044db --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseCore.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseDatabase.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseDatabase.xcscheme new file mode 100644 index 0000000..d44c0d4 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseDatabase.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseMessaging.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseMessaging.xcscheme new file mode 100644 index 0000000..7b32f15 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseMessaging.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseStorage.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseStorage.xcscheme new file mode 100644 index 0000000..f6defba --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/FirebaseStorage.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme new file mode 100644 index 0000000..d36a2c5 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GoogleUtilities.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GoogleUtilities.xcscheme new file mode 100644 index 0000000..ce9b151 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/GoogleUtilities.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My Mind.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My Mind.xcscheme new file mode 100644 index 0000000..9faaec4 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My Mind.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindTests.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindTests.xcscheme new file mode 100644 index 0000000..5b078e6 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindTests.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindUITests.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindUITests.xcscheme new file mode 100644 index 0000000..332df00 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Pods-My MindUITests.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Protobuf.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Protobuf.xcscheme new file mode 100644 index 0000000..6a2f325 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/Protobuf.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/SwiftForms.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/SwiftForms.xcscheme new file mode 100644 index 0000000..9ea58e6 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/SwiftForms.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/leveldb-library.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/leveldb-library.xcscheme new file mode 100644 index 0000000..b4894f7 --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/leveldb-library.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/nanopb.xcscheme b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/nanopb.xcscheme new file mode 100644 index 0000000..bcdd16f --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/nanopb.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..acce09e --- /dev/null +++ b/My Mind/Pods/Pods.xcodeproj/xcuserdata/alexanderdavis.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,109 @@ + + + + + SchemeUserState + + FirebaseAuth.xcscheme + + isShown + + orderHint + 0 + + FirebaseCore.xcscheme + + isShown + + orderHint + 1 + + FirebaseDatabase.xcscheme + + isShown + + orderHint + 2 + + FirebaseMessaging.xcscheme + + isShown + + orderHint + 3 + + FirebaseStorage.xcscheme + + isShown + + orderHint + 4 + + GTMSessionFetcher.xcscheme + + isShown + + orderHint + 6 + + GoogleUtilities.xcscheme + + isShown + + orderHint + 5 + + Pods-My Mind.xcscheme + + isShown + + orderHint + 9 + + Pods-My MindTests.xcscheme + + isShown + + orderHint + 10 + + Pods-My MindUITests.xcscheme + + isShown + + orderHint + 11 + + Protobuf.xcscheme + + isShown + + orderHint + 12 + + SwiftForms.xcscheme + + isShown + + orderHint + 13 + + leveldb-library.xcscheme + + isShown + + orderHint + 7 + + nanopb.xcscheme + + isShown + + orderHint + 8 + + + SuppressBuildableAutocreation + + + diff --git a/My Mind/Pods/Protobuf/LICENSE b/My Mind/Pods/Protobuf/LICENSE new file mode 100644 index 0000000..19b305b --- /dev/null +++ b/My Mind/Pods/Protobuf/LICENSE @@ -0,0 +1,32 @@ +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/My Mind/Pods/Protobuf/README.md b/My Mind/Pods/Protobuf/README.md new file mode 100644 index 0000000..1a45ee6 --- /dev/null +++ b/My Mind/Pods/Protobuf/README.md @@ -0,0 +1,85 @@ +Protocol Buffers - Google's data interchange format +=================================================== + +Copyright 2008 Google Inc. + +https://developers.google.com/protocol-buffers/ + +Overview +-------- + +Protocol Buffers (a.k.a., protobuf) are Google's language-neutral, +platform-neutral, extensible mechanism for serializing structured data. You +can find [protobuf's documentation on the Google Developers site](https://developers.google.com/protocol-buffers/). + +This README file contains protobuf installation instructions. To install +protobuf, you need to install the protocol compiler (used to compile .proto +files) and the protobuf runtime for your chosen programming language. + +Protocol Compiler Installation +------------------------------ + +The protocol compiler is written in C++. If you are using C++, please follow +the [C++ Installation Instructions](src/README.md) to install protoc along +with the C++ runtime. + +For non-C++ users, the simplest way to install the protocol compiler is to +download a pre-built binary from our release page: + + [https://github.com/google/protobuf/releases](https://github.com/google/protobuf/releases) + +In the downloads section of each release, you can find pre-built binaries in +zip packages: protoc-$VERSION-$PLATFORM.zip. It contains the protoc binary +as well as a set of standard .proto files distributed along with protobuf. + +If you are looking for an old version that is not available in the release +page, check out the maven repo here: + + [https://repo1.maven.org/maven2/com/google/protobuf/protoc/](https://repo1.maven.org/maven2/com/google/protobuf/protoc/) + +These pre-built binaries are only provided for released versions. If you want +to use the github master version at HEAD, or you need to modify protobuf code, +or you are using C++, it's recommended to build your own protoc binary from +source. + +If you would like to build protoc binary from source, see the [C++ Installation +Instructions](src/README.md). + +Protobuf Runtime Installation +----------------------------- + +Protobuf supports several different programming languages. For each programming +language, you can find instructions in the corresponding source directory about +how to install protobuf runtime for that specific language: + +| Language | Source | Ubuntu | MacOS | Windows | +|--------------------------------------|-------------------------------------------------------------|--------|-------|---------| +| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| Java | [java](java) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_compatibility%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_jdk7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_jdk7%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_oracle7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_oracle7%2Fcontinuous) | | | +| Python | [python](python) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_cpp%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous) | | +| Objective-C | [objectivec](objectivec) | | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_cocoapods_integration.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_debug.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_osx.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous) | | +| C# | [csharp](csharp) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-csharp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) | +| JavaScript | [js](js) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous) | | +| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_all%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby21.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby21%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby22.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby22%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-jruby.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjruby%2Fcontinuous) | | +| Go | [golang/protobuf](https://github.com/golang/protobuf) | | | | +| PHP | [php](php) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-php_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fphp_all%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-32-bit.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2F32-bit%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php5.6_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp5.6_mac%2Fcontinuous)
[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php7.0_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp7.0_mac%2Fcontinuous) | | +| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | | | | + +Quick Start +----------- + +The best way to learn how to use protobuf is to follow the tutorials in our +developer guide: + +https://developers.google.com/protocol-buffers/docs/tutorials + +If you want to learn from code examples, take a look at the examples in the +[examples](examples) directory. + +Documentation +------------- + +The complete documentation for Protocol Buffers is available via the +web at: + +https://developers.google.com/protocol-buffers/ diff --git a/My Mind/Pods/Protobuf/objectivec/GPBArray.h b/My Mind/Pods/Protobuf/objectivec/GPBArray.h new file mode 100644 index 0000000..638b288 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBArray.h @@ -0,0 +1,1967 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBRuntimeTypes.h" + +NS_ASSUME_NONNULL_BEGIN + +//%PDDM-EXPAND DECLARE_ARRAYS() +// This block of code is generated, do not edit it directly. + +#pragma mark - Int32 + +/** + * Class used for repeated fields of int32_t values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32Array : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBInt32Array. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBInt32Array with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBInt32Array with value in it. + **/ ++ (instancetype)arrayWithValue:(int32_t)value; + +/** + * Creates and initializes a GPBInt32Array with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBInt32Array with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBInt32Array *)array; + +/** + * Creates and initializes a GPBInt32Array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBInt32Array with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBInt32Array. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBInt32Array with a copy of the values. + **/ +- (instancetype)initWithValues:(const int32_t [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBInt32Array with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBInt32Array *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBInt32Array with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (int32_t)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(int32_t)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const int32_t [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBInt32Array *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - UInt32 + +/** + * Class used for repeated fields of uint32_t values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32Array : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBUInt32Array. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBUInt32Array with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBUInt32Array with value in it. + **/ ++ (instancetype)arrayWithValue:(uint32_t)value; + +/** + * Creates and initializes a GPBUInt32Array with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBUInt32Array with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBUInt32Array *)array; + +/** + * Creates and initializes a GPBUInt32Array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBUInt32Array with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBUInt32Array. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBUInt32Array with a copy of the values. + **/ +- (instancetype)initWithValues:(const uint32_t [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBUInt32Array with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBUInt32Array *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBUInt32Array with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (uint32_t)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(uint32_t)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const uint32_t [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBUInt32Array *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(uint32_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint32_t)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - Int64 + +/** + * Class used for repeated fields of int64_t values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64Array : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBInt64Array. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBInt64Array with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBInt64Array with value in it. + **/ ++ (instancetype)arrayWithValue:(int64_t)value; + +/** + * Creates and initializes a GPBInt64Array with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBInt64Array with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBInt64Array *)array; + +/** + * Creates and initializes a GPBInt64Array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBInt64Array with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBInt64Array. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBInt64Array with a copy of the values. + **/ +- (instancetype)initWithValues:(const int64_t [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBInt64Array with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBInt64Array *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBInt64Array with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (int64_t)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(int64_t)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const int64_t [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBInt64Array *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(int64_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int64_t)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - UInt64 + +/** + * Class used for repeated fields of uint64_t values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64Array : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBUInt64Array. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBUInt64Array with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBUInt64Array with value in it. + **/ ++ (instancetype)arrayWithValue:(uint64_t)value; + +/** + * Creates and initializes a GPBUInt64Array with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBUInt64Array with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBUInt64Array *)array; + +/** + * Creates and initializes a GPBUInt64Array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBUInt64Array with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBUInt64Array. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBUInt64Array with a copy of the values. + **/ +- (instancetype)initWithValues:(const uint64_t [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBUInt64Array with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBUInt64Array *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBUInt64Array with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (uint64_t)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(uint64_t)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const uint64_t [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBUInt64Array *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(uint64_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint64_t)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - Float + +/** + * Class used for repeated fields of float values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBFloatArray : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBFloatArray. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBFloatArray with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBFloatArray with value in it. + **/ ++ (instancetype)arrayWithValue:(float)value; + +/** + * Creates and initializes a GPBFloatArray with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBFloatArray with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBFloatArray *)array; + +/** + * Creates and initializes a GPBFloatArray with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBFloatArray with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBFloatArray. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBFloatArray with a copy of the values. + **/ +- (instancetype)initWithValues:(const float [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBFloatArray with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBFloatArray *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBFloatArray with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (float)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(float)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const float [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBFloatArray *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(float)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(float)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - Double + +/** + * Class used for repeated fields of double values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBDoubleArray : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBDoubleArray. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBDoubleArray with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBDoubleArray with value in it. + **/ ++ (instancetype)arrayWithValue:(double)value; + +/** + * Creates and initializes a GPBDoubleArray with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBDoubleArray with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBDoubleArray *)array; + +/** + * Creates and initializes a GPBDoubleArray with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBDoubleArray with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBDoubleArray. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBDoubleArray with a copy of the values. + **/ +- (instancetype)initWithValues:(const double [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBDoubleArray with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBDoubleArray *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBDoubleArray with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (double)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(double)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const double [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBDoubleArray *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(double)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(double)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - Bool + +/** + * Class used for repeated fields of BOOL values. This performs better than + * boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolArray : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * @return A newly instanced and empty GPBBoolArray. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBBoolArray with the single element given. + * + * @param value The value to be placed in the array. + * + * @return A newly instanced GPBBoolArray with value in it. + **/ ++ (instancetype)arrayWithValue:(BOOL)value; + +/** + * Creates and initializes a GPBBoolArray with the contents of the given + * array. + * + * @param array Array with the contents to be put into the new array. + * + * @return A newly instanced GPBBoolArray with the contents of array. + **/ ++ (instancetype)arrayWithValueArray:(GPBBoolArray *)array; + +/** + * Creates and initializes a GPBBoolArray with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBBoolArray with a capacity of count. + **/ ++ (instancetype)arrayWithCapacity:(NSUInteger)count; + +/** + * @return A newly initialized and empty GPBBoolArray. + **/ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBBoolArray with a copy of the values. + **/ +- (instancetype)initWithValues:(const BOOL [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBBoolArray with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBBoolArray *)array; + +/** + * Initializes the array with the given capacity. + * + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBBoolArray with a capacity of count. + **/ +- (instancetype)initWithCapacity:(NSUInteger)count; + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (BOOL)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block; + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(BOOL)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const BOOL [__nullable])values count:(NSUInteger)count; + +/** + * Adds the values from the given array to this array. + * + * @param array The array containing the elements to add to this array. + **/ +- (void)addValuesFromArray:(GPBBoolArray *)array; + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(BOOL)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(BOOL)value; + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +#pragma mark - Enum + +/** + * This class is used for repeated fields of int32_t values. This performs + * better than boxing into NSNumbers in NSArrays. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBEnumArray : NSObject + +/** The number of elements contained in the array. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * @return A newly instanced and empty GPBEnumArray. + **/ ++ (instancetype)array; + +/** + * Creates and initializes a GPBEnumArray with the enum validation function + * given. + * + * @param func The enum validation function for the array. + * + * @return A newly instanced GPBEnumArray. + **/ ++ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Creates and initializes a GPBEnumArray with the enum validation function + * given and the single raw value given. + * + * @param func The enum validation function for the array. + * @param value The raw value to add to this array. + * + * @return A newly instanced GPBEnumArray. + **/ ++ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValue:(int32_t)value; + +/** + * Creates and initializes a GPBEnumArray that adds the elements from the + * given array. + * + * @param array Array containing the values to add to the new array. + * + * @return A newly instanced GPBEnumArray. + **/ ++ (instancetype)arrayWithValueArray:(GPBEnumArray *)array; + +/** + * Creates and initializes a GPBEnumArray with the given enum validation + * function and with the givencapacity. + * + * @param func The enum validation function for the array. + * @param count The capacity needed for the array. + * + * @return A newly instanced GPBEnumArray with a capacity of count. + **/ ++ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)count; + +/** + * Initializes the array with the given enum validation function. + * + * @param func The enum validation function for the array. + * + * @return A newly initialized GPBEnumArray with a copy of the values. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + NS_DESIGNATED_INITIALIZER; + +/** + * Initializes the array, copying the given values. + * + * @param func The enum validation function for the array. + * @param values An array with the values to put inside this array. + * @param count The number of elements to copy into the array. + * + * @return A newly initialized GPBEnumArray with a copy of the values. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + count:(NSUInteger)count; + +/** + * Initializes the array, copying the given values. + * + * @param array An array with the values to put inside this array. + * + * @return A newly initialized GPBEnumArray with a copy of the values. + **/ +- (instancetype)initWithValueArray:(GPBEnumArray *)array; + +/** + * Initializes the array with the given capacity. + * + * @param func The enum validation function for the array. + * @param count The capacity needed for the array. + * + * @return A newly initialized GPBEnumArray with a capacity of count. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)count; + +// These will return kGPBUnrecognizedEnumeratorValue if the value at index is not a +// valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value at the given index. + * + * @param index The index of the value to get. + * + * @return The value at the given index. + **/ +- (int32_t)valueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +// These methods bypass the validationFunc to provide access to values that were not +// known at the time the binary was compiled. + +/** + * Gets the raw enum value at the given index. + * + * @param index The index of the raw enum value to get. + * + * @return The raw enum value at the given index. + **/ +- (int32_t)rawValueAtIndex:(NSUInteger)index; + +/** + * Enumerates the values on this array with the given block. + * + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +/** + * Enumerates the values on this array with the given block. + * + * @param opts Options to control the enumeration. + * @param block The block to enumerate with. + * **value**: The current value being enumerated. + * **idx**: The index of the current value. + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Adds a value to this array. + * + * @param value The value to add to this array. + **/ +- (void)addValue:(int32_t)value; + +/** + * Adds values to this array. + * + * @param values The values to add to this array. + * @param count The number of elements to add. + **/ +- (void)addValues:(const int32_t [__nullable])values count:(NSUInteger)count; + + +/** + * Inserts a value into the given position. + * + * @param value The value to add to this array. + * @param index The index into which to insert the value. + **/ +- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the value at the given index with the given value. + * + * @param index The index for which to replace the value. + * @param value The value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value; + +// These methods bypass the validationFunc to provide setting of values that were not +// known at the time the binary was compiled. + +/** + * Adds a raw enum value to this array. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param value The raw enum value to add to the array. + **/ +- (void)addRawValue:(int32_t)value; + +/** + * Adds raw enum values to this array. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param array Array containing the raw enum values to add to this array. + **/ +- (void)addRawValuesFromArray:(GPBEnumArray *)array; + +/** + * Adds raw enum values to this array. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param values Array containing the raw enum values to add to this array. + * @param count The number of raw values to add. + **/ +- (void)addRawValues:(const int32_t [__nullable])values count:(NSUInteger)count; + +/** + * Inserts a raw enum value at the given index. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param value Raw enum value to add. + * @param index The index into which to insert the value. + **/ +- (void)insertRawValue:(int32_t)value atIndex:(NSUInteger)index; + +/** + * Replaces the raw enum value at the given index with the given value. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param index The index for which to replace the value. + * @param value The raw enum value to replace with. + **/ +- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(int32_t)value; + +// No validation applies to these methods. + +/** + * Removes the value at the given index. + * + * @param index The index of the value to remove. + **/ +- (void)removeValueAtIndex:(NSUInteger)index; + +/** + * Removes all the values from this array. + **/ +- (void)removeAll; + +/** + * Exchanges the values between the given indexes. + * + * @param idx1 The index of the first element to exchange. + * @param idx2 The index of the second element to exchange. + **/ +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2; + +@end + +//%PDDM-EXPAND-END DECLARE_ARRAYS() + +NS_ASSUME_NONNULL_END + +//%PDDM-DEFINE DECLARE_ARRAYS() +//%ARRAY_INTERFACE_SIMPLE(Int32, int32_t) +//%ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t) +//%ARRAY_INTERFACE_SIMPLE(Int64, int64_t) +//%ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t) +//%ARRAY_INTERFACE_SIMPLE(Float, float) +//%ARRAY_INTERFACE_SIMPLE(Double, double) +//%ARRAY_INTERFACE_SIMPLE(Bool, BOOL) +//%ARRAY_INTERFACE_ENUM(Enum, int32_t) + +// +// The common case (everything but Enum) +// + +//%PDDM-DEFINE ARRAY_INTERFACE_SIMPLE(NAME, TYPE) +//%#pragma mark - NAME +//% +//%/** +//% * Class used for repeated fields of ##TYPE## values. This performs better than +//% * boxing into NSNumbers in NSArrays. +//% * +//% * @note This class is not meant to be subclassed. +//% **/ +//%@interface GPB##NAME##Array : NSObject +//% +//%/** The number of elements contained in the array. */ +//%@property(nonatomic, readonly) NSUInteger count; +//% +//%/** +//% * @return A newly instanced and empty GPB##NAME##Array. +//% **/ +//%+ (instancetype)array; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the single element given. +//% * +//% * @param value The value to be placed in the array. +//% * +//% * @return A newly instanced GPB##NAME##Array with value in it. +//% **/ +//%+ (instancetype)arrayWithValue:(TYPE)value; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the contents of the given +//% * array. +//% * +//% * @param array Array with the contents to be put into the new array. +//% * +//% * @return A newly instanced GPB##NAME##Array with the contents of array. +//% **/ +//%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the given capacity. +//% * +//% * @param count The capacity needed for the array. +//% * +//% * @return A newly instanced GPB##NAME##Array with a capacity of count. +//% **/ +//%+ (instancetype)arrayWithCapacity:(NSUInteger)count; +//% +//%/** +//% * @return A newly initialized and empty GPB##NAME##Array. +//% **/ +//%- (instancetype)init NS_DESIGNATED_INITIALIZER; +//% +//%/** +//% * Initializes the array, copying the given values. +//% * +//% * @param values An array with the values to put inside this array. +//% * @param count The number of elements to copy into the array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a copy of the values. +//% **/ +//%- (instancetype)initWithValues:(const TYPE [__nullable])values +//% count:(NSUInteger)count; +//% +//%/** +//% * Initializes the array, copying the given values. +//% * +//% * @param array An array with the values to put inside this array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a copy of the values. +//% **/ +//%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; +//% +//%/** +//% * Initializes the array with the given capacity. +//% * +//% * @param count The capacity needed for the array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a capacity of count. +//% **/ +//%- (instancetype)initWithCapacity:(NSUInteger)count; +//% +//%ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, Basic) +//% +//%ARRAY_MUTABLE_INTERFACE(NAME, TYPE, Basic) +//% +//%@end +//% + +// +// Macros specific to Enums (to tweak their interface). +// + +//%PDDM-DEFINE ARRAY_INTERFACE_ENUM(NAME, TYPE) +//%#pragma mark - NAME +//% +//%/** +//% * This class is used for repeated fields of ##TYPE## values. This performs +//% * better than boxing into NSNumbers in NSArrays. +//% * +//% * @note This class is not meant to be subclassed. +//% **/ +//%@interface GPB##NAME##Array : NSObject +//% +//%/** The number of elements contained in the array. */ +//%@property(nonatomic, readonly) NSUInteger count; +//%/** The validation function to check if the enums are valid. */ +//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; +//% +//%/** +//% * @return A newly instanced and empty GPB##NAME##Array. +//% **/ +//%+ (instancetype)array; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the enum validation function +//% * given. +//% * +//% * @param func The enum validation function for the array. +//% * +//% * @return A newly instanced GPB##NAME##Array. +//% **/ +//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the enum validation function +//% * given and the single raw value given. +//% * +//% * @param func The enum validation function for the array. +//% * @param value The raw value to add to this array. +//% * +//% * @return A newly instanced GPB##NAME##Array. +//% **/ +//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% rawValue:(TYPE)value; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array that adds the elements from the +//% * given array. +//% * +//% * @param array Array containing the values to add to the new array. +//% * +//% * @return A newly instanced GPB##NAME##Array. +//% **/ +//%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array; +//% +//%/** +//% * Creates and initializes a GPB##NAME##Array with the given enum validation +//% * function and with the givencapacity. +//% * +//% * @param func The enum validation function for the array. +//% * @param count The capacity needed for the array. +//% * +//% * @return A newly instanced GPB##NAME##Array with a capacity of count. +//% **/ +//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% capacity:(NSUInteger)count; +//% +//%/** +//% * Initializes the array with the given enum validation function. +//% * +//% * @param func The enum validation function for the array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a copy of the values. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% NS_DESIGNATED_INITIALIZER; +//% +//%/** +//% * Initializes the array, copying the given values. +//% * +//% * @param func The enum validation function for the array. +//% * @param values An array with the values to put inside this array. +//% * @param count The number of elements to copy into the array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a copy of the values. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% rawValues:(const TYPE [__nullable])values +//% count:(NSUInteger)count; +//% +//%/** +//% * Initializes the array, copying the given values. +//% * +//% * @param array An array with the values to put inside this array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a copy of the values. +//% **/ +//%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; +//% +//%/** +//% * Initializes the array with the given capacity. +//% * +//% * @param func The enum validation function for the array. +//% * @param count The capacity needed for the array. +//% * +//% * @return A newly initialized GPB##NAME##Array with a capacity of count. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% capacity:(NSUInteger)count; +//% +//%// These will return kGPBUnrecognizedEnumeratorValue if the value at index is not a +//%// valid enumerator as defined by validationFunc. If the actual value is +//%// desired, use "raw" version of the method. +//% +//%ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, NAME) +//% +//%// These methods bypass the validationFunc to provide access to values that were not +//%// known at the time the binary was compiled. +//% +//%/** +//% * Gets the raw enum value at the given index. +//% * +//% * @param index The index of the raw enum value to get. +//% * +//% * @return The raw enum value at the given index. +//% **/ +//%- (TYPE)rawValueAtIndex:(NSUInteger)index; +//% +//%/** +//% * Enumerates the values on this array with the given block. +//% * +//% * @param block The block to enumerate with. +//% * **value**: The current value being enumerated. +//% * **idx**: The index of the current value. +//% * **stop**: A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateRawValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//% +//%/** +//% * Enumerates the values on this array with the given block. +//% * +//% * @param opts Options to control the enumeration. +//% * @param block The block to enumerate with. +//% * **value**: The current value being enumerated. +//% * **idx**: The index of the current value. +//% * **stop**: A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts +//% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//% +//%// If value is not a valid enumerator as defined by validationFunc, these +//%// methods will assert in debug, and will log in release and assign the value +//%// to the default value. Use the rawValue methods below to assign non enumerator +//%// values. +//% +//%ARRAY_MUTABLE_INTERFACE(NAME, TYPE, NAME) +//% +//%@end +//% + +//%PDDM-DEFINE ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME) +//%/** +//% * Gets the value at the given index. +//% * +//% * @param index The index of the value to get. +//% * +//% * @return The value at the given index. +//% **/ +//%- (TYPE)valueAtIndex:(NSUInteger)index; +//% +//%/** +//% * Enumerates the values on this array with the given block. +//% * +//% * @param block The block to enumerate with. +//% * **value**: The current value being enumerated. +//% * **idx**: The index of the current value. +//% * **stop**: A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//% +//%/** +//% * Enumerates the values on this array with the given block. +//% * +//% * @param opts Options to control the enumeration. +//% * @param block The block to enumerate with. +//% * **value**: The current value being enumerated. +//% * **idx**: The index of the current value. +//% * **stop**: A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts +//% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; + +//%PDDM-DEFINE ARRAY_MUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME) +//%/** +//% * Adds a value to this array. +//% * +//% * @param value The value to add to this array. +//% **/ +//%- (void)addValue:(TYPE)value; +//% +//%/** +//% * Adds values to this array. +//% * +//% * @param values The values to add to this array. +//% * @param count The number of elements to add. +//% **/ +//%- (void)addValues:(const TYPE [__nullable])values count:(NSUInteger)count; +//% +//%ARRAY_EXTRA_MUTABLE_METHODS1_##HELPER_NAME(NAME, TYPE) +//%/** +//% * Inserts a value into the given position. +//% * +//% * @param value The value to add to this array. +//% * @param index The index into which to insert the value. +//% **/ +//%- (void)insertValue:(TYPE)value atIndex:(NSUInteger)index; +//% +//%/** +//% * Replaces the value at the given index with the given value. +//% * +//% * @param index The index for which to replace the value. +//% * @param value The value to replace with. +//% **/ +//%- (void)replaceValueAtIndex:(NSUInteger)index withValue:(TYPE)value; +//%ARRAY_EXTRA_MUTABLE_METHODS2_##HELPER_NAME(NAME, TYPE) +//%/** +//% * Removes the value at the given index. +//% * +//% * @param index The index of the value to remove. +//% **/ +//%- (void)removeValueAtIndex:(NSUInteger)index; +//% +//%/** +//% * Removes all the values from this array. +//% **/ +//%- (void)removeAll; +//% +//%/** +//% * Exchanges the values between the given indexes. +//% * +//% * @param idx1 The index of the first element to exchange. +//% * @param idx2 The index of the second element to exchange. +//% **/ +//%- (void)exchangeValueAtIndex:(NSUInteger)idx1 +//% withValueAtIndex:(NSUInteger)idx2; + +// +// These are hooks invoked by the above to do insert as needed. +// + +//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS1_Basic(NAME, TYPE) +//%/** +//% * Adds the values from the given array to this array. +//% * +//% * @param array The array containing the elements to add to this array. +//% **/ +//%- (void)addValuesFromArray:(GPB##NAME##Array *)array; +//% +//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS2_Basic(NAME, TYPE) +// Empty +//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS1_Enum(NAME, TYPE) +// Empty +//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS2_Enum(NAME, TYPE) +//% +//%// These methods bypass the validationFunc to provide setting of values that were not +//%// known at the time the binary was compiled. +//% +//%/** +//% * Adds a raw enum value to this array. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param value The raw enum value to add to the array. +//% **/ +//%- (void)addRawValue:(TYPE)value; +//% +//%/** +//% * Adds raw enum values to this array. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param array Array containing the raw enum values to add to this array. +//% **/ +//%- (void)addRawValuesFromArray:(GPB##NAME##Array *)array; +//% +//%/** +//% * Adds raw enum values to this array. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param values Array containing the raw enum values to add to this array. +//% * @param count The number of raw values to add. +//% **/ +//%- (void)addRawValues:(const TYPE [__nullable])values count:(NSUInteger)count; +//% +//%/** +//% * Inserts a raw enum value at the given index. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param value Raw enum value to add. +//% * @param index The index into which to insert the value. +//% **/ +//%- (void)insertRawValue:(TYPE)value atIndex:(NSUInteger)index; +//% +//%/** +//% * Replaces the raw enum value at the given index with the given value. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param index The index for which to replace the value. +//% * @param value The raw enum value to replace with. +//% **/ +//%- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(TYPE)value; +//% +//%// No validation applies to these methods. +//% diff --git a/My Mind/Pods/Protobuf/objectivec/GPBArray.m b/My Mind/Pods/Protobuf/objectivec/GPBArray.m new file mode 100644 index 0000000..122e030 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBArray.m @@ -0,0 +1,2551 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBArray_PackagePrivate.h" + +#import "GPBMessage_PackagePrivate.h" + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +// Mutable arrays use an internal buffer that can always hold a multiple of this elements. +#define kChunkSize 16 +#define CapacityFromCount(x) (((x / kChunkSize) + 1) * kChunkSize) + +static BOOL ArrayDefault_IsValidValue(int32_t value) { + // Anything but the bad value marker is allowed. + return (value != kGPBUnrecognizedEnumeratorValue); +} + +//%PDDM-DEFINE VALIDATE_RANGE(INDEX, COUNT) +//% if (INDEX >= COUNT) { +//% [NSException raise:NSRangeException +//% format:@"Index (%lu) beyond bounds (%lu)", +//% (unsigned long)INDEX, (unsigned long)COUNT]; +//% } +//%PDDM-DEFINE MAYBE_GROW_TO_SET_COUNT(NEW_COUNT) +//% if (NEW_COUNT > _capacity) { +//% [self internalResizeToCapacity:CapacityFromCount(NEW_COUNT)]; +//% } +//% _count = NEW_COUNT; +//%PDDM-DEFINE SET_COUNT_AND_MAYBE_SHRINK(NEW_COUNT) +//% _count = NEW_COUNT; +//% if ((NEW_COUNT + (2 * kChunkSize)) < _capacity) { +//% [self internalResizeToCapacity:CapacityFromCount(NEW_COUNT)]; +//% } + +// +// Macros for the common basic cases. +// + +//%PDDM-DEFINE ARRAY_INTERFACE_SIMPLE(NAME, TYPE, FORMAT) +//%#pragma mark - NAME +//% +//%@implementation GPB##NAME##Array { +//% @package +//% TYPE *_values; +//% NSUInteger _count; +//% NSUInteger _capacity; +//%} +//% +//%@synthesize count = _count; +//% +//%+ (instancetype)array { +//% return [[[self alloc] init] autorelease]; +//%} +//% +//%+ (instancetype)arrayWithValue:(TYPE)value { +//% // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get +//% // the type correct. +//% return [[(GPB##NAME##Array*)[self alloc] initWithValues:&value count:1] autorelease]; +//%} +//% +//%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array { +//% return [[(GPB##NAME##Array*)[self alloc] initWithValueArray:array] autorelease]; +//%} +//% +//%+ (instancetype)arrayWithCapacity:(NSUInteger)count { +//% return [[[self alloc] initWithCapacity:count] autorelease]; +//%} +//% +//%- (instancetype)init { +//% self = [super init]; +//% // No work needed; +//% return self; +//%} +//% +//%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array { +//% return [self initWithValues:array->_values count:array->_count]; +//%} +//% +//%- (instancetype)initWithValues:(const TYPE [])values count:(NSUInteger)count { +//% self = [self init]; +//% if (self) { +//% if (count && values) { +//% _values = reallocf(_values, count * sizeof(TYPE)); +//% if (_values != NULL) { +//% _capacity = count; +//% memcpy(_values, values, count * sizeof(TYPE)); +//% _count = count; +//% } else { +//% [self release]; +//% [NSException raise:NSMallocException +//% format:@"Failed to allocate %lu bytes", +//% (unsigned long)(count * sizeof(TYPE))]; +//% } +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithCapacity:(NSUInteger)count { +//% self = [self initWithValues:NULL count:0]; +//% if (self && count) { +//% [self internalResizeToCapacity:count]; +//% } +//% return self; +//%} +//% +//%- (instancetype)copyWithZone:(NSZone *)zone { +//% return [[GPB##NAME##Array allocWithZone:zone] initWithValues:_values count:_count]; +//%} +//% +//%ARRAY_IMMUTABLE_CORE(NAME, TYPE, , FORMAT) +//% +//%- (TYPE)valueAtIndex:(NSUInteger)index { +//%VALIDATE_RANGE(index, _count) +//% return _values[index]; +//%} +//% +//%ARRAY_MUTABLE_CORE(NAME, TYPE, , FORMAT) +//%@end +//% + +// +// Some core macros used for both the simple types and Enums. +// + +//%PDDM-DEFINE ARRAY_IMMUTABLE_CORE(NAME, TYPE, ACCESSOR_NAME, FORMAT) +//%- (void)dealloc { +//% NSAssert(!_autocreator, +//% @"%@: Autocreator must be cleared before release, autocreator: %@", +//% [self class], _autocreator); +//% free(_values); +//% [super dealloc]; +//%} +//% +//%- (BOOL)isEqual:(id)other { +//% if (self == other) { +//% return YES; +//% } +//% if (![other isKindOfClass:[GPB##NAME##Array class]]) { +//% return NO; +//% } +//% GPB##NAME##Array *otherArray = other; +//% return (_count == otherArray->_count +//% && memcmp(_values, otherArray->_values, (_count * sizeof(TYPE))) == 0); +//%} +//% +//%- (NSUInteger)hash { +//% // Follow NSArray's lead, and use the count as the hash. +//% return _count; +//%} +//% +//%- (NSString *)description { +//% NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; +//% for (NSUInteger i = 0, count = _count; i < count; ++i) { +//% if (i == 0) { +//% [result appendFormat:@"##FORMAT##", _values[i]]; +//% } else { +//% [result appendFormat:@", ##FORMAT##", _values[i]]; +//% } +//% } +//% [result appendFormat:@" }"]; +//% return result; +//%} +//% +//%- (void)enumerate##ACCESSOR_NAME##ValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block { +//% [self enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +//%} +//% +//%- (void)enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)opts +//% ACCESSOR_NAME$S usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block { +//% // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). +//% BOOL stop = NO; +//% if ((opts & NSEnumerationReverse) == 0) { +//% for (NSUInteger i = 0, count = _count; i < count; ++i) { +//% block(_values[i], i, &stop); +//% if (stop) break; +//% } +//% } else if (_count > 0) { +//% for (NSUInteger i = _count; i > 0; --i) { +//% block(_values[i - 1], (i - 1), &stop); +//% if (stop) break; +//% } +//% } +//%} + +//%PDDM-DEFINE MUTATION_HOOK_None() +//%PDDM-DEFINE MUTATION_METHODS(NAME, TYPE, ACCESSOR_NAME, HOOK_1, HOOK_2) +//%- (void)add##ACCESSOR_NAME##Value:(TYPE)value { +//% [self add##ACCESSOR_NAME##Values:&value count:1]; +//%} +//% +//%- (void)add##ACCESSOR_NAME##Values:(const TYPE [])values count:(NSUInteger)count { +//% if (values == NULL || count == 0) return; +//%MUTATION_HOOK_##HOOK_1() NSUInteger initialCount = _count; +//% NSUInteger newCount = initialCount + count; +//%MAYBE_GROW_TO_SET_COUNT(newCount) +//% memcpy(&_values[initialCount], values, count * sizeof(TYPE)); +//% if (_autocreator) { +//% GPBAutocreatedArrayModified(_autocreator, self); +//% } +//%} +//% +//%- (void)insert##ACCESSOR_NAME##Value:(TYPE)value atIndex:(NSUInteger)index { +//%VALIDATE_RANGE(index, _count + 1) +//%MUTATION_HOOK_##HOOK_2() NSUInteger initialCount = _count; +//% NSUInteger newCount = initialCount + 1; +//%MAYBE_GROW_TO_SET_COUNT(newCount) +//% if (index != initialCount) { +//% memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(TYPE)); +//% } +//% _values[index] = value; +//% if (_autocreator) { +//% GPBAutocreatedArrayModified(_autocreator, self); +//% } +//%} +//% +//%- (void)replaceValueAtIndex:(NSUInteger)index with##ACCESSOR_NAME##Value:(TYPE)value { +//%VALIDATE_RANGE(index, _count) +//%MUTATION_HOOK_##HOOK_2() _values[index] = value; +//%} + +//%PDDM-DEFINE ARRAY_MUTABLE_CORE(NAME, TYPE, ACCESSOR_NAME, FORMAT) +//%- (void)internalResizeToCapacity:(NSUInteger)newCapacity { +//% _values = reallocf(_values, newCapacity * sizeof(TYPE)); +//% if (_values == NULL) { +//% _capacity = 0; +//% _count = 0; +//% [NSException raise:NSMallocException +//% format:@"Failed to allocate %lu bytes", +//% (unsigned long)(newCapacity * sizeof(TYPE))]; +//% } +//% _capacity = newCapacity; +//%} +//% +//%MUTATION_METHODS(NAME, TYPE, ACCESSOR_NAME, None, None) +//% +//%- (void)add##ACCESSOR_NAME##ValuesFromArray:(GPB##NAME##Array *)array { +//% [self add##ACCESSOR_NAME##Values:array->_values count:array->_count]; +//%} +//% +//%- (void)removeValueAtIndex:(NSUInteger)index { +//%VALIDATE_RANGE(index, _count) +//% NSUInteger newCount = _count - 1; +//% if (index != newCount) { +//% memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(TYPE)); +//% } +//%SET_COUNT_AND_MAYBE_SHRINK(newCount) +//%} +//% +//%- (void)removeAll { +//%SET_COUNT_AND_MAYBE_SHRINK(0) +//%} +//% +//%- (void)exchangeValueAtIndex:(NSUInteger)idx1 +//% withValueAtIndex:(NSUInteger)idx2 { +//%VALIDATE_RANGE(idx1, _count) +//%VALIDATE_RANGE(idx2, _count) +//% TYPE temp = _values[idx1]; +//% _values[idx1] = _values[idx2]; +//% _values[idx2] = temp; +//%} +//% + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int32, int32_t, %d) +// This block of code is generated, do not edit it directly. + +#pragma mark - Int32 + +@implementation GPBInt32Array { + @package + int32_t *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(int32_t)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBInt32Array*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBInt32Array *)array { + return [[(GPBInt32Array*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBInt32Array *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const int32_t [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(int32_t)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(int32_t)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(int32_t))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32Array allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32Array class]]) { + return NO; + } + GPBInt32Array *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(int32_t))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%d", _values[i]]; + } else { + [result appendFormat:@", %d", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (int32_t)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(int32_t)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(int32_t))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(int32_t)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const int32_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(int32_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBInt32Array *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int32_t)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + int32_t temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t, %u) +// This block of code is generated, do not edit it directly. + +#pragma mark - UInt32 + +@implementation GPBUInt32Array { + @package + uint32_t *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(uint32_t)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBUInt32Array*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBUInt32Array *)array { + return [[(GPBUInt32Array*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBUInt32Array *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const uint32_t [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(uint32_t)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(uint32_t)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(uint32_t))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32Array allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32Array class]]) { + return NO; + } + GPBUInt32Array *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(uint32_t))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%u", _values[i]]; + } else { + [result appendFormat:@", %u", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (uint32_t)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(uint32_t)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(uint32_t))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(uint32_t)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const uint32_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(uint32_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(uint32_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(uint32_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint32_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBUInt32Array *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(uint32_t)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + uint32_t temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int64, int64_t, %lld) +// This block of code is generated, do not edit it directly. + +#pragma mark - Int64 + +@implementation GPBInt64Array { + @package + int64_t *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(int64_t)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBInt64Array*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBInt64Array *)array { + return [[(GPBInt64Array*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBInt64Array *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const int64_t [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(int64_t)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(int64_t)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(int64_t))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64Array allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64Array class]]) { + return NO; + } + GPBInt64Array *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(int64_t))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%lld", _values[i]]; + } else { + [result appendFormat:@", %lld", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (int64_t)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(int64_t)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(int64_t))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(int64_t)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const int64_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(int64_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(int64_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int64_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int64_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBInt64Array *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int64_t)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + int64_t temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t, %llu) +// This block of code is generated, do not edit it directly. + +#pragma mark - UInt64 + +@implementation GPBUInt64Array { + @package + uint64_t *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(uint64_t)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBUInt64Array*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBUInt64Array *)array { + return [[(GPBUInt64Array*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBUInt64Array *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const uint64_t [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(uint64_t)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(uint64_t)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(uint64_t))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64Array allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64Array class]]) { + return NO; + } + GPBUInt64Array *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(uint64_t))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%llu", _values[i]]; + } else { + [result appendFormat:@", %llu", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (uint64_t)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(uint64_t)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(uint64_t))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(uint64_t)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const uint64_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(uint64_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(uint64_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(uint64_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint64_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBUInt64Array *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(uint64_t)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + uint64_t temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Float, float, %f) +// This block of code is generated, do not edit it directly. + +#pragma mark - Float + +@implementation GPBFloatArray { + @package + float *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(float)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBFloatArray*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBFloatArray *)array { + return [[(GPBFloatArray*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBFloatArray *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const float [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(float)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(float)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(float))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBFloatArray allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBFloatArray class]]) { + return NO; + } + GPBFloatArray *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(float))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%f", _values[i]]; + } else { + [result appendFormat:@", %f", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (float)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(float)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(float))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(float)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const float [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(float)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(float)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(float)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(float)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBFloatArray *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(float)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + float temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Double, double, %lf) +// This block of code is generated, do not edit it directly. + +#pragma mark - Double + +@implementation GPBDoubleArray { + @package + double *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(double)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBDoubleArray*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBDoubleArray *)array { + return [[(GPBDoubleArray*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBDoubleArray *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const double [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(double)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(double)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(double))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBDoubleArray allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBDoubleArray class]]) { + return NO; + } + GPBDoubleArray *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(double))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%lf", _values[i]]; + } else { + [result appendFormat:@", %lf", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (double)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(double)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(double))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(double)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const double [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(double)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(double)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(double)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(double)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBDoubleArray *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(double)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + double temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Bool, BOOL, %d) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool + +@implementation GPBBoolArray { + @package + BOOL *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; + ++ (instancetype)array { + return [[[self alloc] init] autorelease]; +} + ++ (instancetype)arrayWithValue:(BOOL)value { + // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get + // the type correct. + return [[(GPBBoolArray*)[self alloc] initWithValues:&value count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBBoolArray *)array { + return [[(GPBBoolArray*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithCapacity:count] autorelease]; +} + +- (instancetype)init { + self = [super init]; + // No work needed; + return self; +} + +- (instancetype)initWithValueArray:(GPBBoolArray *)array { + return [self initWithValues:array->_values count:array->_count]; +} + +- (instancetype)initWithValues:(const BOOL [])values count:(NSUInteger)count { + self = [self init]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(BOOL)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(BOOL)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(BOOL))]; + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)count { + self = [self initWithValues:NULL count:0]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolArray allocWithZone:zone] initWithValues:_values count:_count]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolArray class]]) { + return NO; + } + GPBBoolArray *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(BOOL))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%d", _values[i]]; + } else { + [result appendFormat:@", %d", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} + +- (BOOL)valueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + return _values[index]; +} + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(BOOL)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(BOOL))]; + } + _capacity = newCapacity; +} + +- (void)addValue:(BOOL)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const BOOL [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(BOOL)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(BOOL)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(BOOL)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(BOOL)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addValuesFromArray:(GPBBoolArray *)array { + [self addValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(BOOL)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + BOOL temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +@end + +//%PDDM-EXPAND-END (7 expansions) + +#pragma mark - Enum + +@implementation GPBEnumArray { + @package + GPBEnumValidationFunc _validationFunc; + int32_t *_values; + NSUInteger _count; + NSUInteger _capacity; +} + +@synthesize count = _count; +@synthesize validationFunc = _validationFunc; + ++ (instancetype)array { + return [[[self alloc] initWithValidationFunction:NULL] autorelease]; +} + ++ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func { + return [[[self alloc] initWithValidationFunction:func] autorelease]; +} + ++ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func + rawValue:(int32_t)value { + return [[[self alloc] initWithValidationFunction:func + rawValues:&value + count:1] autorelease]; +} + ++ (instancetype)arrayWithValueArray:(GPBEnumArray *)array { + return [[(GPBEnumArray*)[self alloc] initWithValueArray:array] autorelease]; +} + ++ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)count { + return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease]; +} + +- (instancetype)init { + return [self initWithValidationFunction:NULL]; +} + +- (instancetype)initWithValueArray:(GPBEnumArray *)array { + return [self initWithValidationFunction:array->_validationFunc + rawValues:array->_values + count:array->_count]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + self = [super init]; + if (self) { + _validationFunc = (func != NULL ? func : ArrayDefault_IsValidValue); + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])values + count:(NSUInteger)count { + self = [self initWithValidationFunction:func]; + if (self) { + if (count && values) { + _values = reallocf(_values, count * sizeof(int32_t)); + if (_values != NULL) { + _capacity = count; + memcpy(_values, values, count * sizeof(int32_t)); + _count = count; + } else { + [self release]; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(count * sizeof(int32_t))]; + } + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)count { + self = [self initWithValidationFunction:func]; + if (self && count) { + [self internalResizeToCapacity:count]; + } + return self; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBEnumArray allocWithZone:zone] + initWithValidationFunction:_validationFunc + rawValues:_values + count:_count]; +} + +//%PDDM-EXPAND ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) +// This block of code is generated, do not edit it directly. + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + free(_values); + [super dealloc]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBEnumArray class]]) { + return NO; + } + GPBEnumArray *otherArray = other; + return (_count == otherArray->_count + && memcmp(_values, otherArray->_values, (_count * sizeof(int32_t))) == 0); +} + +- (NSUInteger)hash { + // Follow NSArray's lead, and use the count as the hash. + return _count; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; + for (NSUInteger i = 0, count = _count; i < count; ++i) { + if (i == 0) { + [result appendFormat:@"%d", _values[i]]; + } else { + [result appendFormat:@", %d", _values[i]]; + } + } + [result appendFormat:@" }"]; + return result; +} + +- (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateRawValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + if ((opts & NSEnumerationReverse) == 0) { + for (NSUInteger i = 0, count = _count; i < count; ++i) { + block(_values[i], i, &stop); + if (stop) break; + } + } else if (_count > 0) { + for (NSUInteger i = _count; i > 0; --i) { + block(_values[i - 1], (i - 1), &stop); + if (stop) break; + } + } +} +//%PDDM-EXPAND-END ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) + +- (int32_t)valueAtIndex:(NSUInteger)index { +//%PDDM-EXPAND VALIDATE_RANGE(index, _count) +// This block of code is generated, do not edit it directly. + + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } +//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) + int32_t result = _values[index]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + return result; +} + +- (int32_t)rawValueAtIndex:(NSUInteger)index { +//%PDDM-EXPAND VALIDATE_RANGE(index, _count) +// This block of code is generated, do not edit it directly. + + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } +//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) + return _values[index]; +} + +- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; +} + +- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { + // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). + BOOL stop = NO; + GPBEnumValidationFunc func = _validationFunc; + if ((opts & NSEnumerationReverse) == 0) { + int32_t *scan = _values; + int32_t *end = scan + _count; + for (NSUInteger i = 0; scan < end; ++i, ++scan) { + int32_t value = *scan; + if (!func(value)) { + value = kGPBUnrecognizedEnumeratorValue; + } + block(value, i, &stop); + if (stop) break; + } + } else if (_count > 0) { + int32_t *end = _values; + int32_t *scan = end + (_count - 1); + for (NSUInteger i = (_count - 1); scan >= end; --i, --scan) { + int32_t value = *scan; + if (!func(value)) { + value = kGPBUnrecognizedEnumeratorValue; + } + block(value, i, &stop); + if (stop) break; + } + } +} + +//%PDDM-EXPAND ARRAY_MUTABLE_CORE(Enum, int32_t, Raw, %d) +// This block of code is generated, do not edit it directly. + +- (void)internalResizeToCapacity:(NSUInteger)newCapacity { + _values = reallocf(_values, newCapacity * sizeof(int32_t)); + if (_values == NULL) { + _capacity = 0; + _count = 0; + [NSException raise:NSMallocException + format:@"Failed to allocate %lu bytes", + (unsigned long)(newCapacity * sizeof(int32_t))]; + } + _capacity = newCapacity; +} + +- (void)addRawValue:(int32_t)value { + [self addRawValues:&value count:1]; +} + +- (void)addRawValues:(const int32_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(int32_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertRawValue:(int32_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(int32_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + _values[index] = value; +} + +- (void)addRawValuesFromArray:(GPBEnumArray *)array { + [self addRawValues:array->_values count:array->_count]; +} + +- (void)removeValueAtIndex:(NSUInteger)index { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + NSUInteger newCount = _count - 1; + if (index != newCount) { + memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int32_t)); + } + _count = newCount; + if ((newCount + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } +} + +- (void)removeAll { + _count = 0; + if ((0 + (2 * kChunkSize)) < _capacity) { + [self internalResizeToCapacity:CapacityFromCount(0)]; + } +} + +- (void)exchangeValueAtIndex:(NSUInteger)idx1 + withValueAtIndex:(NSUInteger)idx2 { + if (idx1 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx1, (unsigned long)_count]; + } + if (idx2 >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)idx2, (unsigned long)_count]; + } + int32_t temp = _values[idx1]; + _values[idx1] = _values[idx2]; + _values[idx2] = temp; +} + +//%PDDM-EXPAND MUTATION_METHODS(Enum, int32_t, , EnumValidationList, EnumValidationOne) +// This block of code is generated, do not edit it directly. + +- (void)addValue:(int32_t)value { + [self addValues:&value count:1]; +} + +- (void)addValues:(const int32_t [])values count:(NSUInteger)count { + if (values == NULL || count == 0) return; + GPBEnumValidationFunc func = _validationFunc; + for (NSUInteger i = 0; i < count; ++i) { + if (!func(values[i])) { + [NSException raise:NSInvalidArgumentException + format:@"%@: Attempt to set an unknown enum value (%d)", + [self class], values[i]]; + } + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + count; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + memcpy(&_values[initialCount], values, count * sizeof(int32_t)); + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index { + if (index >= _count + 1) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count + 1]; + } + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"%@: Attempt to set an unknown enum value (%d)", + [self class], value]; + } + NSUInteger initialCount = _count; + NSUInteger newCount = initialCount + 1; + if (newCount > _capacity) { + [self internalResizeToCapacity:CapacityFromCount(newCount)]; + } + _count = newCount; + if (index != initialCount) { + memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); + } + _values[index] = value; + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value { + if (index >= _count) { + [NSException raise:NSRangeException + format:@"Index (%lu) beyond bounds (%lu)", + (unsigned long)index, (unsigned long)_count]; + } + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"%@: Attempt to set an unknown enum value (%d)", + [self class], value]; + } + _values[index] = value; +} +//%PDDM-EXPAND-END (2 expansions) + +//%PDDM-DEFINE MUTATION_HOOK_EnumValidationList() +//% GPBEnumValidationFunc func = _validationFunc; +//% for (NSUInteger i = 0; i < count; ++i) { +//% if (!func(values[i])) { +//% [NSException raise:NSInvalidArgumentException +//% format:@"%@: Attempt to set an unknown enum value (%d)", +//% [self class], values[i]]; +//% } +//% } +//% +//%PDDM-DEFINE MUTATION_HOOK_EnumValidationOne() +//% if (!_validationFunc(value)) { +//% [NSException raise:NSInvalidArgumentException +//% format:@"%@: Attempt to set an unknown enum value (%d)", +//% [self class], value]; +//% } +//% + +@end + +#pragma mark - NSArray Subclass + +@implementation GPBAutocreatedArray { + NSMutableArray *_array; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_array release]; + [super dealloc]; +} + +#pragma mark Required NSArray overrides + +- (NSUInteger)count { + return [_array count]; +} + +- (id)objectAtIndex:(NSUInteger)idx { + return [_array objectAtIndex:idx]; +} + +#pragma mark Required NSMutableArray overrides + +// Only need to call GPBAutocreatedArrayModified() when adding things since +// we only autocreate empty arrays. + +- (void)insertObject:(id)anObject atIndex:(NSUInteger)idx { + if (_array == nil) { + _array = [[NSMutableArray alloc] init]; + } + [_array insertObject:anObject atIndex:idx]; + + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)removeObject:(id)anObject { + [_array removeObject:anObject]; +} + +- (void)removeObjectAtIndex:(NSUInteger)idx { + [_array removeObjectAtIndex:idx]; +} + +- (void)addObject:(id)anObject { + if (_array == nil) { + _array = [[NSMutableArray alloc] init]; + } + [_array addObject:anObject]; + + if (_autocreator) { + GPBAutocreatedArrayModified(_autocreator, self); + } +} + +- (void)removeLastObject { + [_array removeLastObject]; +} + +- (void)replaceObjectAtIndex:(NSUInteger)idx withObject:(id)anObject { + [_array replaceObjectAtIndex:idx withObject:anObject]; +} + +#pragma mark Extra things hooked + +- (id)copyWithZone:(NSZone *)zone { + if (_array == nil) { + return [[NSMutableArray allocWithZone:zone] init]; + } + return [_array copyWithZone:zone]; +} + +- (id)mutableCopyWithZone:(NSZone *)zone { + if (_array == nil) { + return [[NSMutableArray allocWithZone:zone] init]; + } + return [_array mutableCopyWithZone:zone]; +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state + objects:(id __unsafe_unretained [])buffer + count:(NSUInteger)len { + return [_array countByEnumeratingWithState:state objects:buffer count:len]; +} + +- (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { + [_array enumerateObjectsUsingBlock:block]; +} + +- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { + [_array enumerateObjectsWithOptions:opts usingBlock:block]; +} + +@end + +#pragma clang diagnostic pop diff --git a/My Mind/Pods/Protobuf/objectivec/GPBArray_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBArray_PackagePrivate.h new file mode 100644 index 0000000..35a4538 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBArray_PackagePrivate.h @@ -0,0 +1,130 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBArray.h" + +@class GPBMessage; + +//%PDDM-DEFINE DECLARE_ARRAY_EXTRAS() +//%ARRAY_INTERFACE_EXTRAS(Int32, int32_t) +//%ARRAY_INTERFACE_EXTRAS(UInt32, uint32_t) +//%ARRAY_INTERFACE_EXTRAS(Int64, int64_t) +//%ARRAY_INTERFACE_EXTRAS(UInt64, uint64_t) +//%ARRAY_INTERFACE_EXTRAS(Float, float) +//%ARRAY_INTERFACE_EXTRAS(Double, double) +//%ARRAY_INTERFACE_EXTRAS(Bool, BOOL) +//%ARRAY_INTERFACE_EXTRAS(Enum, int32_t) + +//%PDDM-DEFINE ARRAY_INTERFACE_EXTRAS(NAME, TYPE) +//%#pragma mark - NAME +//% +//%@interface GPB##NAME##Array () { +//% @package +//% GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +//%} +//%@end +//% + +//%PDDM-EXPAND DECLARE_ARRAY_EXTRAS() +// This block of code is generated, do not edit it directly. + +#pragma mark - Int32 + +@interface GPBInt32Array () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - UInt32 + +@interface GPBUInt32Array () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Int64 + +@interface GPBInt64Array () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - UInt64 + +@interface GPBUInt64Array () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Float + +@interface GPBFloatArray () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Double + +@interface GPBDoubleArray () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Bool + +@interface GPBBoolArray () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Enum + +@interface GPBEnumArray () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +//%PDDM-EXPAND-END DECLARE_ARRAY_EXTRAS() + +#pragma mark - NSArray Subclass + +@interface GPBAutocreatedArray : NSMutableArray { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBBootstrap.h b/My Mind/Pods/Protobuf/objectivec/GPBBootstrap.h new file mode 100644 index 0000000..ed53ae7 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBBootstrap.h @@ -0,0 +1,123 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +/** + * The Objective C runtime has complete enough info that most protos don’t end + * up using this, so leaving it on is no cost or very little cost. If you + * happen to see it causing bloat, this is the way to disable it. If you do + * need to disable it, try only disabling it for Release builds as having + * full TextFormat can be useful for debugging. + **/ +#ifndef GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS +#define GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS 0 +#endif + +// Used in the generated code to give sizes to enums. int32_t was chosen based +// on the fact that Protocol Buffers enums are limited to this range. +#if !__has_feature(objc_fixed_enum) + #error All supported Xcode versions should support objc_fixed_enum. +#endif + +// If the headers are imported into Objective-C++, we can run into an issue +// where the defintion of NS_ENUM (really CF_ENUM) changes based on the C++ +// standard that is in effect. If it isn't C++11 or higher, the definition +// doesn't allow us to forward declare. We work around this one case by +// providing a local definition. The default case has to use NS_ENUM for the +// magic that is Swift bridging of enums. +#if (defined(__cplusplus) && __cplusplus && __cplusplus < 201103L) + #define GPB_ENUM(X) enum X : int32_t X; enum X : int32_t +#else + #define GPB_ENUM(X) NS_ENUM(int32_t, X) +#endif + +/** + * GPB_ENUM_FWD_DECLARE is used for forward declaring enums, for example: + * + * ``` + * GPB_ENUM_FWD_DECLARE(Foo_Enum) + * + * @interface BarClass : NSObject + * @property (nonatomic) enum Foo_Enum value; + * - (void)bazMethod:(enum Foo_Enum):value; + * @end + * ``` + **/ +#define GPB_ENUM_FWD_DECLARE(X) enum X : int32_t + +/** + * Based upon CF_INLINE. Forces inlining in non DEBUG builds. + **/ +#if !defined(DEBUG) +#define GPB_INLINE static __inline__ __attribute__((always_inline)) +#else +#define GPB_INLINE static __inline__ +#endif + +/** + * For use in public headers that might need to deal with ARC. + **/ +#ifndef GPB_UNSAFE_UNRETAINED +#if __has_feature(objc_arc) +#define GPB_UNSAFE_UNRETAINED __unsafe_unretained +#else +#define GPB_UNSAFE_UNRETAINED +#endif +#endif + +// If property name starts with init we need to annotate it to get past ARC. +// http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 +// +// Meant to be used internally by generated code. +#define GPB_METHOD_FAMILY_NONE __attribute__((objc_method_family(none))) + +// ---------------------------------------------------------------------------- +// These version numbers are all internal to the ObjC Protobuf runtime; they +// are used to ensure compatibility between the generated sources and the +// headers being compiled against and/or the version of sources being run +// against. +// +// They are all #defines so the values are captured into every .o file they +// are used in and to allow comparisons in the preprocessor. + +// Current library runtime version. +// - Gets bumped when the runtime makes changes to the interfaces between the +// generated code and runtime (things added/removed, etc). +#define GOOGLE_PROTOBUF_OBJC_VERSION 30002 + +// Minimum runtime version supported for compiling/running against. +// - Gets changed when support for the older generated code is dropped. +#define GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION 30001 + + +// This is a legacy constant now frozen in time for old generated code. If +// GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION ever gets moved above 30001 then +// this should also change to break code compiled with an old runtime that +// can't be supported any more. +#define GOOGLE_PROTOBUF_OBJC_GEN_VERSION 30001 diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.h b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.h new file mode 100644 index 0000000..fbe5009 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.h @@ -0,0 +1,253 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +@class GPBMessage; +@class GPBExtensionRegistry; + +NS_ASSUME_NONNULL_BEGIN + +CF_EXTERN_C_BEGIN + +/** + * @c GPBCodedInputStream exception name. Exceptions raised from + * @c GPBCodedInputStream contain an underlying error in the userInfo dictionary + * under the GPBCodedInputStreamUnderlyingErrorKey key. + **/ +extern NSString *const GPBCodedInputStreamException; + +/** The key under which the underlying NSError from the exception is stored. */ +extern NSString *const GPBCodedInputStreamUnderlyingErrorKey; + +/** NSError domain used for @c GPBCodedInputStream errors. */ +extern NSString *const GPBCodedInputStreamErrorDomain; + +/** + * Error code for NSError with @c GPBCodedInputStreamErrorDomain. + **/ +typedef NS_ENUM(NSInteger, GPBCodedInputStreamErrorCode) { + /** The size does not fit in the remaining bytes to be read. */ + GPBCodedInputStreamErrorInvalidSize = -100, + /** Attempted to read beyond the subsection limit. */ + GPBCodedInputStreamErrorSubsectionLimitReached = -101, + /** The requested subsection limit is invalid. */ + GPBCodedInputStreamErrorInvalidSubsectionLimit = -102, + /** Invalid tag read. */ + GPBCodedInputStreamErrorInvalidTag = -103, + /** Invalid UTF-8 character in a string. */ + GPBCodedInputStreamErrorInvalidUTF8 = -104, + /** Invalid VarInt read. */ + GPBCodedInputStreamErrorInvalidVarInt = -105, + /** The maximum recursion depth of messages was exceeded. */ + GPBCodedInputStreamErrorRecursionDepthExceeded = -106, +}; + +CF_EXTERN_C_END + +/** + * Reads and decodes protocol message fields. + * + * The common uses of protocol buffers shouldn't need to use this class. + * @c GPBMessage's provide a @c +parseFromData:error: and + * @c +parseFromData:extensionRegistry:error: method that will decode a + * message for you. + * + * @note Subclassing of @c GPBCodedInputStream is NOT supported. + **/ +@interface GPBCodedInputStream : NSObject + +/** + * Creates a new stream wrapping some data. + * + * @param data The data to wrap inside the stream. + * + * @return A newly instanced GPBCodedInputStream. + **/ ++ (instancetype)streamWithData:(NSData *)data; + +/** + * Initializes a stream wrapping some data. + * + * @param data The data to wrap inside the stream. + * + * @return A newly initialized GPBCodedInputStream. + **/ +- (instancetype)initWithData:(NSData *)data; + +/** + * Attempts to read a field tag, returning zero if we have reached EOF. + * Protocol message parsers use this to read tags, since a protocol message + * may legally end wherever a tag occurs, and zero is not a valid tag number. + * + * @return The field tag, or zero if EOF was reached. + **/ +- (int32_t)readTag; + +/** + * @return A double read from the stream. + **/ +- (double)readDouble; +/** + * @return A float read from the stream. + **/ +- (float)readFloat; +/** + * @return A uint64 read from the stream. + **/ +- (uint64_t)readUInt64; +/** + * @return A uint32 read from the stream. + **/ +- (uint32_t)readUInt32; +/** + * @return An int64 read from the stream. + **/ +- (int64_t)readInt64; +/** + * @return An int32 read from the stream. + **/ +- (int32_t)readInt32; +/** + * @return A fixed64 read from the stream. + **/ +- (uint64_t)readFixed64; +/** + * @return A fixed32 read from the stream. + **/ +- (uint32_t)readFixed32; +/** + * @return An enum read from the stream. + **/ +- (int32_t)readEnum; +/** + * @return A sfixed32 read from the stream. + **/ +- (int32_t)readSFixed32; +/** + * @return A fixed64 read from the stream. + **/ +- (int64_t)readSFixed64; +/** + * @return A sint32 read from the stream. + **/ +- (int32_t)readSInt32; +/** + * @return A sint64 read from the stream. + **/ +- (int64_t)readSInt64; +/** + * @return A boolean read from the stream. + **/ +- (BOOL)readBool; +/** + * @return A string read from the stream. + **/ +- (NSString *)readString; +/** + * @return Data read from the stream. + **/ +- (NSData *)readBytes; + +/** + * Read an embedded message field value from the stream. + * + * @param message The message to set fields on as they are read. + * @param extensionRegistry An optional extension registry to use to lookup + * extensions for message. + **/ +- (void)readMessage:(GPBMessage *)message + extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; + +/** + * Reads and discards a single field, given its tag value. + * + * @param tag The tag number of the field to skip. + * + * @return NO if the tag is an endgroup tag (in which case nothing is skipped), + * YES in all other cases. + **/ +- (BOOL)skipField:(int32_t)tag; + +/** + * Reads and discards an entire message. This will read either until EOF or + * until an endgroup tag, whichever comes first. + **/ +- (void)skipMessage; + +/** + * Check to see if the logical end of the stream has been reached. + * + * @note This can return NO when there is no more data, but the current parsing + * expected more data. + * + * @return YES if the logical end of the stream has been reached, NO otherwise. + **/ +- (BOOL)isAtEnd; + +/** + * @return The offset into the stream. + **/ +- (size_t)position; + +/** + * Moves the limit to the given byte offset starting at the current location. + * + * @exception GPBCodedInputStreamException If the requested bytes exceeed the + * current limit. + * + * @param byteLimit The number of bytes to move the limit, offset to the current + * location. + * + * @return The limit offset before moving the new limit. + */ +- (size_t)pushLimit:(size_t)byteLimit; + +/** + * Moves the limit back to the offset as it was before calling pushLimit:. + * + * @param oldLimit The number of bytes to move the current limit. Usually this + * is the value returned by the pushLimit: method. + */ +- (void)popLimit:(size_t)oldLimit; + +/** + * Verifies that the last call to -readTag returned the given tag value. This + * is used to verify that a nested group ended with the correct end tag. + * + * @exception NSParseErrorException If the value does not match the last tag. + * + * @param expected The tag that was expected. + **/ +- (void)checkLastTagWas:(int32_t)expected; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.m b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.m new file mode 100644 index 0000000..dd05ddb --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream.m @@ -0,0 +1,505 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBCodedInputStream_PackagePrivate.h" + +#import "GPBDictionary_PackagePrivate.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" +#import "GPBWireFormat.h" + +NSString *const GPBCodedInputStreamException = + GPBNSStringifySymbol(GPBCodedInputStreamException); + +NSString *const GPBCodedInputStreamUnderlyingErrorKey = + GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey); + +NSString *const GPBCodedInputStreamErrorDomain = + GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain); + +// Matching: +// https://github.com/google/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62 +// private static final int DEFAULT_RECURSION_LIMIT = 100; +// https://github.com/google/protobuf/blob/master/src/google/protobuf/io/coded_stream.cc#L86 +// int CodedInputStream::default_recursion_limit_ = 100; +static const NSUInteger kDefaultRecursionLimit = 100; + +static void RaiseException(NSInteger code, NSString *reason) { + NSDictionary *errorInfo = nil; + if ([reason length]) { + errorInfo = @{ GPBErrorReasonKey: reason }; + } + NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain + code:code + userInfo:errorInfo]; + + NSDictionary *exceptionInfo = + @{ GPBCodedInputStreamUnderlyingErrorKey: error }; + [[NSException exceptionWithName:GPBCodedInputStreamException + reason:reason + userInfo:exceptionInfo] raise]; +} + +static void CheckRecursionLimit(GPBCodedInputStreamState *state) { + if (state->recursionDepth >= kDefaultRecursionLimit) { + RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil); + } +} + +static void CheckSize(GPBCodedInputStreamState *state, size_t size) { + size_t newSize = state->bufferPos + size; + if (newSize > state->bufferSize) { + RaiseException(GPBCodedInputStreamErrorInvalidSize, nil); + } + if (newSize > state->currentLimit) { + // Fast forward to end of currentLimit; + state->bufferPos = state->currentLimit; + RaiseException(GPBCodedInputStreamErrorSubsectionLimitReached, nil); + } +} + +static int8_t ReadRawByte(GPBCodedInputStreamState *state) { + CheckSize(state, sizeof(int8_t)); + return ((int8_t *)state->bytes)[state->bufferPos++]; +} + +static int32_t ReadRawLittleEndian32(GPBCodedInputStreamState *state) { + CheckSize(state, sizeof(int32_t)); + int32_t value = OSReadLittleInt32(state->bytes, state->bufferPos); + state->bufferPos += sizeof(int32_t); + return value; +} + +static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) { + CheckSize(state, sizeof(int64_t)); + int64_t value = OSReadLittleInt64(state->bytes, state->bufferPos); + state->bufferPos += sizeof(int64_t); + return value; +} + +static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) { + int32_t shift = 0; + int64_t result = 0; + while (shift < 64) { + int8_t b = ReadRawByte(state); + result |= (int64_t)((uint64_t)(b & 0x7F) << shift); + if ((b & 0x80) == 0) { + return result; + } + shift += 7; + } + RaiseException(GPBCodedInputStreamErrorInvalidVarInt, @"Invalid VarInt64"); + return 0; +} + +static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) { + return (int32_t)ReadRawVarint64(state); +} + +static void SkipRawData(GPBCodedInputStreamState *state, size_t size) { + CheckSize(state, size); + state->bufferPos += size; +} + +double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state) { + int64_t value = ReadRawLittleEndian64(state); + return GPBConvertInt64ToDouble(value); +} + +float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state) { + int32_t value = ReadRawLittleEndian32(state); + return GPBConvertInt32ToFloat(value); +} + +uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state) { + uint64_t value = ReadRawVarint64(state); + return value; +} + +uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state) { + uint32_t value = ReadRawVarint32(state); + return value; +} + +int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state) { + int64_t value = ReadRawVarint64(state); + return value; +} + +int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state) { + int32_t value = ReadRawVarint32(state); + return value; +} + +uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state) { + uint64_t value = ReadRawLittleEndian64(state); + return value; +} + +uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state) { + uint32_t value = ReadRawLittleEndian32(state); + return value; +} + +int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state) { + int32_t value = ReadRawVarint32(state); + return value; +} + +int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state) { + int32_t value = ReadRawLittleEndian32(state); + return value; +} + +int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state) { + int64_t value = ReadRawLittleEndian64(state); + return value; +} + +int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state) { + int32_t value = GPBDecodeZigZag32(ReadRawVarint32(state)); + return value; +} + +int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state) { + int64_t value = GPBDecodeZigZag64(ReadRawVarint64(state)); + return value; +} + +BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state) { + return ReadRawVarint32(state) != 0; +} + +int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) { + if (GPBCodedInputStreamIsAtEnd(state)) { + state->lastTag = 0; + return 0; + } + + state->lastTag = ReadRawVarint32(state); + // Tags have to include a valid wireformat. + if (!GPBWireFormatIsValidTag(state->lastTag)) { + RaiseException(GPBCodedInputStreamErrorInvalidTag, + @"Invalid wireformat in tag."); + } + // Zero is not a valid field number. + if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) { + RaiseException(GPBCodedInputStreamErrorInvalidTag, + @"A zero field number on the wire is invalid."); + } + return state->lastTag; +} + +NSString *GPBCodedInputStreamReadRetainedString( + GPBCodedInputStreamState *state) { + int32_t size = ReadRawVarint32(state); + NSString *result; + if (size == 0) { + result = @""; + } else { + CheckSize(state, size); + result = [[NSString alloc] initWithBytes:&state->bytes[state->bufferPos] + length:size + encoding:NSUTF8StringEncoding]; + state->bufferPos += size; + if (!result) { +#ifdef DEBUG + // https://developers.google.com/protocol-buffers/docs/proto#scalar + NSLog(@"UTF-8 failure, is some field type 'string' when it should be " + @"'bytes'?"); +#endif + RaiseException(GPBCodedInputStreamErrorInvalidUTF8, nil); + } + } + return result; +} + +NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) { + int32_t size = ReadRawVarint32(state); + if (size < 0) return nil; + CheckSize(state, size); + NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos + length:size]; + state->bufferPos += size; + return result; +} + +NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( + GPBCodedInputStreamState *state) { + int32_t size = ReadRawVarint32(state); + if (size < 0) return nil; + CheckSize(state, size); + // Cast is safe because freeWhenDone is NO. + NSData *result = [[NSData alloc] + initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos) + length:size + freeWhenDone:NO]; + state->bufferPos += size; + return result; +} + +size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, + size_t byteLimit) { + byteLimit += state->bufferPos; + size_t oldLimit = state->currentLimit; + if (byteLimit > oldLimit) { + RaiseException(GPBCodedInputStreamErrorInvalidSubsectionLimit, nil); + } + state->currentLimit = byteLimit; + return oldLimit; +} + +void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, + size_t oldLimit) { + state->currentLimit = oldLimit; +} + +size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) { + return state->currentLimit - state->bufferPos; +} + +BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) { + return (state->bufferPos == state->bufferSize) || + (state->bufferPos == state->currentLimit); +} + +void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, + int32_t value) { + if (state->lastTag != value) { + RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read"); + } +} + +@implementation GPBCodedInputStream + ++ (instancetype)streamWithData:(NSData *)data { + return [[[self alloc] initWithData:data] autorelease]; +} + +- (instancetype)initWithData:(NSData *)data { + if ((self = [super init])) { +#ifdef DEBUG + NSCAssert([self class] == [GPBCodedInputStream class], + @"Subclassing of GPBCodedInputStream is not allowed."); +#endif + buffer_ = [data retain]; + state_.bytes = (const uint8_t *)[data bytes]; + state_.bufferSize = [data length]; + state_.currentLimit = state_.bufferSize; + } + return self; +} + +- (void)dealloc { + [buffer_ release]; + [super dealloc]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (int32_t)readTag { + return GPBCodedInputStreamReadTag(&state_); +} + +- (void)checkLastTagWas:(int32_t)value { + GPBCodedInputStreamCheckLastTagWas(&state_, value); +} + +- (BOOL)skipField:(int32_t)tag { + NSAssert(GPBWireFormatIsValidTag(tag), @"Invalid tag"); + switch (GPBWireFormatGetTagWireType(tag)) { + case GPBWireFormatVarint: + GPBCodedInputStreamReadInt32(&state_); + return YES; + case GPBWireFormatFixed64: + SkipRawData(&state_, sizeof(int64_t)); + return YES; + case GPBWireFormatLengthDelimited: + SkipRawData(&state_, ReadRawVarint32(&state_)); + return YES; + case GPBWireFormatStartGroup: + [self skipMessage]; + GPBCodedInputStreamCheckLastTagWas( + &state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), + GPBWireFormatEndGroup)); + return YES; + case GPBWireFormatEndGroup: + return NO; + case GPBWireFormatFixed32: + SkipRawData(&state_, sizeof(int32_t)); + return YES; + } +} + +- (void)skipMessage { + while (YES) { + int32_t tag = GPBCodedInputStreamReadTag(&state_); + if (tag == 0 || ![self skipField:tag]) { + return; + } + } +} + +- (BOOL)isAtEnd { + return GPBCodedInputStreamIsAtEnd(&state_); +} + +- (size_t)position { + return state_.bufferPos; +} + +- (size_t)pushLimit:(size_t)byteLimit { + return GPBCodedInputStreamPushLimit(&state_, byteLimit); +} + +- (void)popLimit:(size_t)oldLimit { + GPBCodedInputStreamPopLimit(&state_, oldLimit); +} + +- (double)readDouble { + return GPBCodedInputStreamReadDouble(&state_); +} + +- (float)readFloat { + return GPBCodedInputStreamReadFloat(&state_); +} + +- (uint64_t)readUInt64 { + return GPBCodedInputStreamReadUInt64(&state_); +} + +- (int64_t)readInt64 { + return GPBCodedInputStreamReadInt64(&state_); +} + +- (int32_t)readInt32 { + return GPBCodedInputStreamReadInt32(&state_); +} + +- (uint64_t)readFixed64 { + return GPBCodedInputStreamReadFixed64(&state_); +} + +- (uint32_t)readFixed32 { + return GPBCodedInputStreamReadFixed32(&state_); +} + +- (BOOL)readBool { + return GPBCodedInputStreamReadBool(&state_); +} + +- (NSString *)readString { + return [GPBCodedInputStreamReadRetainedString(&state_) autorelease]; +} + +- (void)readGroup:(int32_t)fieldNumber + message:(GPBMessage *)message + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + CheckRecursionLimit(&state_); + ++state_.recursionDepth; + [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; + GPBCodedInputStreamCheckLastTagWas( + &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); + --state_.recursionDepth; +} + +- (void)readUnknownGroup:(int32_t)fieldNumber + message:(GPBUnknownFieldSet *)message { + CheckRecursionLimit(&state_); + ++state_.recursionDepth; + [message mergeFromCodedInputStream:self]; + GPBCodedInputStreamCheckLastTagWas( + &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); + --state_.recursionDepth; +} + +- (void)readMessage:(GPBMessage *)message + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + CheckRecursionLimit(&state_); + int32_t length = ReadRawVarint32(&state_); + size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); + ++state_.recursionDepth; + [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; + GPBCodedInputStreamCheckLastTagWas(&state_, 0); + --state_.recursionDepth; + GPBCodedInputStreamPopLimit(&state_, oldLimit); +} + +- (void)readMapEntry:(id)mapDictionary + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + field:(GPBFieldDescriptor *)field + parentMessage:(GPBMessage *)parentMessage { + CheckRecursionLimit(&state_); + int32_t length = ReadRawVarint32(&state_); + size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); + ++state_.recursionDepth; + GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, + parentMessage); + GPBCodedInputStreamCheckLastTagWas(&state_, 0); + --state_.recursionDepth; + GPBCodedInputStreamPopLimit(&state_, oldLimit); +} + +- (NSData *)readBytes { + return [GPBCodedInputStreamReadRetainedBytes(&state_) autorelease]; +} + +- (uint32_t)readUInt32 { + return GPBCodedInputStreamReadUInt32(&state_); +} + +- (int32_t)readEnum { + return GPBCodedInputStreamReadEnum(&state_); +} + +- (int32_t)readSFixed32 { + return GPBCodedInputStreamReadSFixed32(&state_); +} + +- (int64_t)readSFixed64 { + return GPBCodedInputStreamReadSFixed64(&state_); +} + +- (int32_t)readSInt32 { + return GPBCodedInputStreamReadSInt32(&state_); +} + +- (int64_t)readSInt64 { + return GPBCodedInputStreamReadSInt64(&state_); +} + +#pragma clang diagnostic pop + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream_PackagePrivate.h new file mode 100644 index 0000000..43ec6e7 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedInputStream_PackagePrivate.h @@ -0,0 +1,112 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +// This header is private to the ProtobolBuffers library and must NOT be +// included by any sources outside this library. The contents of this file are +// subject to change at any time without notice. + +#import "GPBCodedInputStream.h" + +@class GPBUnknownFieldSet; +@class GPBFieldDescriptor; + +typedef struct GPBCodedInputStreamState { + const uint8_t *bytes; + size_t bufferSize; + size_t bufferPos; + + // For parsing subsections of an input stream you can put a hard limit on + // how much should be read. Normally the limit is the end of the stream, + // but you can adjust it to anywhere, and if you hit it you will be at the + // end of the stream, until you adjust the limit. + size_t currentLimit; + int32_t lastTag; + NSUInteger recursionDepth; +} GPBCodedInputStreamState; + +@interface GPBCodedInputStream () { + @package + struct GPBCodedInputStreamState state_; + NSData *buffer_; +} + +// Group support is deprecated, so we hide this interface from users, but +// support for older data. +- (void)readGroup:(int32_t)fieldNumber + message:(GPBMessage *)message + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; + +// Reads a group field value from the stream and merges it into the given +// UnknownFieldSet. +- (void)readUnknownGroup:(int32_t)fieldNumber + message:(GPBUnknownFieldSet *)message; + +// Reads a map entry. +- (void)readMapEntry:(id)mapDictionary + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + field:(GPBFieldDescriptor *)field + parentMessage:(GPBMessage *)parentMessage; +@end + +CF_EXTERN_C_BEGIN + +int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state); + +double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state); +float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state); +uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state); +uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state); +int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state); +int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state); +uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state); +uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state); +int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state); +int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state); +int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state); +int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state); +int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state); +BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state); +NSString *GPBCodedInputStreamReadRetainedString(GPBCodedInputStreamState *state) + __attribute((ns_returns_retained)); +NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) + __attribute((ns_returns_retained)); +NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( + GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); + +size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, + size_t byteLimit); +void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, + size_t oldLimit); +size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state); +BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state); +void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, + int32_t value); + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.h b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.h new file mode 100644 index 0000000..23c404b --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.h @@ -0,0 +1,748 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBRuntimeTypes.h" +#import "GPBWireFormat.h" + +@class GPBBoolArray; +@class GPBDoubleArray; +@class GPBEnumArray; +@class GPBFloatArray; +@class GPBMessage; +@class GPBInt32Array; +@class GPBInt64Array; +@class GPBUInt32Array; +@class GPBUInt64Array; +@class GPBUnknownFieldSet; + +NS_ASSUME_NONNULL_BEGIN + +/** + * @c GPBCodedOutputStream exception names. + **/ +extern NSString *const GPBCodedOutputStreamException_OutOfSpace; +extern NSString *const GPBCodedOutputStreamException_WriteFailed; + +/** + * Writes out protocol message fields. + * + * The common uses of protocol buffers shouldn't need to use this class. + * GPBMessage's provide a -data method that will serialize the message for you. + * + * @note Any -write* api can raise the GPBCodedOutputStreamException_* + * exceptions. + * + * @note Subclassing of GPBCodedOutputStream is NOT supported. + **/ +@interface GPBCodedOutputStream : NSObject + +/** + * Creates a stream to fill in the given data. Data must be sized to fit or + * an error will be raised when out of space. + * + * @param data The data where the stream will be written to. + * + * @return A newly instanced GPBCodedOutputStream. + **/ ++ (instancetype)streamWithData:(NSMutableData *)data; + +/** + * Creates a stream to write into the given NSOutputStream. + * + * @param output The output stream where the stream will be written to. + * + * @return A newly instanced GPBCodedOutputStream. + **/ ++ (instancetype)streamWithOutputStream:(NSOutputStream *)output; + +/** + * Initializes a stream to fill in the given data. Data must be sized to fit + * or an error will be raised when out of space. + * + * @param data The data where the stream will be written to. + * + * @return A newly initialized GPBCodedOutputStream. + **/ +- (instancetype)initWithData:(NSMutableData *)data; + +/** + * Initializes a stream to write into the given @c NSOutputStream. + * + * @param output The output stream where the stream will be written to. + * + * @return A newly initialized GPBCodedOutputStream. + **/ +- (instancetype)initWithOutputStream:(NSOutputStream *)output; + +/** + * Flush any buffered data out. + **/ +- (void)flush; + +/** + * Write the raw byte out. + * + * @param value The value to write out. + **/ +- (void)writeRawByte:(uint8_t)value; + +/** + * Write the tag for the given field number and wire format. + * + * @param fieldNumber The field number. + * @param format The wire format the data for the field will be in. + **/ +- (void)writeTag:(uint32_t)fieldNumber format:(GPBWireFormat)format; + +/** + * Write a 32bit value out in little endian format. + * + * @param value The value to write out. + **/ +- (void)writeRawLittleEndian32:(int32_t)value; +/** + * Write a 64bit value out in little endian format. + * + * @param value The value to write out. + **/ +- (void)writeRawLittleEndian64:(int64_t)value; + +/** + * Write a 32bit value out in varint format. + * + * @param value The value to write out. + **/ +- (void)writeRawVarint32:(int32_t)value; +/** + * Write a 64bit value out in varint format. + * + * @param value The value to write out. + **/ +- (void)writeRawVarint64:(int64_t)value; + +/** + * Write a size_t out as a 32bit varint value. + * + * @note This will truncate 64 bit values to 32. + * + * @param value The value to write out. + **/ +- (void)writeRawVarintSizeTAs32:(size_t)value; + +/** + * Writes the contents of an NSData out. + * + * @param data The data to write out. + **/ +- (void)writeRawData:(NSData *)data; +/** + * Writes out the given data. + * + * @param data The data blob to write out. + * @param offset The offset into the blob to start writing out. + * @param length The number of bytes from the blob to write out. + **/ +- (void)writeRawPtr:(const void *)data + offset:(size_t)offset + length:(size_t)length; + +//%PDDM-EXPAND _WRITE_DECLS() +// This block of code is generated, do not edit it directly. + +/** + * Write a double for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeDouble:(int32_t)fieldNumber value:(double)value; +/** + * Write a packed array of double for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeDoubleArray:(int32_t)fieldNumber + values:(GPBDoubleArray *)values + tag:(uint32_t)tag; +/** + * Write a double without any tag. + * + * @param value The value to write out. + **/ +- (void)writeDoubleNoTag:(double)value; + +/** + * Write a float for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeFloat:(int32_t)fieldNumber value:(float)value; +/** + * Write a packed array of float for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeFloatArray:(int32_t)fieldNumber + values:(GPBFloatArray *)values + tag:(uint32_t)tag; +/** + * Write a float without any tag. + * + * @param value The value to write out. + **/ +- (void)writeFloatNoTag:(float)value; + +/** + * Write a uint64_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeUInt64:(int32_t)fieldNumber value:(uint64_t)value; +/** + * Write a packed array of uint64_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeUInt64Array:(int32_t)fieldNumber + values:(GPBUInt64Array *)values + tag:(uint32_t)tag; +/** + * Write a uint64_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeUInt64NoTag:(uint64_t)value; + +/** + * Write a int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeInt64:(int32_t)fieldNumber value:(int64_t)value; +/** + * Write a packed array of int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeInt64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag; +/** + * Write a int64_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeInt64NoTag:(int64_t)value; + +/** + * Write a int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeInt32:(int32_t)fieldNumber value:(int32_t)value; +/** + * Write a packed array of int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeInt32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag; +/** + * Write a int32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeInt32NoTag:(int32_t)value; + +/** + * Write a uint32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeUInt32:(int32_t)fieldNumber value:(uint32_t)value; +/** + * Write a packed array of uint32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeUInt32Array:(int32_t)fieldNumber + values:(GPBUInt32Array *)values + tag:(uint32_t)tag; +/** + * Write a uint32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeUInt32NoTag:(uint32_t)value; + +/** + * Write a uint64_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeFixed64:(int32_t)fieldNumber value:(uint64_t)value; +/** + * Write a packed array of uint64_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeFixed64Array:(int32_t)fieldNumber + values:(GPBUInt64Array *)values + tag:(uint32_t)tag; +/** + * Write a uint64_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeFixed64NoTag:(uint64_t)value; + +/** + * Write a uint32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeFixed32:(int32_t)fieldNumber value:(uint32_t)value; +/** + * Write a packed array of uint32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeFixed32Array:(int32_t)fieldNumber + values:(GPBUInt32Array *)values + tag:(uint32_t)tag; +/** + * Write a uint32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeFixed32NoTag:(uint32_t)value; + +/** + * Write a int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeSInt32:(int32_t)fieldNumber value:(int32_t)value; +/** + * Write a packed array of int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeSInt32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag; +/** + * Write a int32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeSInt32NoTag:(int32_t)value; + +/** + * Write a int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeSInt64:(int32_t)fieldNumber value:(int64_t)value; +/** + * Write a packed array of int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeSInt64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag; +/** + * Write a int64_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeSInt64NoTag:(int64_t)value; + +/** + * Write a int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeSFixed64:(int32_t)fieldNumber value:(int64_t)value; +/** + * Write a packed array of int64_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeSFixed64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag; +/** + * Write a int64_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeSFixed64NoTag:(int64_t)value; + +/** + * Write a int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeSFixed32:(int32_t)fieldNumber value:(int32_t)value; +/** + * Write a packed array of int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeSFixed32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag; +/** + * Write a int32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeSFixed32NoTag:(int32_t)value; + +/** + * Write a BOOL for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeBool:(int32_t)fieldNumber value:(BOOL)value; +/** + * Write a packed array of BOOL for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeBoolArray:(int32_t)fieldNumber + values:(GPBBoolArray *)values + tag:(uint32_t)tag; +/** + * Write a BOOL without any tag. + * + * @param value The value to write out. + **/ +- (void)writeBoolNoTag:(BOOL)value; + +/** + * Write a int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeEnum:(int32_t)fieldNumber value:(int32_t)value; +/** + * Write a packed array of int32_t for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + * @param tag The tag assigned to the values. + **/ +- (void)writeEnumArray:(int32_t)fieldNumber + values:(GPBEnumArray *)values + tag:(uint32_t)tag; +/** + * Write a int32_t without any tag. + * + * @param value The value to write out. + **/ +- (void)writeEnumNoTag:(int32_t)value; + +/** + * Write a NSString for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeString:(int32_t)fieldNumber value:(NSString *)value; +/** + * Write an array of NSString for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + **/ +- (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values; +/** + * Write a NSString without any tag. + * + * @param value The value to write out. + **/ +- (void)writeStringNoTag:(NSString *)value; + +/** + * Write a GPBMessage for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeMessage:(int32_t)fieldNumber value:(GPBMessage *)value; +/** + * Write an array of GPBMessage for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + **/ +- (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values; +/** + * Write a GPBMessage without any tag. + * + * @param value The value to write out. + **/ +- (void)writeMessageNoTag:(GPBMessage *)value; + +/** + * Write a NSData for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeBytes:(int32_t)fieldNumber value:(NSData *)value; +/** + * Write an array of NSData for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + **/ +- (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values; +/** + * Write a NSData without any tag. + * + * @param value The value to write out. + **/ +- (void)writeBytesNoTag:(NSData *)value; + +/** + * Write a GPBMessage for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeGroup:(int32_t)fieldNumber + value:(GPBMessage *)value; +/** + * Write an array of GPBMessage for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + **/ +- (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values; +/** + * Write a GPBMessage without any tag (but does write the endGroup tag). + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeGroupNoTag:(int32_t)fieldNumber + value:(GPBMessage *)value; + +/** + * Write a GPBUnknownFieldSet for the given field number. + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeUnknownGroup:(int32_t)fieldNumber + value:(GPBUnknownFieldSet *)value; +/** + * Write an array of GPBUnknownFieldSet for the given field number. + * + * @param fieldNumber The field number assigned to the values. + * @param values The values to write out. + **/ +- (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values; +/** + * Write a GPBUnknownFieldSet without any tag (but does write the endGroup tag). + * + * @param fieldNumber The field number assigned to the value. + * @param value The value to write out. + **/ +- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber + value:(GPBUnknownFieldSet *)value; + +//%PDDM-EXPAND-END _WRITE_DECLS() + +/** +Write a MessageSet extension field to the stream. For historical reasons, +the wire format differs from normal fields. + +@param fieldNumber The extension field number to write out. +@param value The message from where to get the extension. +*/ +- (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value; + +/** +Write an unparsed MessageSet extension field to the stream. For historical +reasons, the wire format differs from normal fields. + +@param fieldNumber The extension field number to write out. +@param value The raw message from where to get the extension. +*/ +- (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value; + +@end + +NS_ASSUME_NONNULL_END + +// Write methods for types that can be in packed arrays. +//%PDDM-DEFINE _WRITE_PACKABLE_DECLS(NAME, ARRAY_TYPE, TYPE) +//%/** +//% * Write a TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the value. +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE)value; +//%/** +//% * Write a packed array of TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the values. +//% * @param values The values to write out. +//% * @param tag The tag assigned to the values. +//% **/ +//%- (void)write##NAME##Array:(int32_t)fieldNumber +//% NAME$S values:(GPB##ARRAY_TYPE##Array *)values +//% NAME$S tag:(uint32_t)tag; +//%/** +//% * Write a TYPE without any tag. +//% * +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME##NoTag:(TYPE)value; +//% +// Write methods for types that aren't in packed arrays. +//%PDDM-DEFINE _WRITE_UNPACKABLE_DECLS(NAME, TYPE) +//%/** +//% * Write a TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the value. +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE *)value; +//%/** +//% * Write an array of TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the values. +//% * @param values The values to write out. +//% **/ +//%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values; +//%/** +//% * Write a TYPE without any tag. +//% * +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME##NoTag:(TYPE *)value; +//% +// Special write methods for Groups. +//%PDDM-DEFINE _WRITE_GROUP_DECLS(NAME, TYPE) +//%/** +//% * Write a TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the value. +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME:(int32_t)fieldNumber +//% NAME$S value:(TYPE *)value; +//%/** +//% * Write an array of TYPE for the given field number. +//% * +//% * @param fieldNumber The field number assigned to the values. +//% * @param values The values to write out. +//% **/ +//%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values; +//%/** +//% * Write a TYPE without any tag (but does write the endGroup tag). +//% * +//% * @param fieldNumber The field number assigned to the value. +//% * @param value The value to write out. +//% **/ +//%- (void)write##NAME##NoTag:(int32_t)fieldNumber +//% NAME$S value:(TYPE *)value; +//% + +// One macro to hide it all up above. +//%PDDM-DEFINE _WRITE_DECLS() +//%_WRITE_PACKABLE_DECLS(Double, Double, double) +//%_WRITE_PACKABLE_DECLS(Float, Float, float) +//%_WRITE_PACKABLE_DECLS(UInt64, UInt64, uint64_t) +//%_WRITE_PACKABLE_DECLS(Int64, Int64, int64_t) +//%_WRITE_PACKABLE_DECLS(Int32, Int32, int32_t) +//%_WRITE_PACKABLE_DECLS(UInt32, UInt32, uint32_t) +//%_WRITE_PACKABLE_DECLS(Fixed64, UInt64, uint64_t) +//%_WRITE_PACKABLE_DECLS(Fixed32, UInt32, uint32_t) +//%_WRITE_PACKABLE_DECLS(SInt32, Int32, int32_t) +//%_WRITE_PACKABLE_DECLS(SInt64, Int64, int64_t) +//%_WRITE_PACKABLE_DECLS(SFixed64, Int64, int64_t) +//%_WRITE_PACKABLE_DECLS(SFixed32, Int32, int32_t) +//%_WRITE_PACKABLE_DECLS(Bool, Bool, BOOL) +//%_WRITE_PACKABLE_DECLS(Enum, Enum, int32_t) +//%_WRITE_UNPACKABLE_DECLS(String, NSString) +//%_WRITE_UNPACKABLE_DECLS(Message, GPBMessage) +//%_WRITE_UNPACKABLE_DECLS(Bytes, NSData) +//%_WRITE_GROUP_DECLS(Group, GPBMessage) +//%_WRITE_GROUP_DECLS(UnknownGroup, GPBUnknownFieldSet) diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.m b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.m new file mode 100644 index 0000000..b846c2f --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream.m @@ -0,0 +1,1210 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBCodedOutputStream_PackagePrivate.h" + +#import + +#import "GPBArray.h" +#import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" + +// These values are the existing values so as not to break any code that might +// have already been inspecting them when they weren't documented/exposed. +NSString *const GPBCodedOutputStreamException_OutOfSpace = @"OutOfSpace"; +NSString *const GPBCodedOutputStreamException_WriteFailed = @"WriteFailed"; + +// Structure for containing state of a GPBCodedInputStream. Brought out into +// a struct so that we can inline several common functions instead of dealing +// with overhead of ObjC dispatch. +typedef struct GPBOutputBufferState { + uint8_t *bytes; + size_t size; + size_t position; + NSOutputStream *output; +} GPBOutputBufferState; + +@implementation GPBCodedOutputStream { + GPBOutputBufferState state_; + NSMutableData *buffer_; +} + +static const int32_t LITTLE_ENDIAN_32_SIZE = sizeof(uint32_t); +static const int32_t LITTLE_ENDIAN_64_SIZE = sizeof(uint64_t); + +// Internal helper that writes the current buffer to the output. The +// buffer position is reset to its initial value when this returns. +static void GPBRefreshBuffer(GPBOutputBufferState *state) { + if (state->output == nil) { + // We're writing to a single buffer. + [NSException raise:GPBCodedOutputStreamException_OutOfSpace format:@""]; + } + if (state->position != 0) { + NSInteger written = + [state->output write:state->bytes maxLength:state->position]; + if (written != (NSInteger)state->position) { + [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""]; + } + state->position = 0; + } +} + +static void GPBWriteRawByte(GPBOutputBufferState *state, uint8_t value) { + if (state->position == state->size) { + GPBRefreshBuffer(state); + } + state->bytes[state->position++] = value; +} + +static void GPBWriteRawVarint32(GPBOutputBufferState *state, int32_t value) { + while (YES) { + if ((value & ~0x7F) == 0) { + uint8_t val = (uint8_t)value; + GPBWriteRawByte(state, val); + return; + } else { + GPBWriteRawByte(state, (value & 0x7F) | 0x80); + value = GPBLogicalRightShift32(value, 7); + } + } +} + +static void GPBWriteRawVarint64(GPBOutputBufferState *state, int64_t value) { + while (YES) { + if ((value & ~0x7FL) == 0) { + uint8_t val = (uint8_t)value; + GPBWriteRawByte(state, val); + return; + } else { + GPBWriteRawByte(state, ((int32_t)value & 0x7F) | 0x80); + value = GPBLogicalRightShift64(value, 7); + } + } +} + +static void GPBWriteInt32NoTag(GPBOutputBufferState *state, int32_t value) { + if (value >= 0) { + GPBWriteRawVarint32(state, value); + } else { + // Must sign-extend + GPBWriteRawVarint64(state, value); + } +} + +static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, + uint32_t value) { + GPBWriteTagWithFormat(state, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint32(state, value); +} + +static void GPBWriteTagWithFormat(GPBOutputBufferState *state, + uint32_t fieldNumber, GPBWireFormat format) { + GPBWriteRawVarint32(state, GPBWireFormatMakeTag(fieldNumber, format)); +} + +static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, + int32_t value) { + GPBWriteRawByte(state, (value)&0xFF); + GPBWriteRawByte(state, (value >> 8) & 0xFF); + GPBWriteRawByte(state, (value >> 16) & 0xFF); + GPBWriteRawByte(state, (value >> 24) & 0xFF); +} + +static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, + int64_t value) { + GPBWriteRawByte(state, (int32_t)(value)&0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 8) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 16) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 24) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 32) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 40) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 48) & 0xFF); + GPBWriteRawByte(state, (int32_t)(value >> 56) & 0xFF); +} + +- (void)dealloc { + [self flush]; + [state_.output close]; + [state_.output release]; + [buffer_ release]; + + [super dealloc]; +} + +- (instancetype)initWithOutputStream:(NSOutputStream *)output { + NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; + return [self initWithOutputStream:output data:data]; +} + +- (instancetype)initWithData:(NSMutableData *)data { + return [self initWithOutputStream:nil data:data]; +} + +// This initializer isn't exposed, but it is the designated initializer. +// Setting OutputStream and NSData is to control the buffering behavior/size +// of the work, but that is more obvious via the bufferSize: version. +- (instancetype)initWithOutputStream:(NSOutputStream *)output + data:(NSMutableData *)data { + if ((self = [super init])) { + buffer_ = [data retain]; + state_.bytes = [data mutableBytes]; + state_.size = [data length]; + state_.output = [output retain]; + [state_.output open]; + } + return self; +} + ++ (instancetype)streamWithOutputStream:(NSOutputStream *)output { + NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; + return [[[self alloc] initWithOutputStream:output + data:data] autorelease]; +} + ++ (instancetype)streamWithData:(NSMutableData *)data { + return [[[self alloc] initWithData:data] autorelease]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (void)writeDoubleNoTag:(double)value { + GPBWriteRawLittleEndian64(&state_, GPBConvertDoubleToInt64(value)); +} + +- (void)writeDouble:(int32_t)fieldNumber value:(double)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); + GPBWriteRawLittleEndian64(&state_, GPBConvertDoubleToInt64(value)); +} + +- (void)writeFloatNoTag:(float)value { + GPBWriteRawLittleEndian32(&state_, GPBConvertFloatToInt32(value)); +} + +- (void)writeFloat:(int32_t)fieldNumber value:(float)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); + GPBWriteRawLittleEndian32(&state_, GPBConvertFloatToInt32(value)); +} + +- (void)writeUInt64NoTag:(uint64_t)value { + GPBWriteRawVarint64(&state_, value); +} + +- (void)writeUInt64:(int32_t)fieldNumber value:(uint64_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint64(&state_, value); +} + +- (void)writeInt64NoTag:(int64_t)value { + GPBWriteRawVarint64(&state_, value); +} + +- (void)writeInt64:(int32_t)fieldNumber value:(int64_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint64(&state_, value); +} + +- (void)writeInt32NoTag:(int32_t)value { + GPBWriteInt32NoTag(&state_, value); +} + +- (void)writeInt32:(int32_t)fieldNumber value:(int32_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteInt32NoTag(&state_, value); +} + +- (void)writeFixed64NoTag:(uint64_t)value { + GPBWriteRawLittleEndian64(&state_, value); +} + +- (void)writeFixed64:(int32_t)fieldNumber value:(uint64_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); + GPBWriteRawLittleEndian64(&state_, value); +} + +- (void)writeFixed32NoTag:(uint32_t)value { + GPBWriteRawLittleEndian32(&state_, value); +} + +- (void)writeFixed32:(int32_t)fieldNumber value:(uint32_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); + GPBWriteRawLittleEndian32(&state_, value); +} + +- (void)writeBoolNoTag:(BOOL)value { + GPBWriteRawByte(&state_, (value ? 1 : 0)); +} + +- (void)writeBool:(int32_t)fieldNumber value:(BOOL)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawByte(&state_, (value ? 1 : 0)); +} + +- (void)writeStringNoTag:(const NSString *)value { + size_t length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + GPBWriteRawVarint32(&state_, (int32_t)length); + if (length == 0) { + return; + } + + const char *quickString = + CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8); + + // Fast path: Most strings are short, if the buffer already has space, + // add to it directly. + NSUInteger bufferBytesLeft = state_.size - state_.position; + if (bufferBytesLeft >= length) { + NSUInteger usedBufferLength = 0; + BOOL result; + if (quickString != NULL) { + memcpy(state_.bytes + state_.position, quickString, length); + usedBufferLength = length; + result = YES; + } else { + result = [value getBytes:state_.bytes + state_.position + maxLength:bufferBytesLeft + usedLength:&usedBufferLength + encoding:NSUTF8StringEncoding + options:(NSStringEncodingConversionOptions)0 + range:NSMakeRange(0, [value length]) + remainingRange:NULL]; + } + if (result) { + NSAssert2((usedBufferLength == length), + @"Our UTF8 calc was wrong? %tu vs %zd", usedBufferLength, + length); + state_.position += usedBufferLength; + return; + } + } else if (quickString != NULL) { + [self writeRawPtr:quickString offset:0 length:length]; + } else { + // Slow path: just get it as data and write it out. + NSData *utf8Data = [value dataUsingEncoding:NSUTF8StringEncoding]; + NSAssert2(([utf8Data length] == length), + @"Strings UTF8 length was wrong? %tu vs %zd", [utf8Data length], + length); + [self writeRawData:utf8Data]; + } +} + +- (void)writeString:(int32_t)fieldNumber value:(NSString *)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); + [self writeStringNoTag:value]; +} + +- (void)writeGroupNoTag:(int32_t)fieldNumber value:(GPBMessage *)value { + [value writeToCodedOutputStream:self]; + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); +} + +- (void)writeGroup:(int32_t)fieldNumber value:(GPBMessage *)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); + [self writeGroupNoTag:fieldNumber value:value]; +} + +- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber + value:(const GPBUnknownFieldSet *)value { + [value writeToCodedOutputStream:self]; + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); +} + +- (void)writeUnknownGroup:(int32_t)fieldNumber + value:(GPBUnknownFieldSet *)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); + [self writeUnknownGroupNoTag:fieldNumber value:value]; +} + +- (void)writeMessageNoTag:(GPBMessage *)value { + GPBWriteRawVarint32(&state_, (int32_t)[value serializedSize]); + [value writeToCodedOutputStream:self]; +} + +- (void)writeMessage:(int32_t)fieldNumber value:(GPBMessage *)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); + [self writeMessageNoTag:value]; +} + +- (void)writeBytesNoTag:(NSData *)value { + GPBWriteRawVarint32(&state_, (int32_t)[value length]); + [self writeRawData:value]; +} + +- (void)writeBytes:(int32_t)fieldNumber value:(NSData *)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); + [self writeBytesNoTag:value]; +} + +- (void)writeUInt32NoTag:(uint32_t)value { + GPBWriteRawVarint32(&state_, value); +} + +- (void)writeUInt32:(int32_t)fieldNumber value:(uint32_t)value { + GPBWriteUInt32(&state_, fieldNumber, value); +} + +- (void)writeEnumNoTag:(int32_t)value { + GPBWriteRawVarint32(&state_, value); +} + +- (void)writeEnum:(int32_t)fieldNumber value:(int32_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint32(&state_, value); +} + +- (void)writeSFixed32NoTag:(int32_t)value { + GPBWriteRawLittleEndian32(&state_, value); +} + +- (void)writeSFixed32:(int32_t)fieldNumber value:(int32_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); + GPBWriteRawLittleEndian32(&state_, value); +} + +- (void)writeSFixed64NoTag:(int64_t)value { + GPBWriteRawLittleEndian64(&state_, value); +} + +- (void)writeSFixed64:(int32_t)fieldNumber value:(int64_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); + GPBWriteRawLittleEndian64(&state_, value); +} + +- (void)writeSInt32NoTag:(int32_t)value { + GPBWriteRawVarint32(&state_, GPBEncodeZigZag32(value)); +} + +- (void)writeSInt32:(int32_t)fieldNumber value:(int32_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint32(&state_, GPBEncodeZigZag32(value)); +} + +- (void)writeSInt64NoTag:(int64_t)value { + GPBWriteRawVarint64(&state_, GPBEncodeZigZag64(value)); +} + +- (void)writeSInt64:(int32_t)fieldNumber value:(int64_t)value { + GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); + GPBWriteRawVarint64(&state_, GPBEncodeZigZag64(value)); +} + +//%PDDM-DEFINE WRITE_PACKABLE_DEFNS(NAME, ARRAY_TYPE, TYPE, ACCESSOR_NAME) +//%- (void)write##NAME##Array:(int32_t)fieldNumber +//% NAME$S values:(GPB##ARRAY_TYPE##Array *)values +//% NAME$S tag:(uint32_t)tag { +//% if (tag != 0) { +//% if (values.count == 0) return; +//% __block size_t dataSize = 0; +//% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//%#pragma unused(idx, stop) +//% dataSize += GPBCompute##NAME##SizeNoTag(value); +//% }]; +//% GPBWriteRawVarint32(&state_, tag); +//% GPBWriteRawVarint32(&state_, (int32_t)dataSize); +//% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//%#pragma unused(idx, stop) +//% [self write##NAME##NoTag:value]; +//% }]; +//% } else { +//% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//%#pragma unused(idx, stop) +//% [self write##NAME:fieldNumber value:value]; +//% }]; +//% } +//%} +//% +//%PDDM-DEFINE WRITE_UNPACKABLE_DEFNS(NAME, TYPE) +//%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray *)values { +//% for (TYPE *value in values) { +//% [self write##NAME:fieldNumber value:value]; +//% } +//%} +//% +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Double, Double, double, ) +// This block of code is generated, do not edit it directly. + +- (void)writeDoubleArray:(int32_t)fieldNumber + values:(GPBDoubleArray *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeDoubleSizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeDoubleNoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeDouble:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Float, Float, float, ) +// This block of code is generated, do not edit it directly. + +- (void)writeFloatArray:(int32_t)fieldNumber + values:(GPBFloatArray *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeFloatSizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFloatNoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFloat:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt64, UInt64, uint64_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeUInt64Array:(int32_t)fieldNumber + values:(GPBUInt64Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeUInt64SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeUInt64NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeUInt64:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int64, Int64, int64_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeInt64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeInt64SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeInt64NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeInt64:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int32, Int32, int32_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeInt32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeInt32SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeInt32NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeInt32:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt32, UInt32, uint32_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeUInt32Array:(int32_t)fieldNumber + values:(GPBUInt32Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeUInt32SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeUInt32NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeUInt32:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed64, UInt64, uint64_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeFixed64Array:(int32_t)fieldNumber + values:(GPBUInt64Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeFixed64SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFixed64NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFixed64:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed32, UInt32, uint32_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeFixed32Array:(int32_t)fieldNumber + values:(GPBUInt32Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeFixed32SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFixed32NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeFixed32:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt32, Int32, int32_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeSInt32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeSInt32SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSInt32NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSInt32:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt64, Int64, int64_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeSInt64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeSInt64SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSInt64NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSInt64:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed64, Int64, int64_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeSFixed64Array:(int32_t)fieldNumber + values:(GPBInt64Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeSFixed64SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSFixed64NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSFixed64:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed32, Int32, int32_t, ) +// This block of code is generated, do not edit it directly. + +- (void)writeSFixed32Array:(int32_t)fieldNumber + values:(GPBInt32Array *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeSFixed32SizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSFixed32NoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeSFixed32:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Bool, Bool, BOOL, ) +// This block of code is generated, do not edit it directly. + +- (void)writeBoolArray:(int32_t)fieldNumber + values:(GPBBoolArray *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeBoolSizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeBoolNoTag:value]; + }]; + } else { + [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeBool:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Enum, Enum, int32_t, Raw) +// This block of code is generated, do not edit it directly. + +- (void)writeEnumArray:(int32_t)fieldNumber + values:(GPBEnumArray *)values + tag:(uint32_t)tag { + if (tag != 0) { + if (values.count == 0) return; + __block size_t dataSize = 0; + [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + dataSize += GPBComputeEnumSizeNoTag(value); + }]; + GPBWriteRawVarint32(&state_, tag); + GPBWriteRawVarint32(&state_, (int32_t)dataSize); + [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeEnumNoTag:value]; + }]; + } else { + [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [self writeEnum:fieldNumber value:value]; + }]; + } +} + +//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(String, NSString) +// This block of code is generated, do not edit it directly. + +- (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values { + for (NSString *value in values) { + [self writeString:fieldNumber value:value]; + } +} + +//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Message, GPBMessage) +// This block of code is generated, do not edit it directly. + +- (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values { + for (GPBMessage *value in values) { + [self writeMessage:fieldNumber value:value]; + } +} + +//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Bytes, NSData) +// This block of code is generated, do not edit it directly. + +- (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values { + for (NSData *value in values) { + [self writeBytes:fieldNumber value:value]; + } +} + +//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Group, GPBMessage) +// This block of code is generated, do not edit it directly. + +- (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values { + for (GPBMessage *value in values) { + [self writeGroup:fieldNumber value:value]; + } +} + +//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(UnknownGroup, GPBUnknownFieldSet) +// This block of code is generated, do not edit it directly. + +- (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values { + for (GPBUnknownFieldSet *value in values) { + [self writeUnknownGroup:fieldNumber value:value]; + } +} + +//%PDDM-EXPAND-END (19 expansions) + +- (void)writeMessageSetExtension:(int32_t)fieldNumber + value:(GPBMessage *)value { + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, + GPBWireFormatStartGroup); + GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); + [self writeMessage:GPBWireFormatMessageSetMessage value:value]; + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, + GPBWireFormatEndGroup); +} + +- (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value { + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, + GPBWireFormatStartGroup); + GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); + [self writeBytes:GPBWireFormatMessageSetMessage value:value]; + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, + GPBWireFormatEndGroup); +} + +- (void)flush { + if (state_.output != nil) { + GPBRefreshBuffer(&state_); + } +} + +- (void)writeRawByte:(uint8_t)value { + GPBWriteRawByte(&state_, value); +} + +- (void)writeRawData:(const NSData *)data { + [self writeRawPtr:[data bytes] offset:0 length:[data length]]; +} + +- (void)writeRawPtr:(const void *)value + offset:(size_t)offset + length:(size_t)length { + if (value == nil || length == 0) { + return; + } + + NSUInteger bufferLength = state_.size; + NSUInteger bufferBytesLeft = bufferLength - state_.position; + if (bufferBytesLeft >= length) { + // We have room in the current buffer. + memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, length); + state_.position += length; + } else { + // Write extends past current buffer. Fill the rest of this buffer and + // flush. + size_t bytesWritten = bufferBytesLeft; + memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, + bytesWritten); + offset += bytesWritten; + length -= bytesWritten; + state_.position = bufferLength; + GPBRefreshBuffer(&state_); + bufferLength = state_.size; + + // Now deal with the rest. + // Since we have an output stream, this is our buffer + // and buffer offset == 0 + if (length <= bufferLength) { + // Fits in new buffer. + memcpy(state_.bytes, ((uint8_t *)value) + offset, length); + state_.position = length; + } else { + // Write is very big. Let's do it all at once. + NSInteger written = [state_.output write:((uint8_t *)value) + offset maxLength:length]; + if (written != (NSInteger)length) { + [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""]; + } + } + } +} + +- (void)writeTag:(uint32_t)fieldNumber format:(GPBWireFormat)format { + GPBWriteTagWithFormat(&state_, fieldNumber, format); +} + +- (void)writeRawVarint32:(int32_t)value { + GPBWriteRawVarint32(&state_, value); +} + +- (void)writeRawVarintSizeTAs32:(size_t)value { + // Note the truncation. + GPBWriteRawVarint32(&state_, (int32_t)value); +} + +- (void)writeRawVarint64:(int64_t)value { + GPBWriteRawVarint64(&state_, value); +} + +- (void)writeRawLittleEndian32:(int32_t)value { + GPBWriteRawLittleEndian32(&state_, value); +} + +- (void)writeRawLittleEndian64:(int64_t)value { + GPBWriteRawLittleEndian64(&state_, value); +} + +#pragma clang diagnostic pop + +@end + +size_t GPBComputeDoubleSizeNoTag(Float64 value) { +#pragma unused(value) + return LITTLE_ENDIAN_64_SIZE; +} + +size_t GPBComputeFloatSizeNoTag(Float32 value) { +#pragma unused(value) + return LITTLE_ENDIAN_32_SIZE; +} + +size_t GPBComputeUInt64SizeNoTag(uint64_t value) { + return GPBComputeRawVarint64Size(value); +} + +size_t GPBComputeInt64SizeNoTag(int64_t value) { + return GPBComputeRawVarint64Size(value); +} + +size_t GPBComputeInt32SizeNoTag(int32_t value) { + if (value >= 0) { + return GPBComputeRawVarint32Size(value); + } else { + // Must sign-extend. + return 10; + } +} + +size_t GPBComputeSizeTSizeAsInt32NoTag(size_t value) { + return GPBComputeInt32SizeNoTag((int32_t)value); +} + +size_t GPBComputeFixed64SizeNoTag(uint64_t value) { +#pragma unused(value) + return LITTLE_ENDIAN_64_SIZE; +} + +size_t GPBComputeFixed32SizeNoTag(uint32_t value) { +#pragma unused(value) + return LITTLE_ENDIAN_32_SIZE; +} + +size_t GPBComputeBoolSizeNoTag(BOOL value) { +#pragma unused(value) + return 1; +} + +size_t GPBComputeStringSizeNoTag(NSString *value) { + NSUInteger length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + return GPBComputeRawVarint32SizeForInteger(length) + length; +} + +size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { + return [value serializedSize]; +} + +size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { + return value.serializedSize; +} + +size_t GPBComputeMessageSizeNoTag(GPBMessage *value) { + size_t size = [value serializedSize]; + return GPBComputeRawVarint32SizeForInteger(size) + size; +} + +size_t GPBComputeBytesSizeNoTag(NSData *value) { + NSUInteger valueLength = [value length]; + return GPBComputeRawVarint32SizeForInteger(valueLength) + valueLength; +} + +size_t GPBComputeUInt32SizeNoTag(int32_t value) { + return GPBComputeRawVarint32Size(value); +} + +size_t GPBComputeEnumSizeNoTag(int32_t value) { + return GPBComputeRawVarint32Size(value); +} + +size_t GPBComputeSFixed32SizeNoTag(int32_t value) { +#pragma unused(value) + return LITTLE_ENDIAN_32_SIZE; +} + +size_t GPBComputeSFixed64SizeNoTag(int64_t value) { +#pragma unused(value) + return LITTLE_ENDIAN_64_SIZE; +} + +size_t GPBComputeSInt32SizeNoTag(int32_t value) { + return GPBComputeRawVarint32Size(GPBEncodeZigZag32(value)); +} + +size_t GPBComputeSInt64SizeNoTag(int64_t value) { + return GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); +} + +size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeDoubleSizeNoTag(value); +} + +size_t GPBComputeFloatSize(int32_t fieldNumber, float value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeFloatSizeNoTag(value); +} + +size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeUInt64SizeNoTag(value); +} + +size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeInt64SizeNoTag(value); +} + +size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeInt32SizeNoTag(value); +} + +size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeFixed64SizeNoTag(value); +} + +size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeFixed32SizeNoTag(value); +} + +size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeBoolSizeNoTag(value); +} + +size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeStringSizeNoTag(value); +} + +size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) { + return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeGroupSizeNoTag(value); +} + +size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, + GPBUnknownFieldSet *value) { + return GPBComputeTagSize(fieldNumber) * 2 + + GPBComputeUnknownGroupSizeNoTag(value); +} + +size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeMessageSizeNoTag(value); +} + +size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeBytesSizeNoTag(value); +} + +size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeUInt32SizeNoTag(value); +} + +size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeEnumSizeNoTag(value); +} + +size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeSFixed32SizeNoTag(value); +} + +size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeSFixed64SizeNoTag(value); +} + +size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) { + return GPBComputeTagSize(fieldNumber) + GPBComputeSInt32SizeNoTag(value); +} + +size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) { + return GPBComputeTagSize(fieldNumber) + + GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); +} + +size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, + GPBMessage *value) { + return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + + GPBComputeMessageSize(GPBWireFormatMessageSetMessage, value); +} + +size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, + NSData *value) { + return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + + GPBComputeBytesSize(GPBWireFormatMessageSetMessage, value); +} + +size_t GPBComputeTagSize(int32_t fieldNumber) { + return GPBComputeRawVarint32Size( + GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint)); +} + +size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) { + size_t result = GPBComputeTagSize(field_number); + if (dataType == GPBDataTypeGroup) { + // Groups have both a start and an end tag. + return result * 2; + } else { + return result; + } +} + +size_t GPBComputeRawVarint32Size(int32_t value) { + // value is treated as unsigned, so it won't be sign-extended if negative. + if ((value & (0xffffffff << 7)) == 0) return 1; + if ((value & (0xffffffff << 14)) == 0) return 2; + if ((value & (0xffffffff << 21)) == 0) return 3; + if ((value & (0xffffffff << 28)) == 0) return 4; + return 5; +} + +size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) { + // Note the truncation. + return GPBComputeRawVarint32Size((int32_t)value); +} + +size_t GPBComputeRawVarint64Size(int64_t value) { + if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; + if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; + if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; + if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; + if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; + if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; + if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; + if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; + if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; + return 10; +} diff --git a/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream_PackagePrivate.h new file mode 100644 index 0000000..2e7bb4c --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBCodedOutputStream_PackagePrivate.h @@ -0,0 +1,126 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBCodedOutputStream.h" + +NS_ASSUME_NONNULL_BEGIN + +CF_EXTERN_C_BEGIN + +size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) + __attribute__((const)); +size_t GPBComputeFloatSize(int32_t fieldNumber, float value) + __attribute__((const)); +size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) + __attribute__((const)); +size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) + __attribute__((const)); +size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) + __attribute__((const)); +size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) + __attribute__((const)); +size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) + __attribute__((const)); +size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) + __attribute__((const)); +size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) + __attribute__((const)); +size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) + __attribute__((const)); +size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, + GPBUnknownFieldSet *value) + __attribute__((const)); +size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) + __attribute__((const)); +size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) + __attribute__((const)); +size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) + __attribute__((const)); +size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) + __attribute__((const)); +size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) + __attribute__((const)); +size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) + __attribute__((const)); +size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) + __attribute__((const)); +size_t GPBComputeTagSize(int32_t fieldNumber) __attribute__((const)); +size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) + __attribute__((const)); + +size_t GPBComputeDoubleSizeNoTag(double value) __attribute__((const)); +size_t GPBComputeFloatSizeNoTag(float value) __attribute__((const)); +size_t GPBComputeUInt64SizeNoTag(uint64_t value) __attribute__((const)); +size_t GPBComputeInt64SizeNoTag(int64_t value) __attribute__((const)); +size_t GPBComputeInt32SizeNoTag(int32_t value) __attribute__((const)); +size_t GPBComputeFixed64SizeNoTag(uint64_t value) __attribute__((const)); +size_t GPBComputeFixed32SizeNoTag(uint32_t value) __attribute__((const)); +size_t GPBComputeBoolSizeNoTag(BOOL value) __attribute__((const)); +size_t GPBComputeStringSizeNoTag(NSString *value) __attribute__((const)); +size_t GPBComputeGroupSizeNoTag(GPBMessage *value) __attribute__((const)); +size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) + __attribute__((const)); +size_t GPBComputeMessageSizeNoTag(GPBMessage *value) __attribute__((const)); +size_t GPBComputeBytesSizeNoTag(NSData *value) __attribute__((const)); +size_t GPBComputeUInt32SizeNoTag(int32_t value) __attribute__((const)); +size_t GPBComputeEnumSizeNoTag(int32_t value) __attribute__((const)); +size_t GPBComputeSFixed32SizeNoTag(int32_t value) __attribute__((const)); +size_t GPBComputeSFixed64SizeNoTag(int64_t value) __attribute__((const)); +size_t GPBComputeSInt32SizeNoTag(int32_t value) __attribute__((const)); +size_t GPBComputeSInt64SizeNoTag(int64_t value) __attribute__((const)); + +// Note that this will calculate the size of 64 bit values truncated to 32. +size_t GPBComputeSizeTSizeAsInt32NoTag(size_t value) __attribute__((const)); + +size_t GPBComputeRawVarint32Size(int32_t value) __attribute__((const)); +size_t GPBComputeRawVarint64Size(int64_t value) __attribute__((const)); + +// Note that this will calculate the size of 64 bit values truncated to 32. +size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) + __attribute__((const)); + +// Compute the number of bytes that would be needed to encode a +// MessageSet extension to the stream. For historical reasons, +// the wire format differs from normal fields. +size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) + __attribute__((const)); + +// Compute the number of bytes that would be needed to encode an +// unparsed MessageSet extension field to the stream. For +// historical reasons, the wire format differs from normal fields. +size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) + __attribute__((const)); + +size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) + __attribute__((const)); + +CF_EXTERN_C_END + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.h b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.h new file mode 100644 index 0000000..651f4de --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.h @@ -0,0 +1,288 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBRuntimeTypes.h" + +@class GPBEnumDescriptor; +@class GPBFieldDescriptor; +@class GPBFileDescriptor; +@class GPBOneofDescriptor; + +NS_ASSUME_NONNULL_BEGIN + +/** Syntax used in the proto file. */ +typedef NS_ENUM(uint8_t, GPBFileSyntax) { + /** Unknown syntax. */ + GPBFileSyntaxUnknown = 0, + /** Proto2 syntax. */ + GPBFileSyntaxProto2 = 2, + /** Proto3 syntax. */ + GPBFileSyntaxProto3 = 3, +}; + +/** Type of proto field. */ +typedef NS_ENUM(uint8_t, GPBFieldType) { + /** Optional/required field. Only valid for proto2 fields. */ + GPBFieldTypeSingle, + /** Repeated field. */ + GPBFieldTypeRepeated, + /** Map field. */ + GPBFieldTypeMap, +}; + +/** + * Describes a proto message. + **/ +@interface GPBDescriptor : NSObject + +/** Name of the message. */ +@property(nonatomic, readonly, copy) NSString *name; +/** Fields declared in the message. */ +@property(nonatomic, readonly, strong, nullable) NSArray *fields; +/** Oneofs declared in the message. */ +@property(nonatomic, readonly, strong, nullable) NSArray *oneofs; +/** Extension range declared for the message. */ +@property(nonatomic, readonly, nullable) const GPBExtensionRange *extensionRanges; +/** Number of extension ranges declared for the message. */ +@property(nonatomic, readonly) uint32_t extensionRangesCount; +/** Descriptor for the file where the message was defined. */ +@property(nonatomic, readonly, assign) GPBFileDescriptor *file; + +/** Whether the message is in wire format or not. */ +@property(nonatomic, readonly, getter=isWireFormat) BOOL wireFormat; +/** The class of this message. */ +@property(nonatomic, readonly) Class messageClass; +/** Containing message descriptor if this message is nested, or nil otherwise. */ +@property(readonly, nullable) GPBDescriptor *containingType; +/** + * Fully qualified name for this message (package.message). Can be nil if the + * value is unable to be computed. + */ +@property(readonly, nullable) NSString *fullName; + +/** + * Gets the field for the given number. + * + * @param fieldNumber The number for the field to get. + * + * @return The field descriptor for the given number, or nil if not found. + **/ +- (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber; + +/** + * Gets the field for the given name. + * + * @param name The name for the field to get. + * + * @return The field descriptor for the given name, or nil if not found. + **/ +- (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name; + +/** + * Gets the oneof for the given name. + * + * @param name The name for the oneof to get. + * + * @return The oneof descriptor for the given name, or nil if not found. + **/ +- (nullable GPBOneofDescriptor *)oneofWithName:(NSString *)name; + +@end + +/** + * Describes a proto file. + **/ +@interface GPBFileDescriptor : NSObject + +/** The package declared in the proto file. */ +@property(nonatomic, readonly, copy) NSString *package; +/** The objc prefix declared in the proto file. */ +@property(nonatomic, readonly, copy, nullable) NSString *objcPrefix; +/** The syntax of the proto file. */ +@property(nonatomic, readonly) GPBFileSyntax syntax; + +@end + +/** + * Describes a oneof field. + **/ +@interface GPBOneofDescriptor : NSObject +/** Name of the oneof field. */ +@property(nonatomic, readonly) NSString *name; +/** Fields declared in the oneof. */ +@property(nonatomic, readonly) NSArray *fields; + +/** + * Gets the field for the given number. + * + * @param fieldNumber The number for the field to get. + * + * @return The field descriptor for the given number, or nil if not found. + **/ +- (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber; + +/** + * Gets the field for the given name. + * + * @param name The name for the field to get. + * + * @return The field descriptor for the given name, or nil if not found. + **/ +- (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name; + +@end + +/** + * Describes a proto field. + **/ +@interface GPBFieldDescriptor : NSObject + +/** Name of the field. */ +@property(nonatomic, readonly, copy) NSString *name; +/** Number associated with the field. */ +@property(nonatomic, readonly) uint32_t number; +/** Data type contained in the field. */ +@property(nonatomic, readonly) GPBDataType dataType; +/** Whether it has a default value or not. */ +@property(nonatomic, readonly) BOOL hasDefaultValue; +/** Default value for the field. */ +@property(nonatomic, readonly) GPBGenericValue defaultValue; +/** Whether this field is required. Only valid for proto2 fields. */ +@property(nonatomic, readonly, getter=isRequired) BOOL required; +/** Whether this field is optional. */ +@property(nonatomic, readonly, getter=isOptional) BOOL optional; +/** Type of field (single, repeated, map). */ +@property(nonatomic, readonly) GPBFieldType fieldType; +/** Type of the key if the field is a map. The value's type is -fieldType. */ +@property(nonatomic, readonly) GPBDataType mapKeyDataType; +/** Whether the field is packable. */ +@property(nonatomic, readonly, getter=isPackable) BOOL packable; + +/** The containing oneof if this field is part of one, nil otherwise. */ +@property(nonatomic, readonly, assign, nullable) GPBOneofDescriptor *containingOneof; + +/** Class of the message if the field is of message type. */ +@property(nonatomic, readonly, assign, nullable) Class msgClass; + +/** Descriptor for the enum if this field is an enum. */ +@property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor; + +/** + * Checks whether the given enum raw value is a valid enum value. + * + * @param value The raw enum value to check. + * + * @return YES if value is a valid enum raw value. + **/ +- (BOOL)isValidEnumValue:(int32_t)value; + +/** @return Name for the text format, or nil if not known. */ +- (nullable NSString *)textFormatName; + +@end + +/** + * Describes a proto enum. + **/ +@interface GPBEnumDescriptor : NSObject + +/** Name of the enum. */ +@property(nonatomic, readonly, copy) NSString *name; +/** Function that validates that raw values are valid enum values. */ +@property(nonatomic, readonly) GPBEnumValidationFunc enumVerifier; + +/** + * Returns the enum value name for the given raw enum. + * + * @param number The raw enum value. + * + * @return The name of the enum value passed, or nil if not valid. + **/ +- (nullable NSString *)enumNameForValue:(int32_t)number; + +/** + * Gets the enum raw value for the given enum name. + * + * @param outValue A pointer where the value will be set. + * @param name The enum name for which to get the raw value. + * + * @return YES if a value was copied into the pointer, NO otherwise. + **/ +- (BOOL)getValue:(nullable int32_t *)outValue forEnumName:(NSString *)name; + +/** + * Returns the text format for the given raw enum value. + * + * @param number The raw enum value. + * + * @return The text format name for the raw enum value, or nil if not valid. + **/ +- (nullable NSString *)textFormatNameForValue:(int32_t)number; + +/** + * Gets the enum raw value for the given text format name. + * + * @param outValue A pointer where the value will be set. + * @param textFormatName The text format name for which to get the raw value. + * + * @return YES if a value was copied into the pointer, NO otherwise. + **/ +- (BOOL)getValue:(nullable int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName; + +@end + +/** + * Describes a proto extension. + **/ +@interface GPBExtensionDescriptor : NSObject +/** Field number under which the extension is stored. */ +@property(nonatomic, readonly) uint32_t fieldNumber; +/** The containing message class, i.e. the class extended by this extension. */ +@property(nonatomic, readonly) Class containingMessageClass; +/** Data type contained in the extension. */ +@property(nonatomic, readonly) GPBDataType dataType; +/** Whether the extension is repeated. */ +@property(nonatomic, readonly, getter=isRepeated) BOOL repeated; +/** Whether the extension is packable. */ +@property(nonatomic, readonly, getter=isPackable) BOOL packable; +/** The class of the message if the extension is of message type. */ +@property(nonatomic, readonly, assign) Class msgClass; +/** The singleton name for the extension. */ +@property(nonatomic, readonly) NSString *singletonName; +/** The enum descriptor if the extension is of enum type. */ +@property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor; +/** The default value for the extension. */ +@property(nonatomic, readonly, nullable) id defaultValue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.m b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.m new file mode 100644 index 0000000..4b39c63 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor.m @@ -0,0 +1,1102 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBDescriptor_PackagePrivate.h" + +#import + +#import "GPBUtilities_PackagePrivate.h" +#import "GPBWireFormat.h" +#import "GPBMessage_PackagePrivate.h" + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +// The addresses of these variables are used as keys for objc_getAssociatedObject. +static const char kTextFormatExtraValueKey = 0; +static const char kParentClassNameValueKey = 0; +static const char kClassNameSuffixKey = 0; + +// Utility function to generate selectors on the fly. +static SEL SelFromStrings(const char *prefix, const char *middle, + const char *suffix, BOOL takesArg) { + if (prefix == NULL && suffix == NULL && !takesArg) { + return sel_getUid(middle); + } + const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0; + const size_t middleLen = strlen(middle); + const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0; + size_t totalLen = + prefixLen + middleLen + suffixLen + 1; // include space for null on end. + if (takesArg) { + totalLen += 1; + } + char buffer[totalLen]; + if (prefix != NULL) { + memcpy(buffer, prefix, prefixLen); + memcpy(buffer + prefixLen, middle, middleLen); + buffer[prefixLen] = (char)toupper(buffer[prefixLen]); + } else { + memcpy(buffer, middle, middleLen); + } + if (suffix != NULL) { + memcpy(buffer + prefixLen + middleLen, suffix, suffixLen); + } + if (takesArg) { + buffer[totalLen - 2] = ':'; + } + // Always null terminate it. + buffer[totalLen - 1] = 0; + + SEL result = sel_getUid(buffer); + return result; +} + +static NSArray *NewFieldsArrayForHasIndex(int hasIndex, + NSArray *allMessageFields) + __attribute__((ns_returns_retained)); + +static NSArray *NewFieldsArrayForHasIndex(int hasIndex, + NSArray *allMessageFields) { + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (GPBFieldDescriptor *fieldDesc in allMessageFields) { + if (fieldDesc->description_->hasIndex == hasIndex) { + [result addObject:fieldDesc]; + } + } + return result; +} + +@implementation GPBDescriptor { + Class messageClass_; + GPBFileDescriptor *file_; + BOOL wireFormat_; +} + +@synthesize messageClass = messageClass_; +@synthesize fields = fields_; +@synthesize oneofs = oneofs_; +@synthesize extensionRanges = extensionRanges_; +@synthesize extensionRangesCount = extensionRangesCount_; +@synthesize file = file_; +@synthesize wireFormat = wireFormat_; + ++ (instancetype) + allocDescriptorForClass:(Class)messageClass + rootClass:(Class)rootClass + file:(GPBFileDescriptor *)file + fields:(void *)fieldDescriptions + fieldCount:(uint32_t)fieldCount + storageSize:(uint32_t)storageSize + flags:(GPBDescriptorInitializationFlags)flags { + // The rootClass is no longer used, but it is passed in to ensure it + // was started up during initialization also. + (void)rootClass; + NSMutableArray *fields = nil; + GPBFileSyntax syntax = file.syntax; + BOOL fieldsIncludeDefault = + (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0; + + void *desc; + for (uint32_t i = 0; i < fieldCount; ++i) { + if (fields == nil) { + fields = [[NSMutableArray alloc] initWithCapacity:fieldCount]; + } + // Need correctly typed pointer for array indexing below to work. + if (fieldsIncludeDefault) { + GPBMessageFieldDescriptionWithDefault *fieldDescWithDefault = fieldDescriptions; + desc = &(fieldDescWithDefault[i]); + } else { + GPBMessageFieldDescription *fieldDesc = fieldDescriptions; + desc = &(fieldDesc[i]); + } + GPBFieldDescriptor *fieldDescriptor = + [[GPBFieldDescriptor alloc] initWithFieldDescription:desc + includesDefault:fieldsIncludeDefault + syntax:syntax]; + [fields addObject:fieldDescriptor]; + [fieldDescriptor release]; + } + + BOOL wireFormat = (flags & GPBDescriptorInitializationFlag_WireFormat) != 0; + GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass + file:file + fields:fields + storageSize:storageSize + wireFormat:wireFormat]; + [fields release]; + return descriptor; +} + +- (instancetype)initWithClass:(Class)messageClass + file:(GPBFileDescriptor *)file + fields:(NSArray *)fields + storageSize:(uint32_t)storageSize + wireFormat:(BOOL)wireFormat { + if ((self = [super init])) { + messageClass_ = messageClass; + file_ = file; + fields_ = [fields retain]; + storageSize_ = storageSize; + wireFormat_ = wireFormat; + } + return self; +} + +- (void)dealloc { + [fields_ release]; + [oneofs_ release]; + [super dealloc]; +} + +- (void)setupOneofs:(const char **)oneofNames + count:(uint32_t)count + firstHasIndex:(int32_t)firstHasIndex { + NSCAssert(firstHasIndex < 0, @"Should always be <0"); + NSMutableArray *oneofs = [[NSMutableArray alloc] initWithCapacity:count]; + for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) { + const char *name = oneofNames[i]; + NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_); + NSCAssert(fieldsForOneof.count > 0, + @"No fields for this oneof? (%s:%d)", name, hasIndex); + GPBOneofDescriptor *oneofDescriptor = + [[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof]; + [oneofs addObject:oneofDescriptor]; + [oneofDescriptor release]; + [fieldsForOneof release]; + } + oneofs_ = oneofs; +} + +- (void)setupExtraTextInfo:(const char *)extraTextFormatInfo { + // Extra info is a compile time option, so skip the work if not needed. + if (extraTextFormatInfo) { + NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo]; + for (GPBFieldDescriptor *fieldDescriptor in fields_) { + if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) { + objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, + extraInfoValue, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + } + } +} + +- (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count { + extensionRanges_ = ranges; + extensionRangesCount_ = count; +} + +- (void)setupContainingMessageClassName:(const char *)msgClassName { + // Note: Only fetch the class here, can't send messages to it because + // that could cause cycles back to this class within +initialize if + // two messages have each other in fields (i.e. - they build a graph). + NSAssert(objc_getClass(msgClassName), @"Class %s not defined", msgClassName); + NSValue *parentNameValue = [NSValue valueWithPointer:msgClassName]; + objc_setAssociatedObject(self, &kParentClassNameValueKey, + parentNameValue, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)setupMessageClassNameSuffix:(NSString *)suffix { + if (suffix.length) { + objc_setAssociatedObject(self, &kClassNameSuffixKey, + suffix, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (NSString *)name { + return NSStringFromClass(messageClass_); +} + +- (GPBDescriptor *)containingType { + NSValue *parentNameValue = + objc_getAssociatedObject(self, &kParentClassNameValueKey); + if (!parentNameValue) { + return nil; + } + const char *parentName = [parentNameValue pointerValue]; + Class parentClass = objc_getClass(parentName); + NSAssert(parentClass, @"Class %s not defined", parentName); + return [parentClass descriptor]; +} + +- (NSString *)fullName { + NSString *className = NSStringFromClass(self.messageClass); + GPBFileDescriptor *file = self.file; + NSString *objcPrefix = file.objcPrefix; + if (objcPrefix && ![className hasPrefix:objcPrefix]) { + NSAssert(0, + @"Class didn't have correct prefix? (%@ - %@)", + className, objcPrefix); + return nil; + } + GPBDescriptor *parent = self.containingType; + + NSString *name = nil; + if (parent) { + NSString *parentClassName = NSStringFromClass(parent.messageClass); + // The generator will add _Class to avoid reserved words, drop it. + NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey); + if (suffix) { + if (![parentClassName hasSuffix:suffix]) { + NSAssert(0, + @"ParentMessage class didn't have correct suffix? (%@ - %@)", + className, suffix); + return nil; + } + parentClassName = + [parentClassName substringToIndex:(parentClassName.length - suffix.length)]; + } + NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"]; + if (![className hasPrefix:parentPrefix]) { + NSAssert(0, + @"Class didn't have the correct parent name prefix? (%@ - %@)", + parentPrefix, className); + return nil; + } + name = [className substringFromIndex:parentPrefix.length]; + } else { + name = [className substringFromIndex:objcPrefix.length]; + } + + // The generator will add _Class to avoid reserved words, drop it. + NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey); + if (suffix) { + if (![name hasSuffix:suffix]) { + NSAssert(0, + @"Message class didn't have correct suffix? (%@ - %@)", + name, suffix); + return nil; + } + name = [name substringToIndex:(name.length - suffix.length)]; + } + + NSString *prefix = (parent != nil ? parent.fullName : file.package); + NSString *result; + if (prefix.length > 0) { + result = [NSString stringWithFormat:@"%@.%@", prefix, name]; + } else { + result = name; + } + return result; +} + +- (id)copyWithZone:(NSZone *)zone { +#pragma unused(zone) + return [self retain]; +} + +- (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { + for (GPBFieldDescriptor *descriptor in fields_) { + if (GPBFieldNumber(descriptor) == fieldNumber) { + return descriptor; + } + } + return nil; +} + +- (GPBFieldDescriptor *)fieldWithName:(NSString *)name { + for (GPBFieldDescriptor *descriptor in fields_) { + if ([descriptor.name isEqual:name]) { + return descriptor; + } + } + return nil; +} + +- (GPBOneofDescriptor *)oneofWithName:(NSString *)name { + for (GPBOneofDescriptor *descriptor in oneofs_) { + if ([descriptor.name isEqual:name]) { + return descriptor; + } + } + return nil; +} + +@end + +@implementation GPBFileDescriptor { + NSString *package_; + NSString *objcPrefix_; + GPBFileSyntax syntax_; +} + +@synthesize package = package_; +@synthesize objcPrefix = objcPrefix_; +@synthesize syntax = syntax_; + +- (instancetype)initWithPackage:(NSString *)package + objcPrefix:(NSString *)objcPrefix + syntax:(GPBFileSyntax)syntax { + self = [super init]; + if (self) { + package_ = [package copy]; + objcPrefix_ = [objcPrefix copy]; + syntax_ = syntax; + } + return self; +} + +- (instancetype)initWithPackage:(NSString *)package + syntax:(GPBFileSyntax)syntax { + self = [super init]; + if (self) { + package_ = [package copy]; + syntax_ = syntax; + } + return self; +} + +- (void)dealloc { + [package_ release]; + [objcPrefix_ release]; + [super dealloc]; +} + +@end + +@implementation GPBOneofDescriptor + +@synthesize fields = fields_; + +- (instancetype)initWithName:(const char *)name fields:(NSArray *)fields { + self = [super init]; + if (self) { + name_ = name; + fields_ = [fields retain]; + for (GPBFieldDescriptor *fieldDesc in fields) { + fieldDesc->containingOneof_ = self; + } + + caseSel_ = SelFromStrings(NULL, name, "OneOfCase", NO); + } + return self; +} + +- (void)dealloc { + [fields_ release]; + [super dealloc]; +} + +- (NSString *)name { + return (NSString * _Nonnull)@(name_); +} + +- (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { + for (GPBFieldDescriptor *descriptor in fields_) { + if (GPBFieldNumber(descriptor) == fieldNumber) { + return descriptor; + } + } + return nil; +} + +- (GPBFieldDescriptor *)fieldWithName:(NSString *)name { + for (GPBFieldDescriptor *descriptor in fields_) { + if ([descriptor.name isEqual:name]) { + return descriptor; + } + } + return nil; +} + +@end + +uint32_t GPBFieldTag(GPBFieldDescriptor *self) { + GPBMessageFieldDescription *description = self->description_; + GPBWireFormat format; + if ((description->flags & GPBFieldMapKeyMask) != 0) { + // Maps are repeated messages on the wire. + format = GPBWireFormatForType(GPBDataTypeMessage, NO); + } else { + format = GPBWireFormatForType(description->dataType, + ((description->flags & GPBFieldPacked) != 0)); + } + return GPBWireFormatMakeTag(description->number, format); +} + +uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { + GPBMessageFieldDescription *description = self->description_; + NSCAssert((description->flags & GPBFieldRepeated) != 0, + @"Only valid on repeated fields"); + GPBWireFormat format = + GPBWireFormatForType(description->dataType, + ((description->flags & GPBFieldPacked) == 0)); + return GPBWireFormatMakeTag(description->number, format); +} + +@implementation GPBFieldDescriptor { + GPBGenericValue defaultValue_; + + // Message ivars + Class msgClass_; + + // Enum ivars. + // If protos are generated with GenerateEnumDescriptors on then it will + // be a enumDescriptor, otherwise it will be a enumVerifier. + union { + GPBEnumDescriptor *enumDescriptor_; + GPBEnumValidationFunc enumVerifier_; + } enumHandling_; +} + +@synthesize msgClass = msgClass_; +@synthesize containingOneof = containingOneof_; + +- (instancetype)init { + // Throw an exception if people attempt to not use the designated initializer. + self = [super init]; + if (self != nil) { + [self doesNotRecognizeSelector:_cmd]; + self = nil; + } + return self; +} + +- (instancetype)initWithFieldDescription:(void *)description + includesDefault:(BOOL)includesDefault + syntax:(GPBFileSyntax)syntax { + if ((self = [super init])) { + GPBMessageFieldDescription *coreDesc; + if (includesDefault) { + coreDesc = &(((GPBMessageFieldDescriptionWithDefault *)description)->core); + } else { + coreDesc = description; + } + description_ = coreDesc; + getSel_ = sel_getUid(coreDesc->name); + setSel_ = SelFromStrings("set", coreDesc->name, NULL, YES); + + GPBDataType dataType = coreDesc->dataType; + BOOL isMessage = GPBDataTypeIsMessage(dataType); + BOOL isMapOrArray = GPBFieldIsMapOrArray(self); + + if (isMapOrArray) { + // map<>/repeated fields get a *Count property (inplace of a has*) to + // support checking if there are any entries without triggering + // autocreation. + hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO); + } else { + // If there is a positive hasIndex, then: + // - All fields types for proto2 messages get has* selectors. + // - Only message fields for proto3 messages get has* selectors. + // Note: the positive check is to handle oneOfs, we can't check + // containingOneof_ because it isn't set until after initialization. + if ((coreDesc->hasIndex >= 0) && + (coreDesc->hasIndex != GPBNoHasBit) && + ((syntax != GPBFileSyntaxProto3) || isMessage)) { + hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO); + setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES); + } + } + + // Extra type specific data. + if (isMessage) { + const char *className = coreDesc->dataTypeSpecific.className; + // Note: Only fetch the class here, can't send messages to it because + // that could cause cycles back to this class within +initialize if + // two messages have each other in fields (i.e. - they build a graph). + msgClass_ = objc_getClass(className); + NSAssert(msgClass_, @"Class %s not defined", className); + } else if (dataType == GPBDataTypeEnum) { + if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) { + enumHandling_.enumDescriptor_ = + coreDesc->dataTypeSpecific.enumDescFunc(); + } else { + enumHandling_.enumVerifier_ = + coreDesc->dataTypeSpecific.enumVerifier; + } + } + + // Non map<>/repeated fields can have defaults in proto2 syntax. + if (!isMapOrArray && includesDefault) { + defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue; + if (dataType == GPBDataTypeBytes) { + // Data stored as a length prefixed (network byte order) c-string in + // descriptor structure. + const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData; + if (bytes) { + uint32_t length; + memcpy(&length, bytes, sizeof(length)); + length = ntohl(length); + bytes += sizeof(length); + defaultValue_.valueData = + [[NSData alloc] initWithBytes:bytes length:length]; + } + } + } + } + return self; +} + +- (void)dealloc { + if (description_->dataType == GPBDataTypeBytes && + !(description_->flags & GPBFieldRepeated)) { + [defaultValue_.valueData release]; + } + [super dealloc]; +} + +- (GPBDataType)dataType { + return description_->dataType; +} + +- (BOOL)hasDefaultValue { + return (description_->flags & GPBFieldHasDefaultValue) != 0; +} + +- (uint32_t)number { + return description_->number; +} + +- (NSString *)name { + return (NSString * _Nonnull)@(description_->name); +} + +- (BOOL)isRequired { + return (description_->flags & GPBFieldRequired) != 0; +} + +- (BOOL)isOptional { + return (description_->flags & GPBFieldOptional) != 0; +} + +- (GPBFieldType)fieldType { + GPBFieldFlags flags = description_->flags; + if ((flags & GPBFieldRepeated) != 0) { + return GPBFieldTypeRepeated; + } else if ((flags & GPBFieldMapKeyMask) != 0) { + return GPBFieldTypeMap; + } else { + return GPBFieldTypeSingle; + } +} + +- (GPBDataType)mapKeyDataType { + switch (description_->flags & GPBFieldMapKeyMask) { + case GPBFieldMapKeyInt32: + return GPBDataTypeInt32; + case GPBFieldMapKeyInt64: + return GPBDataTypeInt64; + case GPBFieldMapKeyUInt32: + return GPBDataTypeUInt32; + case GPBFieldMapKeyUInt64: + return GPBDataTypeUInt64; + case GPBFieldMapKeySInt32: + return GPBDataTypeSInt32; + case GPBFieldMapKeySInt64: + return GPBDataTypeSInt64; + case GPBFieldMapKeyFixed32: + return GPBDataTypeFixed32; + case GPBFieldMapKeyFixed64: + return GPBDataTypeFixed64; + case GPBFieldMapKeySFixed32: + return GPBDataTypeSFixed32; + case GPBFieldMapKeySFixed64: + return GPBDataTypeSFixed64; + case GPBFieldMapKeyBool: + return GPBDataTypeBool; + case GPBFieldMapKeyString: + return GPBDataTypeString; + + default: + NSAssert(0, @"Not a map type"); + return GPBDataTypeInt32; // For lack of anything better. + } +} + +- (BOOL)isPackable { + return (description_->flags & GPBFieldPacked) != 0; +} + +- (BOOL)isValidEnumValue:(int32_t)value { + NSAssert(description_->dataType == GPBDataTypeEnum, + @"Field Must be of type GPBDataTypeEnum"); + if (description_->flags & GPBFieldHasEnumDescriptor) { + return enumHandling_.enumDescriptor_.enumVerifier(value); + } else { + return enumHandling_.enumVerifier_(value); + } +} + +- (GPBEnumDescriptor *)enumDescriptor { + if (description_->flags & GPBFieldHasEnumDescriptor) { + return enumHandling_.enumDescriptor_; + } else { + return nil; + } +} + +- (GPBGenericValue)defaultValue { + // Depends on the fact that defaultValue_ is initialized either to "0/nil" or + // to an actual defaultValue in our initializer. + GPBGenericValue value = defaultValue_; + + if (!(description_->flags & GPBFieldRepeated)) { + // We special handle data and strings. If they are nil, we replace them + // with empty string/empty data. + GPBDataType type = description_->dataType; + if (type == GPBDataTypeBytes && value.valueData == nil) { + value.valueData = GPBEmptyNSData(); + } else if (type == GPBDataTypeString && value.valueString == nil) { + value.valueString = @""; + } + } + return value; +} + +- (NSString *)textFormatName { + if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) { + NSValue *extraInfoValue = + objc_getAssociatedObject(self, &kTextFormatExtraValueKey); + // Support can be left out at generation time. + if (!extraInfoValue) { + return nil; + } + const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue]; + return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), + self.name); + } + + // The logic here has to match SetCommonFieldVariables() from + // objectivec_field.cc in the proto compiler. + NSString *name = self.name; + NSUInteger len = [name length]; + + // Remove the "_p" added to reserved names. + if ([name hasSuffix:@"_p"]) { + name = [name substringToIndex:(len - 2)]; + len = [name length]; + } + + // Remove "Array" from the end for repeated fields. + if (((description_->flags & GPBFieldRepeated) != 0) && + [name hasSuffix:@"Array"]) { + name = [name substringToIndex:(len - 5)]; + len = [name length]; + } + + // Groups vs. other fields. + if (description_->dataType == GPBDataTypeGroup) { + // Just capitalize the first letter. + unichar firstChar = [name characterAtIndex:0]; + if (firstChar >= 'a' && firstChar <= 'z') { + NSString *firstCharString = + [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')]; + NSString *result = + [name stringByReplacingCharactersInRange:NSMakeRange(0, 1) + withString:firstCharString]; + return result; + } + return name; + + } else { + // Undo the CamelCase. + NSMutableString *result = [NSMutableString stringWithCapacity:len]; + for (uint32_t i = 0; i < len; i++) { + unichar c = [name characterAtIndex:i]; + if (c >= 'A' && c <= 'Z') { + if (i > 0) { + [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')]; + } else { + [result appendFormat:@"%C", c]; + } + } else { + [result appendFormat:@"%C", c]; + } + } + return result; + } +} + +@end + +@implementation GPBEnumDescriptor { + NSString *name_; + // valueNames_ is a single c string with all of the value names appended + // together, each null terminated. -calcValueNameOffsets fills in + // nameOffsets_ with the offsets to allow quicker access to the individual + // names. + const char *valueNames_; + const int32_t *values_; + GPBEnumValidationFunc enumVerifier_; + const uint8_t *extraTextFormatInfo_; + uint32_t *nameOffsets_; + uint32_t valueCount_; +} + +@synthesize name = name_; +@synthesize enumVerifier = enumVerifier_; + ++ (instancetype) + allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier { + GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name + valueNames:valueNames + values:values + count:valueCount + enumVerifier:enumVerifier]; + return descriptor; +} + ++ (instancetype) + allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier + extraTextFormatInfo:(const char *)extraTextFormatInfo { + // Call the common case. + GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name + valueNames:valueNames + values:values + count:valueCount + enumVerifier:enumVerifier]; + // Set the extra info. + descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo; + return descriptor; +} + +- (instancetype)initWithName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier { + if ((self = [super init])) { + name_ = [name copy]; + valueNames_ = valueNames; + values_ = values; + valueCount_ = valueCount; + enumVerifier_ = enumVerifier; + } + return self; +} + +- (void)dealloc { + [name_ release]; + if (nameOffsets_) free(nameOffsets_); + [super dealloc]; +} + +- (void)calcValueNameOffsets { + @synchronized(self) { + if (nameOffsets_ != NULL) { + return; + } + uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t)); + const char *scan = valueNames_; + for (uint32_t i = 0; i < valueCount_; ++i) { + offsets[i] = (uint32_t)(scan - valueNames_); + while (*scan != '\0') ++scan; + ++scan; // Step over the null. + } + nameOffsets_ = offsets; + } +} + +- (NSString *)enumNameForValue:(int32_t)number { + if (nameOffsets_ == NULL) [self calcValueNameOffsets]; + + for (uint32_t i = 0; i < valueCount_; ++i) { + if (values_[i] == number) { + const char *valueName = valueNames_ + nameOffsets_[i]; + NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName]; + return fullName; + } + } + return nil; +} + +- (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name { + // Must have the prefix. + NSUInteger prefixLen = name_.length + 1; + if ((name.length <= prefixLen) || ![name hasPrefix:name_] || + ([name characterAtIndex:prefixLen - 1] != '_')) { + return NO; + } + + // Skip over the prefix. + const char *nameAsCStr = [name UTF8String]; + nameAsCStr += prefixLen; + + if (nameOffsets_ == NULL) [self calcValueNameOffsets]; + + // Find it. + for (uint32_t i = 0; i < valueCount_; ++i) { + const char *valueName = valueNames_ + nameOffsets_[i]; + if (strcmp(nameAsCStr, valueName) == 0) { + if (outValue) { + *outValue = values_[i]; + } + return YES; + } + } + return NO; +} + +- (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName { + if (nameOffsets_ == NULL) [self calcValueNameOffsets]; + + for (uint32_t i = 0; i < valueCount_; ++i) { + int32_t value = values_[i]; + NSString *valueTextFormatName = [self textFormatNameForValue:value]; + if ([valueTextFormatName isEqual:textFormatName]) { + if (outValue) { + *outValue = value; + } + return YES; + } + } + return NO; +} + +- (NSString *)textFormatNameForValue:(int32_t)number { + if (nameOffsets_ == NULL) [self calcValueNameOffsets]; + + // Find the EnumValue descriptor and its index. + BOOL foundIt = NO; + uint32_t valueDescriptorIndex; + for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; + ++valueDescriptorIndex) { + if (values_[valueDescriptorIndex] == number) { + foundIt = YES; + break; + } + } + + if (!foundIt) { + return nil; + } + + NSString *result = nil; + // Naming adds an underscore between enum name and value name, skip that also. + const char *valueName = valueNames_ + nameOffsets_[valueDescriptorIndex]; + NSString *shortName = @(valueName); + + // See if it is in the map of special format handling. + if (extraTextFormatInfo_) { + result = GPBDecodeTextFormatName(extraTextFormatInfo_, + (int32_t)valueDescriptorIndex, shortName); + } + // Logic here needs to match what objectivec_enum.cc does in the proto + // compiler. + if (result == nil) { + NSUInteger len = [shortName length]; + NSMutableString *worker = [NSMutableString stringWithCapacity:len]; + for (NSUInteger i = 0; i < len; i++) { + unichar c = [shortName characterAtIndex:i]; + if (i > 0 && c >= 'A' && c <= 'Z') { + [worker appendString:@"_"]; + } + [worker appendFormat:@"%c", toupper((char)c)]; + } + result = worker; + } + return result; +} + +@end + +@implementation GPBExtensionDescriptor { + GPBGenericValue defaultValue_; +} + +@synthesize containingMessageClass = containingMessageClass_; + +- (instancetype)initWithExtensionDescription: + (GPBExtensionDescription *)description { + if ((self = [super init])) { + description_ = description; + +#if defined(DEBUG) && DEBUG + const char *className = description->messageOrGroupClassName; + if (className) { + NSAssert(objc_lookUpClass(className) != Nil, + @"Class %s not defined", className); + } +#endif + + if (description->extendedClass) { + Class containingClass = objc_lookUpClass(description->extendedClass); + NSAssert(containingClass, @"Class %s not defined", + description->extendedClass); + containingMessageClass_ = containingClass; + } + + GPBDataType type = description_->dataType; + if (type == GPBDataTypeBytes) { + // Data stored as a length prefixed c-string in descriptor records. + const uint8_t *bytes = + (const uint8_t *)description->defaultValue.valueData; + if (bytes) { + uint32_t length; + memcpy(&length, bytes, sizeof(length)); + // The length is stored in network byte order. + length = ntohl(length); + bytes += sizeof(length); + defaultValue_.valueData = + [[NSData alloc] initWithBytes:bytes length:length]; + } + } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) { + // The default is looked up in -defaultValue instead since extensions + // aren't common, we avoid the hit startup hit and it avoid initialization + // order issues. + } else { + defaultValue_ = description->defaultValue; + } + } + return self; +} + +- (void)dealloc { + if ((description_->dataType == GPBDataTypeBytes) && + !GPBExtensionIsRepeated(description_)) { + [defaultValue_.valueData release]; + } + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { +#pragma unused(zone) + // Immutable. + return [self retain]; +} + +- (NSString *)singletonName { + return (NSString * _Nonnull)@(description_->singletonName); +} + +- (const char *)singletonNameC { + return description_->singletonName; +} + +- (uint32_t)fieldNumber { + return description_->fieldNumber; +} + +- (GPBDataType)dataType { + return description_->dataType; +} + +- (GPBWireFormat)wireType { + return GPBWireFormatForType(description_->dataType, + GPBExtensionIsPacked(description_)); +} + +- (GPBWireFormat)alternateWireType { + NSAssert(GPBExtensionIsRepeated(description_), + @"Only valid on repeated extensions"); + return GPBWireFormatForType(description_->dataType, + !GPBExtensionIsPacked(description_)); +} + +- (BOOL)isRepeated { + return GPBExtensionIsRepeated(description_); +} + +- (BOOL)isPackable { + return GPBExtensionIsPacked(description_); +} + +- (Class)msgClass { + return objc_getClass(description_->messageOrGroupClassName); +} + +- (GPBEnumDescriptor *)enumDescriptor { + if (description_->dataType == GPBDataTypeEnum) { + GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc(); + return enumDescriptor; + } + return nil; +} + +- (id)defaultValue { + if (GPBExtensionIsRepeated(description_)) { + return nil; + } + + switch (description_->dataType) { + case GPBDataTypeBool: + return @(defaultValue_.valueBool); + case GPBDataTypeFloat: + return @(defaultValue_.valueFloat); + case GPBDataTypeDouble: + return @(defaultValue_.valueDouble); + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + case GPBDataTypeEnum: + case GPBDataTypeSFixed32: + return @(defaultValue_.valueInt32); + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + case GPBDataTypeSFixed64: + return @(defaultValue_.valueInt64); + case GPBDataTypeUInt32: + case GPBDataTypeFixed32: + return @(defaultValue_.valueUInt32); + case GPBDataTypeUInt64: + case GPBDataTypeFixed64: + return @(defaultValue_.valueUInt64); + case GPBDataTypeBytes: + // Like message fields, the default is zero length data. + return (defaultValue_.valueData ? defaultValue_.valueData + : GPBEmptyNSData()); + case GPBDataTypeString: + // Like message fields, the default is zero length string. + return (defaultValue_.valueString ? defaultValue_.valueString : @""); + case GPBDataTypeGroup: + case GPBDataTypeMessage: + return nil; + } +} + +- (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other { + int32_t selfNumber = description_->fieldNumber; + int32_t otherNumber = other->description_->fieldNumber; + if (selfNumber < otherNumber) { + return NSOrderedAscending; + } else if (selfNumber == otherNumber) { + return NSOrderedSame; + } else { + return NSOrderedDescending; + } +} + +@end + +#pragma clang diagnostic pop diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDescriptor_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor_PackagePrivate.h new file mode 100644 index 0000000..452b3f8 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDescriptor_PackagePrivate.h @@ -0,0 +1,325 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +// This header is private to the ProtobolBuffers library and must NOT be +// included by any sources outside this library. The contents of this file are +// subject to change at any time without notice. + +#import "GPBDescriptor.h" +#import "GPBWireFormat.h" + +// Describes attributes of the field. +typedef NS_OPTIONS(uint16_t, GPBFieldFlags) { + GPBFieldNone = 0, + // These map to standard protobuf concepts. + GPBFieldRequired = 1 << 0, + GPBFieldRepeated = 1 << 1, + GPBFieldPacked = 1 << 2, + GPBFieldOptional = 1 << 3, + GPBFieldHasDefaultValue = 1 << 4, + + // Indicates the field needs custom handling for the TextFormat name, if not + // set, the name can be derived from the ObjC name. + GPBFieldTextFormatNameCustom = 1 << 6, + // Indicates the field has an enum descriptor. + GPBFieldHasEnumDescriptor = 1 << 7, + + // These are not standard protobuf concepts, they are specific to the + // Objective C runtime. + + // These bits are used to mark the field as a map and what the key + // type is. + GPBFieldMapKeyMask = 0xF << 8, + GPBFieldMapKeyInt32 = 1 << 8, + GPBFieldMapKeyInt64 = 2 << 8, + GPBFieldMapKeyUInt32 = 3 << 8, + GPBFieldMapKeyUInt64 = 4 << 8, + GPBFieldMapKeySInt32 = 5 << 8, + GPBFieldMapKeySInt64 = 6 << 8, + GPBFieldMapKeyFixed32 = 7 << 8, + GPBFieldMapKeyFixed64 = 8 << 8, + GPBFieldMapKeySFixed32 = 9 << 8, + GPBFieldMapKeySFixed64 = 10 << 8, + GPBFieldMapKeyBool = 11 << 8, + GPBFieldMapKeyString = 12 << 8, +}; + +// NOTE: The structures defined here have their members ordered to minimize +// their size. This directly impacts the size of apps since these exist per +// field/extension. + +// Describes a single field in a protobuf as it is represented as an ivar. +typedef struct GPBMessageFieldDescription { + // Name of ivar. + const char *name; + union { + const char *className; // Name for message class. + // For enums only: If EnumDescriptors are compiled in, it will be that, + // otherwise it will be the verifier. + GPBEnumDescriptorFunc enumDescFunc; + GPBEnumValidationFunc enumVerifier; + } dataTypeSpecific; + // The field number for the ivar. + uint32_t number; + // The index (in bits) into _has_storage_. + // >= 0: the bit to use for a value being set. + // = GPBNoHasBit(INT32_MAX): no storage used. + // < 0: in a oneOf, use a full int32 to record the field active. + int32_t hasIndex; + // Offset of the variable into it's structure struct. + uint32_t offset; + // Field flags. Use accessor functions below. + GPBFieldFlags flags; + // Data type of the ivar. + GPBDataType dataType; +} GPBMessageFieldDescription; + +// Fields in messages defined in a 'proto2' syntax file can provide a default +// value. This struct provides the default along with the field info. +typedef struct GPBMessageFieldDescriptionWithDefault { + // Default value for the ivar. + GPBGenericValue defaultValue; + + GPBMessageFieldDescription core; +} GPBMessageFieldDescriptionWithDefault; + +// Describes attributes of the extension. +typedef NS_OPTIONS(uint8_t, GPBExtensionOptions) { + GPBExtensionNone = 0, + // These map to standard protobuf concepts. + GPBExtensionRepeated = 1 << 0, + GPBExtensionPacked = 1 << 1, + GPBExtensionSetWireFormat = 1 << 2, +}; + +// An extension +typedef struct GPBExtensionDescription { + GPBGenericValue defaultValue; + const char *singletonName; + const char *extendedClass; + const char *messageOrGroupClassName; + GPBEnumDescriptorFunc enumDescriptorFunc; + int32_t fieldNumber; + GPBDataType dataType; + GPBExtensionOptions options; +} GPBExtensionDescription; + +typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { + GPBDescriptorInitializationFlag_None = 0, + GPBDescriptorInitializationFlag_FieldsWithDefault = 1 << 0, + GPBDescriptorInitializationFlag_WireFormat = 1 << 1, +}; + +@interface GPBDescriptor () { + @package + NSArray *fields_; + NSArray *oneofs_; + uint32_t storageSize_; +} + +// fieldDescriptions have to be long lived, they are held as raw pointers. ++ (instancetype) + allocDescriptorForClass:(Class)messageClass + rootClass:(Class)rootClass + file:(GPBFileDescriptor *)file + fields:(void *)fieldDescriptions + fieldCount:(uint32_t)fieldCount + storageSize:(uint32_t)storageSize + flags:(GPBDescriptorInitializationFlags)flags; + +- (instancetype)initWithClass:(Class)messageClass + file:(GPBFileDescriptor *)file + fields:(NSArray *)fields + storageSize:(uint32_t)storage + wireFormat:(BOOL)wireFormat; + +// Called right after init to provide extra information to avoid init having +// an explosion of args. These pointers are recorded, so they are expected +// to live for the lifetime of the app. +- (void)setupOneofs:(const char **)oneofNames + count:(uint32_t)count + firstHasIndex:(int32_t)firstHasIndex; +- (void)setupExtraTextInfo:(const char *)extraTextFormatInfo; +- (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count; +- (void)setupContainingMessageClassName:(const char *)msgClassName; +- (void)setupMessageClassNameSuffix:(NSString *)suffix; + +@end + +@interface GPBFileDescriptor () +- (instancetype)initWithPackage:(NSString *)package + objcPrefix:(NSString *)objcPrefix + syntax:(GPBFileSyntax)syntax; +- (instancetype)initWithPackage:(NSString *)package + syntax:(GPBFileSyntax)syntax; +@end + +@interface GPBOneofDescriptor () { + @package + const char *name_; + NSArray *fields_; + SEL caseSel_; +} +// name must be long lived. +- (instancetype)initWithName:(const char *)name fields:(NSArray *)fields; +@end + +@interface GPBFieldDescriptor () { + @package + GPBMessageFieldDescription *description_; + GPB_UNSAFE_UNRETAINED GPBOneofDescriptor *containingOneof_; + + SEL getSel_; + SEL setSel_; + SEL hasOrCountSel_; // *Count for map<>/repeated fields, has* otherwise. + SEL setHasSel_; +} + +// Single initializer +// description has to be long lived, it is held as a raw pointer. +- (instancetype)initWithFieldDescription:(void *)description + includesDefault:(BOOL)includesDefault + syntax:(GPBFileSyntax)syntax; +@end + +@interface GPBEnumDescriptor () +// valueNames, values and extraTextFormatInfo have to be long lived, they are +// held as raw pointers. ++ (instancetype) + allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier; ++ (instancetype) + allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier + extraTextFormatInfo:(const char *)extraTextFormatInfo; + +- (instancetype)initWithName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier; +@end + +@interface GPBExtensionDescriptor () { + @package + GPBExtensionDescription *description_; +} +@property(nonatomic, readonly) GPBWireFormat wireType; + +// For repeated extensions, alternateWireType is the wireType with the opposite +// value for the packable property. i.e. - if the extension was marked packed +// it would be the wire type for unpacked; if the extension was marked unpacked, +// it would be the wire type for packed. +@property(nonatomic, readonly) GPBWireFormat alternateWireType; + +// description has to be long lived, it is held as a raw pointer. +- (instancetype)initWithExtensionDescription: + (GPBExtensionDescription *)description; +- (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other; +@end + +CF_EXTERN_C_BEGIN + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +GPB_INLINE BOOL GPBFieldIsMapOrArray(GPBFieldDescriptor *field) { + return (field->description_->flags & + (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0; +} + +GPB_INLINE GPBDataType GPBGetFieldDataType(GPBFieldDescriptor *field) { + return field->description_->dataType; +} + +GPB_INLINE int32_t GPBFieldHasIndex(GPBFieldDescriptor *field) { + return field->description_->hasIndex; +} + +GPB_INLINE uint32_t GPBFieldNumber(GPBFieldDescriptor *field) { + return field->description_->number; +} + +#pragma clang diagnostic pop + +uint32_t GPBFieldTag(GPBFieldDescriptor *self); + +// For repeated fields, alternateWireType is the wireType with the opposite +// value for the packable property. i.e. - if the field was marked packed it +// would be the wire type for unpacked; if the field was marked unpacked, it +// would be the wire type for packed. +uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self); + +GPB_INLINE BOOL GPBHasPreservingUnknownEnumSemantics(GPBFileSyntax syntax) { + return syntax == GPBFileSyntaxProto3; +} + +GPB_INLINE BOOL GPBExtensionIsRepeated(GPBExtensionDescription *description) { + return (description->options & GPBExtensionRepeated) != 0; +} + +GPB_INLINE BOOL GPBExtensionIsPacked(GPBExtensionDescription *description) { + return (description->options & GPBExtensionPacked) != 0; +} + +GPB_INLINE BOOL GPBExtensionIsWireFormat(GPBExtensionDescription *description) { + return (description->options & GPBExtensionSetWireFormat) != 0; +} + +// Helper for compile time assets. +#ifndef GPBInternalCompileAssert + #if __has_feature(c_static_assert) || __has_extension(c_static_assert) + #define GPBInternalCompileAssert(test, msg) _Static_assert((test), #msg) + #else + // Pre-Xcode 7 support. + #define GPBInternalCompileAssertSymbolInner(line, msg) GPBInternalCompileAssert ## line ## __ ## msg + #define GPBInternalCompileAssertSymbol(line, msg) GPBInternalCompileAssertSymbolInner(line, msg) + #define GPBInternalCompileAssert(test, msg) \ + typedef char GPBInternalCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] + #endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) +#endif // GPBInternalCompileAssert + +// Sanity check that there isn't padding between the field description +// structures with and without a default. +GPBInternalCompileAssert(sizeof(GPBMessageFieldDescriptionWithDefault) == + (sizeof(GPBGenericValue) + + sizeof(GPBMessageFieldDescription)), + DescriptionsWithDefault_different_size_than_expected); + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDictionary.h b/My Mind/Pods/Protobuf/objectivec/GPBDictionary.h new file mode 100644 index 0000000..a81165e --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDictionary.h @@ -0,0 +1,5770 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBRuntimeTypes.h" + +// Note on naming: for the classes holding numeric values, a more natural +// naming of the method might be things like "-valueForKey:", +// "-setValue:forKey:"; etc. But those selectors are also defined by Key Value +// Coding (KVC) as categories on NSObject. So "overloading" the selectors with +// other meanings can cause warnings (based on compiler settings), but more +// importantly, some of those selector get called as KVC breaks up keypaths. +// So if those selectors are used, using KVC will compile cleanly, but could +// crash as it invokes those selectors with the wrong types of arguments. + +NS_ASSUME_NONNULL_BEGIN + +//%PDDM-EXPAND DECLARE_DICTIONARIES() +// This block of code is generated, do not edit it directly. + +#pragma mark - UInt32 -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32UInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(uint32_t key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32UInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32Int32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32Int32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(uint32_t key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32Int32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32UInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(uint32_t key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32UInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32Int64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32Int64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(uint32_t key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32Int64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32BoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32BoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(uint32_t key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32BoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32FloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32FloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(uint32_t key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32FloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32DoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32DoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(uint32_t key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32DoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32EnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBUInt32EnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(uint32_t key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(uint32_t key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(uint32_t)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt32 -> Object + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt32ObjectDictionary<__covariant ObjectType> : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param objects The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects + forKeys:(const uint32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt32ObjectDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Fetches the object stored under the given key. + * + * @param key Key under which the value is stored, if present. + * + * @return The object if found, nil otherwise. + **/ +- (ObjectType)objectForKey:(uint32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **object**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(uint32_t key, ObjectType object, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt32ObjectDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param object The value to set. + * @param key The key under which to store the value. + **/ +- (void)setObject:(ObjectType)object forKey:(uint32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeObjectForKey:(uint32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32UInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32UInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(int32_t key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32UInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32Int32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32Int32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(int32_t key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32Int32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32UInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32UInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(int32_t key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32UInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32Int64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32Int64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(int32_t key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32Int64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32BoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32BoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(int32_t key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32BoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32FloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32FloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(int32_t key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32FloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32DoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32DoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(int32_t key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32DoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32EnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBInt32EnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(int32_t key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(int32_t key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(int32_t)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int32 -> Object + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt32ObjectDictionary<__covariant ObjectType> : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param objects The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects + forKeys:(const int32_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt32ObjectDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Fetches the object stored under the given key. + * + * @param key Key under which the value is stored, if present. + * + * @return The object if found, nil otherwise. + **/ +- (ObjectType)objectForKey:(int32_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **object**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(int32_t key, ObjectType object, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt32ObjectDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param object The value to set. + * @param key The key under which to store the value. + **/ +- (void)setObject:(ObjectType)object forKey:(int32_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeObjectForKey:(int32_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64UInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(uint64_t key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64UInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64Int32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64Int32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(uint64_t key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64Int32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64UInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(uint64_t key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64UInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64Int64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64Int64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(uint64_t key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64Int64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64BoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64BoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(uint64_t key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64BoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64FloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64FloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(uint64_t key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64FloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64DoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64DoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(uint64_t key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64DoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64EnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBUInt64EnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(uint64_t key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(uint64_t key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(uint64_t)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - UInt64 -> Object + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBUInt64ObjectDictionary<__covariant ObjectType> : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param objects The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects + forKeys:(const uint64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBUInt64ObjectDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Fetches the object stored under the given key. + * + * @param key Key under which the value is stored, if present. + * + * @return The object if found, nil otherwise. + **/ +- (ObjectType)objectForKey:(uint64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **object**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(uint64_t key, ObjectType object, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBUInt64ObjectDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param object The value to set. + * @param key The key under which to store the value. + **/ +- (void)setObject:(ObjectType)object forKey:(uint64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeObjectForKey:(uint64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64UInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64UInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(int64_t key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64UInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64Int32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64Int32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(int64_t key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64Int32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64UInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64UInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(int64_t key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64UInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64Int64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64Int64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(int64_t key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64Int64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64BoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64BoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(int64_t key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64BoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64FloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64FloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(int64_t key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64FloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64DoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64DoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(int64_t key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64DoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64EnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBInt64EnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(int64_t key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(int64_t key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(int64_t)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Int64 -> Object + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBInt64ObjectDictionary<__covariant ObjectType> : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param objects The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects + forKeys:(const int64_t [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBInt64ObjectDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Fetches the object stored under the given key. + * + * @param key Key under which the value is stored, if present. + * + * @return The object if found, nil otherwise. + **/ +- (ObjectType)objectForKey:(int64_t)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **object**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(int64_t key, ObjectType object, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBInt64ObjectDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param object The value to set. + * @param key The key under which to store the value. + **/ +- (void)setObject:(ObjectType)object forKey:(int64_t)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeObjectForKey:(int64_t)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolUInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolUInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(BOOL key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolUInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(BOOL key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolUInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolUInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(BOOL key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolUInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(BOOL key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolBoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolBoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(BOOL key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolBoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolFloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolFloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(BOOL key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolFloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolDoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolDoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(BOOL key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolDoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolEnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBBoolEnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(BOOL key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(BOOL key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBBoolEnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(BOOL)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - Bool -> Object + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBBoolObjectDictionary<__covariant ObjectType> : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param objects The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithObjects:(const ObjectType __nonnull GPB_UNSAFE_UNRETAINED [__nullable])objects + forKeys:(const BOOL [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBBoolObjectDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Fetches the object stored under the given key. + * + * @param key Key under which the value is stored, if present. + * + * @return The object if found, nil otherwise. + **/ +- (ObjectType)objectForKey:(BOOL)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **object**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(BOOL key, ObjectType object, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBBoolObjectDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param object The value to set. + * @param key The key under which to store the value. + **/ +- (void)setObject:(ObjectType)object forKey:(BOOL)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeObjectForKey:(BOOL)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> UInt32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringUInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt32s:(const uint32_t [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringUInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(NSString *key, uint32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringUInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt32:(uint32_t)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt32ForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Int32 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringInt32Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt32s:(const int32_t [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringInt32Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt32:(nullable int32_t *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(NSString *key, int32_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringInt32Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt32:(int32_t)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt32ForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> UInt64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringUInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithUInt64s:(const uint64_t [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringUInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(NSString *key, uint64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringUInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setUInt64:(uint64_t)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeUInt64ForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Int64 + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringInt64Dictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithInt64s:(const int64_t [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringInt64Dictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getInt64:(nullable int64_t *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(NSString *key, int64_t value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringInt64Dictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setInt64:(int64_t)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeInt64ForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Bool + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringBoolDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithBools:(const BOOL [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringBoolDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getBool:(nullable BOOL *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(NSString *key, BOOL value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringBoolDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setBool:(BOOL)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeBoolForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Float + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringFloatDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithFloats:(const float [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringFloatDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getFloat:(nullable float *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(NSString *key, float value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringFloatDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setFloat:(float)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeFloatForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Double + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringDoubleDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; + +/** + * Initializes this dictionary, copying the given values and keys. + * + * @param values The values to be placed in this dictionary. + * @param keys The keys under which to store the values. + * @param count The number of elements to copy into the dictionary. + * + * @return A newly initialized dictionary with a copy of the values and keys. + **/ +- (instancetype)initWithDoubles:(const double [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes this dictionary, copying the entries from the given dictionary. + * + * @param dictionary Dictionary containing the entries to add to this dictionary. + * + * @return A newly initialized dictionary with the entries of the given dictionary. + **/ +- (instancetype)initWithDictionary:(GPBStringDoubleDictionary *)dictionary; + +/** + * Initializes this dictionary with the requested capacity. + * + * @param numItems Number of items needed for this dictionary. + * + * @return A newly initialized dictionary with the requested capacity. + **/ +- (instancetype)initWithCapacity:(NSUInteger)numItems; + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getDouble:(nullable double *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(NSString *key, double value, BOOL *stop))block; + +/** + * Adds the keys and values from another dictionary. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addEntriesFromDictionary:(GPBStringDoubleDictionary *)otherDictionary; + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setDouble:(double)value forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeDoubleForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +#pragma mark - String -> Enum + +/** + * Class used for map fields of + * values. This performs better than boxing into NSNumbers in NSDictionaries. + * + * @note This class is not meant to be subclassed. + **/ +@interface GPBStringEnumDictionary : NSObject + +/** Number of entries stored in this dictionary. */ +@property(nonatomic, readonly) NSUInteger count; +/** The validation function to check if the enums are valid. */ +@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; + +/** + * Initializes a dictionary with the given validation function. + * + * @param func The enum validation function for the dictionary. + * + * @return A newly initialized dictionary. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; + +/** + * Initializes a dictionary with the entries given. + * + * @param func The enum validation function for the dictionary. + * @param values The raw enum values values to be placed in the dictionary. + * @param keys The keys under which to store the values. + * @param count The number of entries to store in the dictionary. + * + * @return A newly initialized dictionary with the keys and values in it. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + rawValues:(const int32_t [__nullable])values + forKeys:(const NSString * __nonnull GPB_UNSAFE_UNRETAINED [__nullable])keys + count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + +/** + * Initializes a dictionary with the entries from the given. + * dictionary. + * + * @param dictionary Dictionary containing the entries to add to the dictionary. + * + * @return A newly initialized dictionary with the entries from the given + * dictionary in it. + **/ +- (instancetype)initWithDictionary:(GPBStringEnumDictionary *)dictionary; + +/** + * Initializes a dictionary with the given capacity. + * + * @param func The enum validation function for the dictionary. + * @param numItems Capacity needed for the dictionary. + * + * @return A newly initialized dictionary with the given capacity. + **/ +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems; + +// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +// is not a valid enumerator as defined by validationFunc. If the actual value is +// desired, use "raw" version of the method. + +/** + * Gets the value for the given key. + * + * @param value Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getEnum:(nullable int32_t *)value forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **value**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(NSString *key, int32_t value, BOOL *stop))block; + +/** + * Gets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param rawValue Pointer into which the value will be set, if found. + * @param key Key under which the value is stored, if present. + * + * @return YES if the key was found and the value was copied, NO otherwise. + **/ +- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(NSString *)key; + +/** + * Enumerates the keys and values on this dictionary with the given block. + * + * @note This method bypass the validationFunc to enable the access of values that + * were not known at the time the binary was compiled. + * + * @param block The block to enumerate with. + * **key**: The key for the current entry. + * **rawValue**: The value for the current entry + * **stop**: A pointer to a boolean that when set stops the enumeration. + **/ +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(NSString *key, int32_t rawValue, BOOL *stop))block; + +/** + * Adds the keys and raw enum values from another dictionary. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param otherDictionary Dictionary containing entries to be added to this + * dictionary. + **/ +- (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary; + +// If value is not a valid enumerator as defined by validationFunc, these +// methods will assert in debug, and will log in release and assign the value +// to the default value. Use the rawValue methods below to assign non enumerator +// values. + +/** + * Sets the value for the given key. + * + * @param value The value to set. + * @param key The key under which to store the value. + **/ +- (void)setEnum:(int32_t)value forKey:(NSString *)key; + +/** + * Sets the raw enum value for the given key. + * + * @note This method bypass the validationFunc to enable the setting of values that + * were not known at the time the binary was compiled. + * + * @param rawValue The raw enum value to set. + * @param key The key under which to store the raw enum value. + **/ +- (void)setRawValue:(int32_t)rawValue forKey:(NSString *)key; + +/** + * Removes the entry for the given key. + * + * @param aKey Key to be removed from this dictionary. + **/ +- (void)removeEnumForKey:(NSString *)aKey; + +/** + * Removes all entries in this dictionary. + **/ +- (void)removeAll; + +@end + +//%PDDM-EXPAND-END DECLARE_DICTIONARIES() + +NS_ASSUME_NONNULL_END + +//%PDDM-DEFINE DECLARE_DICTIONARIES() +//%DICTIONARY_INTERFACES_FOR_POD_KEY(UInt32, uint32_t) +//%DICTIONARY_INTERFACES_FOR_POD_KEY(Int32, int32_t) +//%DICTIONARY_INTERFACES_FOR_POD_KEY(UInt64, uint64_t) +//%DICTIONARY_INTERFACES_FOR_POD_KEY(Int64, int64_t) +//%DICTIONARY_INTERFACES_FOR_POD_KEY(Bool, BOOL) +//%DICTIONARY_POD_INTERFACES_FOR_KEY(String, NSString, *, OBJECT) +//%PDDM-DEFINE DICTIONARY_INTERFACES_FOR_POD_KEY(KEY_NAME, KEY_TYPE) +//%DICTIONARY_POD_INTERFACES_FOR_KEY(KEY_NAME, KEY_TYPE, , POD) +//%DICTIONARY_POD_KEY_TO_OBJECT_INTERFACE(KEY_NAME, KEY_TYPE, Object, ObjectType) +//%PDDM-DEFINE DICTIONARY_POD_INTERFACES_FOR_KEY(KEY_NAME, KEY_TYPE, KisP, KHELPER) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, UInt32, uint32_t) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Int32, int32_t) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, UInt64, uint64_t) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Int64, int64_t) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Bool, BOOL) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Float, float) +//%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Double, double) +//%DICTIONARY_KEY_TO_ENUM_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Enum, int32_t) +//%PDDM-DEFINE DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, POD, VALUE_NAME, value) +//%PDDM-DEFINE DICTIONARY_POD_KEY_TO_OBJECT_INTERFACE(KEY_NAME, KEY_TYPE, VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, , POD, VALUE_NAME, VALUE_TYPE, OBJECT, Object, object) +//%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME) +//%/** +//% * Gets the value for the given key. +//% * +//% * @param value Pointer into which the value will be set, if found. +//% * @param key Key under which the value is stored, if present. +//% * +//% * @return YES if the key was found and the value was copied, NO otherwise. +//% **/ +//%- (BOOL)get##VNAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key; +//%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_TYPE, VNAME) +//%/** +//% * Fetches the object stored under the given key. +//% * +//% * @param key Key under which the value is stored, if present. +//% * +//% * @return The object if found, nil otherwise. +//% **/ +//%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key; +//%PDDM-DEFINE VALUE_FOR_KEY_Enum(KEY_TYPE, VALUE_TYPE, VNAME) +//%VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME) +//%PDDM-DEFINE ARRAY_ARG_MODIFIERPOD() +// Nothing +//%PDDM-DEFINE ARRAY_ARG_MODIFIEREnum() +// Nothing +//%PDDM-DEFINE ARRAY_ARG_MODIFIEROBJECT() +//%__nonnull GPB_UNSAFE_UNRETAINED ## +//%PDDM-DEFINE DICTIONARY_CLASS_DECLPOD(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary +//%PDDM-DEFINE DICTIONARY_CLASS_DECLEnum(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary +//%PDDM-DEFINE DICTIONARY_CLASS_DECLOBJECT(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary<__covariant VALUE_TYPE> +//%PDDM-DEFINE DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%/** +//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##> +//% * values. This performs better than boxing into NSNumbers in NSDictionaries. +//% * +//% * @note This class is not meant to be subclassed. +//% **/ +//%@interface DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) : NSObject +//% +//%/** Number of entries stored in this dictionary. */ +//%@property(nonatomic, readonly) NSUInteger count; +//% +//%/** +//% * Initializes this dictionary, copying the given values and keys. +//% * +//% * @param ##VNAME_VAR##s The values to be placed in this dictionary. +//% * @param keys ##VNAME_VAR$S## The keys under which to store the values. +//% * @param count ##VNAME_VAR$S## The number of elements to copy into the dictionary. +//% * +//% * @return A newly initialized dictionary with a copy of the values and keys. +//% **/ +//%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])##VNAME_VAR##s +//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys +//% ##VNAME$S## count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; +//% +//%/** +//% * Initializes this dictionary, copying the entries from the given dictionary. +//% * +//% * @param dictionary Dictionary containing the entries to add to this dictionary. +//% * +//% * @return A newly initialized dictionary with the entries of the given dictionary. +//% **/ +//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; +//% +//%/** +//% * Initializes this dictionary with the requested capacity. +//% * +//% * @param numItems Number of items needed for this dictionary. +//% * +//% * @return A newly initialized dictionary with the requested capacity. +//% **/ +//%- (instancetype)initWithCapacity:(NSUInteger)numItems; +//% +//%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) +//% +//%/** +//% * Adds the keys and values from another dictionary. +//% * +//% * @param otherDictionary Dictionary containing entries to be added to this +//% * dictionary. +//% **/ +//%- (void)addEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary; +//% +//%DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) +//% +//%@end +//% + +//%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_KEY_TO_ENUM_INTERFACE2(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, Enum) +//%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_INTERFACE2(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%/** +//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##> +//% * values. This performs better than boxing into NSNumbers in NSDictionaries. +//% * +//% * @note This class is not meant to be subclassed. +//% **/ +//%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary : NSObject +//% +//%/** Number of entries stored in this dictionary. */ +//%@property(nonatomic, readonly) NSUInteger count; +//%/** The validation function to check if the enums are valid. */ +//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; +//% +//%/** +//% * Initializes a dictionary with the given validation function. +//% * +//% * @param func The enum validation function for the dictionary. +//% * +//% * @return A newly initialized dictionary. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; +//% +//%/** +//% * Initializes a dictionary with the entries given. +//% * +//% * @param func The enum validation function for the dictionary. +//% * @param values The raw enum values values to be placed in the dictionary. +//% * @param keys The keys under which to store the values. +//% * @param count The number of entries to store in the dictionary. +//% * +//% * @return A newly initialized dictionary with the keys and values in it. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[__nullable])values +//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[__nullable])keys +//% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; +//% +//%/** +//% * Initializes a dictionary with the entries from the given. +//% * dictionary. +//% * +//% * @param dictionary Dictionary containing the entries to add to the dictionary. +//% * +//% * @return A newly initialized dictionary with the entries from the given +//% * dictionary in it. +//% **/ +//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; +//% +//%/** +//% * Initializes a dictionary with the given capacity. +//% * +//% * @param func The enum validation function for the dictionary. +//% * @param numItems Capacity needed for the dictionary. +//% * +//% * @return A newly initialized dictionary with the given capacity. +//% **/ +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% capacity:(NSUInteger)numItems; +//% +//%// These will return kGPBUnrecognizedEnumeratorValue if the value for the key +//%// is not a valid enumerator as defined by validationFunc. If the actual value is +//%// desired, use "raw" version of the method. +//% +//%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, Enum, value) +//% +//%/** +//% * Gets the raw enum value for the given key. +//% * +//% * @note This method bypass the validationFunc to enable the access of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param rawValue Pointer into which the value will be set, if found. +//% * @param key Key under which the value is stored, if present. +//% * +//% * @return YES if the key was found and the value was copied, NO otherwise. +//% **/ +//%- (BOOL)getRawValue:(nullable VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key; +//% +//%/** +//% * Enumerates the keys and values on this dictionary with the given block. +//% * +//% * @note This method bypass the validationFunc to enable the access of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param block The block to enumerate with. +//% * **key**: The key for the current entry. +//% * **rawValue**: The value for the current entry +//% * **stop**: A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateKeysAndRawValuesUsingBlock: +//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE rawValue, BOOL *stop))block; +//% +//%/** +//% * Adds the keys and raw enum values from another dictionary. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param otherDictionary Dictionary containing entries to be added to this +//% * dictionary. +//% **/ +//%- (void)addRawEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary; +//% +//%// If value is not a valid enumerator as defined by validationFunc, these +//%// methods will assert in debug, and will log in release and assign the value +//%// to the default value. Use the rawValue methods below to assign non enumerator +//%// values. +//% +//%DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, Enum, value) +//% +//%@end +//% + +//%PDDM-DEFINE DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) +//%VALUE_FOR_KEY_##VHELPER(KEY_TYPE##KisP$S##KisP, VALUE_TYPE, VNAME) +//% +//%/** +//% * Enumerates the keys and values on this dictionary with the given block. +//% * +//% * @param block The block to enumerate with. +//% * **key**: ##VNAME_VAR$S## The key for the current entry. +//% * **VNAME_VAR**: The value for the current entry +//% * **stop**: ##VNAME_VAR$S## A pointer to a boolean that when set stops the enumeration. +//% **/ +//%- (void)enumerateKeysAnd##VNAME##sUsingBlock: +//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block; + +//%PDDM-DEFINE DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) +//%/** +//% * Sets the value for the given key. +//% * +//% * @param ##VNAME_VAR The value to set. +//% * @param key ##VNAME_VAR$S## The key under which to store the value. +//% **/ +//%- (void)set##VNAME##:(VALUE_TYPE)##VNAME_VAR forKey:(KEY_TYPE##KisP$S##KisP)key; +//%DICTIONARY_EXTRA_MUTABLE_METHODS_##VHELPER(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) +//%/** +//% * Removes the entry for the given key. +//% * +//% * @param aKey Key to be removed from this dictionary. +//% **/ +//%- (void)remove##VNAME##ForKey:(KEY_TYPE##KisP$S##KisP)aKey; +//% +//%/** +//% * Removes all entries in this dictionary. +//% **/ +//%- (void)removeAll; + +//%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_POD(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) +// Empty +//%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_OBJECT(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) +// Empty +//%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_Enum(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) +//% +//%/** +//% * Sets the raw enum value for the given key. +//% * +//% * @note This method bypass the validationFunc to enable the setting of values that +//% * were not known at the time the binary was compiled. +//% * +//% * @param rawValue The raw enum value to set. +//% * @param key The key under which to store the raw enum value. +//% **/ +//%- (void)setRawValue:(VALUE_TYPE)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key; +//% diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDictionary.m b/My Mind/Pods/Protobuf/objectivec/GPBDictionary.m new file mode 100644 index 0000000..cedf5e5 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDictionary.m @@ -0,0 +1,12120 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBDictionary_PackagePrivate.h" + +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream_PackagePrivate.h" +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" + +// ------------------------------ NOTE ------------------------------ +// At the moment, this is all using NSNumbers in NSDictionaries under +// the hood, but it is all hidden so we can come back and optimize +// with direct CFDictionary usage later. The reason that wasn't +// done yet is needing to support 32bit iOS builds. Otherwise +// it would be pretty simple to store all this data in CFDictionaries +// directly. +// ------------------------------------------------------------------ + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +// Used to include code only visible to specific versions of the static +// analyzer. Useful for wrapping code that only exists to silence the analyzer. +// Determine the values you want to use for BEGIN_APPLE_BUILD_VERSION, +// END_APPLE_BUILD_VERSION using: +// xcrun clang -dM -E -x c /dev/null | grep __apple_build_version__ +// Example usage: +// #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif +#define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ + (defined(__clang_analyzer__) && \ + (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \ + __apple_build_version__ <= END_APPLE_BUILD_VERSION)) + +enum { + kMapKeyFieldNumber = 1, + kMapValueFieldNumber = 2, +}; + +static BOOL DictDefault_IsValidValue(int32_t value) { + // Anything but the bad value marker is allowed. + return (value != kGPBUnrecognizedEnumeratorValue); +} + +//%PDDM-DEFINE SERIALIZE_SUPPORT_2_TYPE(VALUE_NAME, VALUE_TYPE, GPBDATATYPE_NAME1, GPBDATATYPE_NAME2) +//%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { +//% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { +//% return GPBCompute##GPBDATATYPE_NAME1##Size(fieldNum, value); +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { +//% return GPBCompute##GPBDATATYPE_NAME2##Size(fieldNum, value); +//% } else { +//% NSCAssert(NO, @"Unexpected type %d", dataType); +//% return 0; +//% } +//%} +//% +//%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { +//% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { +//% [stream write##GPBDATATYPE_NAME1##:fieldNum value:value]; +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { +//% [stream write##GPBDATATYPE_NAME2##:fieldNum value:value]; +//% } else { +//% NSCAssert(NO, @"Unexpected type %d", dataType); +//% } +//%} +//% +//%PDDM-DEFINE SERIALIZE_SUPPORT_3_TYPE(VALUE_NAME, VALUE_TYPE, GPBDATATYPE_NAME1, GPBDATATYPE_NAME2, GPBDATATYPE_NAME3) +//%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { +//% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { +//% return GPBCompute##GPBDATATYPE_NAME1##Size(fieldNum, value); +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { +//% return GPBCompute##GPBDATATYPE_NAME2##Size(fieldNum, value); +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME3) { +//% return GPBCompute##GPBDATATYPE_NAME3##Size(fieldNum, value); +//% } else { +//% NSCAssert(NO, @"Unexpected type %d", dataType); +//% return 0; +//% } +//%} +//% +//%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { +//% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { +//% [stream write##GPBDATATYPE_NAME1##:fieldNum value:value]; +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { +//% [stream write##GPBDATATYPE_NAME2##:fieldNum value:value]; +//% } else if (dataType == GPBDataType##GPBDATATYPE_NAME3) { +//% [stream write##GPBDATATYPE_NAME3##:fieldNum value:value]; +//% } else { +//% NSCAssert(NO, @"Unexpected type %d", dataType); +//% } +//%} +//% +//%PDDM-DEFINE SIMPLE_SERIALIZE_SUPPORT(VALUE_NAME, VALUE_TYPE, VisP) +//%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE VisP##value, uint32_t fieldNum, GPBDataType dataType) { +//% NSCAssert(dataType == GPBDataType##VALUE_NAME, @"bad type: %d", dataType); +//% #pragma unused(dataType) // For when asserts are off in release. +//% return GPBCompute##VALUE_NAME##Size(fieldNum, value); +//%} +//% +//%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE VisP##value, uint32_t fieldNum, GPBDataType dataType) { +//% NSCAssert(dataType == GPBDataType##VALUE_NAME, @"bad type: %d", dataType); +//% #pragma unused(dataType) // For when asserts are off in release. +//% [stream write##VALUE_NAME##:fieldNum value:value]; +//%} +//% +//%PDDM-DEFINE SERIALIZE_SUPPORT_HELPERS() +//%SERIALIZE_SUPPORT_3_TYPE(Int32, int32_t, Int32, SInt32, SFixed32) +//%SERIALIZE_SUPPORT_2_TYPE(UInt32, uint32_t, UInt32, Fixed32) +//%SERIALIZE_SUPPORT_3_TYPE(Int64, int64_t, Int64, SInt64, SFixed64) +//%SERIALIZE_SUPPORT_2_TYPE(UInt64, uint64_t, UInt64, Fixed64) +//%SIMPLE_SERIALIZE_SUPPORT(Bool, BOOL, ) +//%SIMPLE_SERIALIZE_SUPPORT(Enum, int32_t, ) +//%SIMPLE_SERIALIZE_SUPPORT(Float, float, ) +//%SIMPLE_SERIALIZE_SUPPORT(Double, double, ) +//%SIMPLE_SERIALIZE_SUPPORT(String, NSString, *) +//%SERIALIZE_SUPPORT_3_TYPE(Object, id, Message, String, Bytes) +//%PDDM-EXPAND SERIALIZE_SUPPORT_HELPERS() +// This block of code is generated, do not edit it directly. + +static size_t ComputeDictInt32FieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeInt32) { + return GPBComputeInt32Size(fieldNum, value); + } else if (dataType == GPBDataTypeSInt32) { + return GPBComputeSInt32Size(fieldNum, value); + } else if (dataType == GPBDataTypeSFixed32) { + return GPBComputeSFixed32Size(fieldNum, value); + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + return 0; + } +} + +static void WriteDictInt32Field(GPBCodedOutputStream *stream, int32_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeInt32) { + [stream writeInt32:fieldNum value:value]; + } else if (dataType == GPBDataTypeSInt32) { + [stream writeSInt32:fieldNum value:value]; + } else if (dataType == GPBDataTypeSFixed32) { + [stream writeSFixed32:fieldNum value:value]; + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + } +} + +static size_t ComputeDictUInt32FieldSize(uint32_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeUInt32) { + return GPBComputeUInt32Size(fieldNum, value); + } else if (dataType == GPBDataTypeFixed32) { + return GPBComputeFixed32Size(fieldNum, value); + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + return 0; + } +} + +static void WriteDictUInt32Field(GPBCodedOutputStream *stream, uint32_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeUInt32) { + [stream writeUInt32:fieldNum value:value]; + } else if (dataType == GPBDataTypeFixed32) { + [stream writeFixed32:fieldNum value:value]; + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + } +} + +static size_t ComputeDictInt64FieldSize(int64_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeInt64) { + return GPBComputeInt64Size(fieldNum, value); + } else if (dataType == GPBDataTypeSInt64) { + return GPBComputeSInt64Size(fieldNum, value); + } else if (dataType == GPBDataTypeSFixed64) { + return GPBComputeSFixed64Size(fieldNum, value); + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + return 0; + } +} + +static void WriteDictInt64Field(GPBCodedOutputStream *stream, int64_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeInt64) { + [stream writeInt64:fieldNum value:value]; + } else if (dataType == GPBDataTypeSInt64) { + [stream writeSInt64:fieldNum value:value]; + } else if (dataType == GPBDataTypeSFixed64) { + [stream writeSFixed64:fieldNum value:value]; + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + } +} + +static size_t ComputeDictUInt64FieldSize(uint64_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeUInt64) { + return GPBComputeUInt64Size(fieldNum, value); + } else if (dataType == GPBDataTypeFixed64) { + return GPBComputeFixed64Size(fieldNum, value); + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + return 0; + } +} + +static void WriteDictUInt64Field(GPBCodedOutputStream *stream, uint64_t value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeUInt64) { + [stream writeUInt64:fieldNum value:value]; + } else if (dataType == GPBDataTypeFixed64) { + [stream writeFixed64:fieldNum value:value]; + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + } +} + +static size_t ComputeDictBoolFieldSize(BOOL value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeBool, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + return GPBComputeBoolSize(fieldNum, value); +} + +static void WriteDictBoolField(GPBCodedOutputStream *stream, BOOL value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeBool, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + [stream writeBool:fieldNum value:value]; +} + +static size_t ComputeDictEnumFieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeEnum, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + return GPBComputeEnumSize(fieldNum, value); +} + +static void WriteDictEnumField(GPBCodedOutputStream *stream, int32_t value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeEnum, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + [stream writeEnum:fieldNum value:value]; +} + +static size_t ComputeDictFloatFieldSize(float value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeFloat, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + return GPBComputeFloatSize(fieldNum, value); +} + +static void WriteDictFloatField(GPBCodedOutputStream *stream, float value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeFloat, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + [stream writeFloat:fieldNum value:value]; +} + +static size_t ComputeDictDoubleFieldSize(double value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeDouble, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + return GPBComputeDoubleSize(fieldNum, value); +} + +static void WriteDictDoubleField(GPBCodedOutputStream *stream, double value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeDouble, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + [stream writeDouble:fieldNum value:value]; +} + +static size_t ComputeDictStringFieldSize(NSString *value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeString, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + return GPBComputeStringSize(fieldNum, value); +} + +static void WriteDictStringField(GPBCodedOutputStream *stream, NSString *value, uint32_t fieldNum, GPBDataType dataType) { + NSCAssert(dataType == GPBDataTypeString, @"bad type: %d", dataType); + #pragma unused(dataType) // For when asserts are off in release. + [stream writeString:fieldNum value:value]; +} + +static size_t ComputeDictObjectFieldSize(id value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeMessage) { + return GPBComputeMessageSize(fieldNum, value); + } else if (dataType == GPBDataTypeString) { + return GPBComputeStringSize(fieldNum, value); + } else if (dataType == GPBDataTypeBytes) { + return GPBComputeBytesSize(fieldNum, value); + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + return 0; + } +} + +static void WriteDictObjectField(GPBCodedOutputStream *stream, id value, uint32_t fieldNum, GPBDataType dataType) { + if (dataType == GPBDataTypeMessage) { + [stream writeMessage:fieldNum value:value]; + } else if (dataType == GPBDataTypeString) { + [stream writeString:fieldNum value:value]; + } else if (dataType == GPBDataTypeBytes) { + [stream writeBytes:fieldNum value:value]; + } else { + NSCAssert(NO, @"Unexpected type %d", dataType); + } +} + +//%PDDM-EXPAND-END SERIALIZE_SUPPORT_HELPERS() + +size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { + GPBDataType mapValueType = GPBGetFieldDataType(field); + size_t result = 0; + NSString *key; + NSEnumerator *keys = [dict keyEnumerator]; + while ((key = [keys nextObject])) { + id obj = dict[key]; + size_t msgSize = GPBComputeStringSize(kMapKeyFieldNumber, key); + msgSize += ComputeDictObjectFieldSize(obj, kMapValueFieldNumber, mapValueType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * dict.count; + return result; +} + +void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream, + NSDictionary *dict, + GPBFieldDescriptor *field) { + NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); + GPBDataType mapValueType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSString *key; + NSEnumerator *keys = [dict keyEnumerator]; + while ((key = [keys nextObject])) { + id obj = dict[key]; + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = GPBComputeStringSize(kMapKeyFieldNumber, key); + msgSize += ComputeDictObjectFieldSize(obj, kMapValueFieldNumber, mapValueType); + + // Write the size and fields. + [outputStream writeInt32NoTag:(int32_t)msgSize]; + [outputStream writeString:kMapKeyFieldNumber value:key]; + WriteDictObjectField(outputStream, obj, kMapValueFieldNumber, mapValueType); + } +} + +BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { + NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); + NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type"); + #pragma unused(field) // For when asserts are off in release. + GPBMessage *msg; + NSEnumerator *objects = [dict objectEnumerator]; + while ((msg = [objects nextObject])) { + if (!msg.initialized) { + return NO; + } + } + return YES; +} + +// Note: if the type is an object, it the retain pass back to the caller. +static void ReadValue(GPBCodedInputStream *stream, + GPBGenericValue *valueToFill, + GPBDataType type, + GPBExtensionRegistry *registry, + GPBFieldDescriptor *field) { + switch (type) { + case GPBDataTypeBool: + valueToFill->valueBool = GPBCodedInputStreamReadBool(&stream->state_); + break; + case GPBDataTypeFixed32: + valueToFill->valueUInt32 = GPBCodedInputStreamReadFixed32(&stream->state_); + break; + case GPBDataTypeSFixed32: + valueToFill->valueInt32 = GPBCodedInputStreamReadSFixed32(&stream->state_); + break; + case GPBDataTypeFloat: + valueToFill->valueFloat = GPBCodedInputStreamReadFloat(&stream->state_); + break; + case GPBDataTypeFixed64: + valueToFill->valueUInt64 = GPBCodedInputStreamReadFixed64(&stream->state_); + break; + case GPBDataTypeSFixed64: + valueToFill->valueInt64 = GPBCodedInputStreamReadSFixed64(&stream->state_); + break; + case GPBDataTypeDouble: + valueToFill->valueDouble = GPBCodedInputStreamReadDouble(&stream->state_); + break; + case GPBDataTypeInt32: + valueToFill->valueInt32 = GPBCodedInputStreamReadInt32(&stream->state_); + break; + case GPBDataTypeInt64: + valueToFill->valueInt64 = GPBCodedInputStreamReadInt64(&stream->state_); + break; + case GPBDataTypeSInt32: + valueToFill->valueInt32 = GPBCodedInputStreamReadSInt32(&stream->state_); + break; + case GPBDataTypeSInt64: + valueToFill->valueInt64 = GPBCodedInputStreamReadSInt64(&stream->state_); + break; + case GPBDataTypeUInt32: + valueToFill->valueUInt32 = GPBCodedInputStreamReadUInt32(&stream->state_); + break; + case GPBDataTypeUInt64: + valueToFill->valueUInt64 = GPBCodedInputStreamReadUInt64(&stream->state_); + break; + case GPBDataTypeBytes: + [valueToFill->valueData release]; + valueToFill->valueData = GPBCodedInputStreamReadRetainedBytes(&stream->state_); + break; + case GPBDataTypeString: + [valueToFill->valueString release]; + valueToFill->valueString = GPBCodedInputStreamReadRetainedString(&stream->state_); + break; + case GPBDataTypeMessage: { + GPBMessage *message = [[field.msgClass alloc] init]; + [stream readMessage:message extensionRegistry:registry]; + [valueToFill->valueMessage release]; + valueToFill->valueMessage = message; + break; + } + case GPBDataTypeGroup: + NSCAssert(NO, @"Can't happen"); + break; + case GPBDataTypeEnum: + valueToFill->valueEnum = GPBCodedInputStreamReadEnum(&stream->state_); + break; + } +} + +void GPBDictionaryReadEntry(id mapDictionary, + GPBCodedInputStream *stream, + GPBExtensionRegistry *registry, + GPBFieldDescriptor *field, + GPBMessage *parentMessage) { + GPBDataType keyDataType = field.mapKeyDataType; + GPBDataType valueDataType = GPBGetFieldDataType(field); + + GPBGenericValue key; + GPBGenericValue value; + // Zero them (but pick up any enum default for proto2). + key.valueString = value.valueString = nil; + if (valueDataType == GPBDataTypeEnum) { + value = field.defaultValue; + } + + GPBCodedInputStreamState *state = &stream->state_; + uint32_t keyTag = + GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO)); + uint32_t valueTag = + GPBWireFormatMakeTag(kMapValueFieldNumber, GPBWireFormatForType(valueDataType, NO)); + + BOOL hitError = NO; + while (YES) { + uint32_t tag = GPBCodedInputStreamReadTag(state); + if (tag == keyTag) { + ReadValue(stream, &key, keyDataType, registry, field); + } else if (tag == valueTag) { + ReadValue(stream, &value, valueDataType, registry, field); + } else if (tag == 0) { + // zero signals EOF / limit reached + break; + } else { // Unknown + if (![stream skipField:tag]){ + hitError = YES; + break; + } + } + } + + if (!hitError) { + // Handle the special defaults and/or missing key/value. + if ((keyDataType == GPBDataTypeString) && (key.valueString == nil)) { + key.valueString = [@"" retain]; + } + if (GPBDataTypeIsObject(valueDataType) && value.valueString == nil) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wswitch-enum" + switch (valueDataType) { + case GPBDataTypeString: + value.valueString = [@"" retain]; + break; + case GPBDataTypeBytes: + value.valueData = [GPBEmptyNSData() retain]; + break; +#if defined(__clang_analyzer__) + case GPBDataTypeGroup: + // Maps can't really have Groups as the value type, but this case is needed + // so the analyzer won't report the posibility of send nil in for the value + // in the NSMutableDictionary case below. +#endif + case GPBDataTypeMessage: { + value.valueMessage = [[field.msgClass alloc] init]; + break; + } + default: + // Nothing + break; + } +#pragma clang diagnostic pop + } + + if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { +#if GPB_STATIC_ANALYZER_ONLY(6020053, 7000181) + // Limited to Xcode 6.4 - 7.2, are known to fail here. The upper end can + // be raised as needed for new Xcodes. + // + // This is only needed on a "shallow" analyze; on a "deep" analyze, the + // existing code path gets this correct. In shallow, the analyzer decides + // GPBDataTypeIsObject(valueDataType) is both false and true on a single + // path through this function, allowing nil to be used for the + // setObject:forKey:. + if (value.valueString == nil) { + value.valueString = [@"" retain]; + } +#endif + // mapDictionary is an NSMutableDictionary + [(NSMutableDictionary *)mapDictionary setObject:value.valueString + forKey:key.valueString]; + } else { + if (valueDataType == GPBDataTypeEnum) { + if (GPBHasPreservingUnknownEnumSemantics([parentMessage descriptor].file.syntax) || + [field isValidEnumValue:value.valueEnum]) { + [mapDictionary setGPBGenericValue:&value forGPBGenericValueKey:&key]; + } else { + NSData *data = [mapDictionary serializedDataForUnknownValue:value.valueEnum + forKey:&key + keyDataType:keyDataType]; + [parentMessage addUnknownMapEntry:GPBFieldNumber(field) value:data]; + } + } else { + [mapDictionary setGPBGenericValue:&value forGPBGenericValueKey:&key]; + } + } + } + + if (GPBDataTypeIsObject(keyDataType)) { + [key.valueString release]; + } + if (GPBDataTypeIsObject(valueDataType)) { + [value.valueString release]; + } +} + +// +// Macros for the common basic cases. +// + +//%PDDM-DEFINE DICTIONARY_IMPL_FOR_POD_KEY(KEY_NAME, KEY_TYPE) +//%DICTIONARY_POD_IMPL_FOR_KEY(KEY_NAME, KEY_TYPE, , POD) +//%DICTIONARY_POD_KEY_TO_OBJECT_IMPL(KEY_NAME, KEY_TYPE, Object, id) + +//%PDDM-DEFINE DICTIONARY_POD_IMPL_FOR_KEY(KEY_NAME, KEY_TYPE, KisP, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, UInt32, uint32_t, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Int32, int32_t, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, UInt64, uint64_t, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Int64, int64_t, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Bool, BOOL, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Float, float, KHELPER) +//%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Double, double, KHELPER) +//%DICTIONARY_KEY_TO_ENUM_IMPL(KEY_NAME, KEY_TYPE, KisP, Enum, int32_t, KHELPER) + +//%PDDM-DEFINE DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER) +//%DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, POD, VALUE_NAME, value) + +//%PDDM-DEFINE DICTIONARY_POD_KEY_TO_OBJECT_IMPL(KEY_NAME, KEY_TYPE, VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, , VALUE_NAME, VALUE_TYPE, POD, OBJECT, Object, object) + +//%PDDM-DEFINE DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%@implementation GPB##KEY_NAME##VALUE_NAME##Dictionary { +//% @package +//% NSMutableDictionary *_dictionary; +//%} +//% +//%- (instancetype)init { +//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; +//%} +//% +//%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s +//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP [])keys +//% ##VNAME$S## count:(NSUInteger)count { +//% self = [super init]; +//% if (self) { +//% _dictionary = [[NSMutableDictionary alloc] init]; +//% if (count && VNAME_VAR##s && keys) { +//% for (NSUInteger i = 0; i < count; ++i) { +//%DICTIONARY_VALIDATE_VALUE_##VHELPER(VNAME_VAR##s[i], ______)##DICTIONARY_VALIDATE_KEY_##KHELPER(keys[i], ______) [_dictionary setObject:WRAPPED##VHELPER(VNAME_VAR##s[i]) forKey:WRAPPED##KHELPER(keys[i])]; +//% } +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { +//% self = [self initWith##VNAME##s:NULL forKeys:NULL count:0]; +//% if (self) { +//% if (dictionary) { +//% [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithCapacity:(NSUInteger)numItems { +//% #pragma unused(numItems) +//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; +//%} +//% +//%DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ) +//% +//%VALUE_FOR_KEY_##VHELPER(KEY_TYPE##KisP$S##KisP, VALUE_NAME, VALUE_TYPE, KHELPER) +//% +//%DICTIONARY_MUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ) +//% +//%@end +//% + +//%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER) +//%DICTIONARY_KEY_TO_ENUM_IMPL2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, POD) +//%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_IMPL2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%@implementation GPB##KEY_NAME##VALUE_NAME##Dictionary { +//% @package +//% NSMutableDictionary *_dictionary; +//% GPBEnumValidationFunc _validationFunc; +//%} +//% +//%@synthesize validationFunc = _validationFunc; +//% +//%- (instancetype)init { +//% return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +//%} +//% +//%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { +//% return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +//%} +//% +//%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func +//% rawValues:(const VALUE_TYPE [])rawValues +//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys +//% count:(NSUInteger)count { +//% self = [super init]; +//% if (self) { +//% _dictionary = [[NSMutableDictionary alloc] init]; +//% _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); +//% if (count && rawValues && keys) { +//% for (NSUInteger i = 0; i < count; ++i) { +//%DICTIONARY_VALIDATE_KEY_##KHELPER(keys[i], ______) [_dictionary setObject:WRAPPED##VHELPER(rawValues[i]) forKey:WRAPPED##KHELPER(keys[i])]; +//% } +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { +//% self = [self initWithValidationFunction:dictionary.validationFunc +//% rawValues:NULL +//% forKeys:NULL +//% count:0]; +//% if (self) { +//% if (dictionary) { +//% [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func +//% capacity:(NSUInteger)numItems { +//% #pragma unused(numItems) +//% return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +//%} +//% +//%DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, Value, value, Raw) +//% +//%- (BOOL)getEnum:(VALUE_TYPE *)value forKey:(KEY_TYPE##KisP$S##KisP)key { +//% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; +//% if (wrapped && value) { +//% VALUE_TYPE result = UNWRAP##VALUE_NAME(wrapped); +//% if (!_validationFunc(result)) { +//% result = kGPBUnrecognizedEnumeratorValue; +//% } +//% *value = result; +//% } +//% return (wrapped != NULL); +//%} +//% +//%- (BOOL)getRawValue:(VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key { +//% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; +//% if (wrapped && rawValue) { +//% *rawValue = UNWRAP##VALUE_NAME(wrapped); +//% } +//% return (wrapped != NULL); +//%} +//% +//%- (void)enumerateKeysAndEnumsUsingBlock: +//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE value, BOOL *stop))block { +//% GPBEnumValidationFunc func = _validationFunc; +//% BOOL stop = NO; +//% NSEnumerator *keys = [_dictionary keyEnumerator]; +//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey; +//% while ((aKey = [keys nextObject])) { +//% ENUM_TYPE##VHELPER(VALUE_TYPE)##aValue = _dictionary[aKey]; +//% VALUE_TYPE unwrapped = UNWRAP##VALUE_NAME(aValue); +//% if (!func(unwrapped)) { +//% unwrapped = kGPBUnrecognizedEnumeratorValue; +//% } +//% block(UNWRAP##KEY_NAME(aKey), unwrapped, &stop); +//% if (stop) { +//% break; +//% } +//% } +//%} +//% +//%DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, Value, Enum, value, Raw) +//% +//%- (void)setEnum:(VALUE_TYPE)value forKey:(KEY_TYPE##KisP$S##KisP)key { +//%DICTIONARY_VALIDATE_KEY_##KHELPER(key, ) if (!_validationFunc(value)) { +//% [NSException raise:NSInvalidArgumentException +//% format:@"GPB##KEY_NAME##VALUE_NAME##Dictionary: Attempt to set an unknown enum value (%d)", +//% value]; +//% } +//% +//% [_dictionary setObject:WRAPPED##VHELPER(value) forKey:WRAPPED##KHELPER(key)]; +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//%} +//% +//%@end +//% + +//%PDDM-DEFINE DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ACCESSOR_NAME) +//%- (void)dealloc { +//% NSAssert(!_autocreator, +//% @"%@: Autocreator must be cleared before release, autocreator: %@", +//% [self class], _autocreator); +//% [_dictionary release]; +//% [super dealloc]; +//%} +//% +//%- (instancetype)copyWithZone:(NSZone *)zone { +//% return [[GPB##KEY_NAME##VALUE_NAME##Dictionary allocWithZone:zone] initWithDictionary:self]; +//%} +//% +//%- (BOOL)isEqual:(id)other { +//% if (self == other) { +//% return YES; +//% } +//% if (![other isKindOfClass:[GPB##KEY_NAME##VALUE_NAME##Dictionary class]]) { +//% return NO; +//% } +//% GPB##KEY_NAME##VALUE_NAME##Dictionary *otherDictionary = other; +//% return [_dictionary isEqual:otherDictionary->_dictionary]; +//%} +//% +//%- (NSUInteger)hash { +//% return _dictionary.count; +//%} +//% +//%- (NSString *)description { +//% return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +//%} +//% +//%- (NSUInteger)count { +//% return _dictionary.count; +//%} +//% +//%- (void)enumerateKeysAnd##ACCESSOR_NAME##VNAME##sUsingBlock: +//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block { +//% BOOL stop = NO; +//% NSDictionary *internal = _dictionary; +//% NSEnumerator *keys = [internal keyEnumerator]; +//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey; +//% while ((aKey = [keys nextObject])) { +//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey]; +//% block(UNWRAP##KEY_NAME(aKey), UNWRAP##VALUE_NAME(a##VNAME_VAR$u), &stop); +//% if (stop) { +//% break; +//% } +//% } +//%} +//% +//%EXTRA_METHODS_##VHELPER(KEY_NAME, VALUE_NAME)- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { +//% NSDictionary *internal = _dictionary; +//% NSUInteger count = internal.count; +//% if (count == 0) { +//% return 0; +//% } +//% +//% GPBDataType valueDataType = GPBGetFieldDataType(field); +//% GPBDataType keyDataType = field.mapKeyDataType; +//% size_t result = 0; +//% NSEnumerator *keys = [internal keyEnumerator]; +//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey; +//% while ((aKey = [keys nextObject])) { +//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey]; +//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType); +//% msgSize += ComputeDict##VALUE_NAME##FieldSize(UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType); +//% result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; +//% } +//% size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); +//% result += tagSize * count; +//% return result; +//%} +//% +//%- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream +//% asField:(GPBFieldDescriptor *)field { +//% GPBDataType valueDataType = GPBGetFieldDataType(field); +//% GPBDataType keyDataType = field.mapKeyDataType; +//% uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); +//% NSDictionary *internal = _dictionary; +//% NSEnumerator *keys = [internal keyEnumerator]; +//% ENUM_TYPE##KHELPER(KEY_TYPE)##aKey; +//% while ((aKey = [keys nextObject])) { +//% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u = internal[aKey]; +//% [outputStream writeInt32NoTag:tag]; +//% // Write the size of the message. +//% KEY_TYPE KisP##unwrappedKey = UNWRAP##KEY_NAME(aKey); +//% VALUE_TYPE unwrappedValue = UNWRAP##VALUE_NAME(a##VNAME_VAR$u); +//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); +//% msgSize += ComputeDict##VALUE_NAME##FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); +//% [outputStream writeInt32NoTag:(int32_t)msgSize]; +//% // Write the fields. +//% WriteDict##KEY_NAME##Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); +//% WriteDict##VALUE_NAME##Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); +//% } +//%} +//% +//%SERIAL_DATA_FOR_ENTRY_##VHELPER(KEY_NAME, VALUE_NAME)- (void)setGPBGenericValue:(GPBGenericValue *)value +//% forGPBGenericValueKey:(GPBGenericValue *)key { +//% [_dictionary setObject:WRAPPED##VHELPER(value->##GPBVALUE_##VHELPER(VALUE_NAME)##) forKey:WRAPPED##KHELPER(key->value##KEY_NAME)]; +//%} +//% +//%- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { +//% [self enumerateKeysAnd##ACCESSOR_NAME##VNAME##sUsingBlock:^(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop) { +//% #pragma unused(stop) +//% block(TEXT_FORMAT_OBJ##KEY_NAME(key), TEXT_FORMAT_OBJ##VALUE_NAME(VNAME_VAR)); +//% }]; +//%} +//%PDDM-DEFINE DICTIONARY_MUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ACCESSOR_NAME) +//%DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME, VNAME_VAR, ACCESSOR_NAME) +//%PDDM-DEFINE DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_REMOVE, VNAME_VAR, ACCESSOR_NAME) +//%- (void)add##ACCESSOR_NAME##EntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary { +//% if (otherDictionary) { +//% [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//% } +//%} +//% +//%- (void)set##ACCESSOR_NAME##VNAME##:(VALUE_TYPE)VNAME_VAR forKey:(KEY_TYPE##KisP$S##KisP)key { +//%DICTIONARY_VALIDATE_VALUE_##VHELPER(VNAME_VAR, )##DICTIONARY_VALIDATE_KEY_##KHELPER(key, ) [_dictionary setObject:WRAPPED##VHELPER(VNAME_VAR) forKey:WRAPPED##KHELPER(key)]; +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//%} +//% +//%- (void)remove##VNAME_REMOVE##ForKey:(KEY_TYPE##KisP$S##KisP)aKey { +//% [_dictionary removeObjectForKey:WRAPPED##KHELPER(aKey)]; +//%} +//% +//%- (void)removeAll { +//% [_dictionary removeAllObjects]; +//%} + +// +// Custom Generation for Bool keys +// + +//%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_POD_IMPL(VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, POD, VALUE_NAME, value) +//%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(VALUE_NAME, VALUE_TYPE) +//%DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, OBJECT, Object, object) + +//%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, HELPER, VNAME, VNAME_VAR) +//%#pragma mark - Bool -> VALUE_NAME +//% +//%@implementation GPBBool##VALUE_NAME##Dictionary { +//% @package +//% VALUE_TYPE _values[2]; +//%BOOL_DICT_HAS_STORAGE_##HELPER()} +//% +//%- (instancetype)init { +//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; +//%} +//% +//%BOOL_DICT_INITS_##HELPER(VALUE_NAME, VALUE_TYPE) +//% +//%- (instancetype)initWithCapacity:(NSUInteger)numItems { +//% #pragma unused(numItems) +//% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; +//%} +//% +//%BOOL_DICT_DEALLOC##HELPER() +//% +//%- (instancetype)copyWithZone:(NSZone *)zone { +//% return [[GPBBool##VALUE_NAME##Dictionary allocWithZone:zone] initWithDictionary:self]; +//%} +//% +//%- (BOOL)isEqual:(id)other { +//% if (self == other) { +//% return YES; +//% } +//% if (![other isKindOfClass:[GPBBool##VALUE_NAME##Dictionary class]]) { +//% return NO; +//% } +//% GPBBool##VALUE_NAME##Dictionary *otherDictionary = other; +//% if ((BOOL_DICT_W_HAS##HELPER(0, ) != BOOL_DICT_W_HAS##HELPER(0, otherDictionary->)) || +//% (BOOL_DICT_W_HAS##HELPER(1, ) != BOOL_DICT_W_HAS##HELPER(1, otherDictionary->))) { +//% return NO; +//% } +//% if ((BOOL_DICT_W_HAS##HELPER(0, ) && (NEQ_##HELPER(_values[0], otherDictionary->_values[0]))) || +//% (BOOL_DICT_W_HAS##HELPER(1, ) && (NEQ_##HELPER(_values[1], otherDictionary->_values[1])))) { +//% return NO; +//% } +//% return YES; +//%} +//% +//%- (NSUInteger)hash { +//% return (BOOL_DICT_W_HAS##HELPER(0, ) ? 1 : 0) + (BOOL_DICT_W_HAS##HELPER(1, ) ? 1 : 0); +//%} +//% +//%- (NSString *)description { +//% NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; +//% if (BOOL_DICT_W_HAS##HELPER(0, )) { +//% [result appendFormat:@"NO: STR_FORMAT_##HELPER(VALUE_NAME)", _values[0]]; +//% } +//% if (BOOL_DICT_W_HAS##HELPER(1, )) { +//% [result appendFormat:@"YES: STR_FORMAT_##HELPER(VALUE_NAME)", _values[1]]; +//% } +//% [result appendString:@" }"]; +//% return result; +//%} +//% +//%- (NSUInteger)count { +//% return (BOOL_DICT_W_HAS##HELPER(0, ) ? 1 : 0) + (BOOL_DICT_W_HAS##HELPER(1, ) ? 1 : 0); +//%} +//% +//%BOOL_VALUE_FOR_KEY_##HELPER(VALUE_NAME, VALUE_TYPE) +//% +//%BOOL_SET_GPBVALUE_FOR_KEY_##HELPER(VALUE_NAME, VALUE_TYPE, VisP) +//% +//%- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { +//% if (BOOL_DICT_HAS##HELPER(0, )) { +//% block(@"false", TEXT_FORMAT_OBJ##VALUE_NAME(_values[0])); +//% } +//% if (BOOL_DICT_W_HAS##HELPER(1, )) { +//% block(@"true", TEXT_FORMAT_OBJ##VALUE_NAME(_values[1])); +//% } +//%} +//% +//%- (void)enumerateKeysAnd##VNAME##sUsingBlock: +//% (void (^)(BOOL key, VALUE_TYPE VNAME_VAR, BOOL *stop))block { +//% BOOL stop = NO; +//% if (BOOL_DICT_HAS##HELPER(0, )) { +//% block(NO, _values[0], &stop); +//% } +//% if (!stop && BOOL_DICT_W_HAS##HELPER(1, )) { +//% block(YES, _values[1], &stop); +//% } +//%} +//% +//%BOOL_EXTRA_METHODS_##HELPER(Bool, VALUE_NAME)- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { +//% GPBDataType valueDataType = GPBGetFieldDataType(field); +//% NSUInteger count = 0; +//% size_t result = 0; +//% for (int i = 0; i < 2; ++i) { +//% if (BOOL_DICT_HAS##HELPER(i, )) { +//% ++count; +//% size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); +//% msgSize += ComputeDict##VALUE_NAME##FieldSize(_values[i], kMapValueFieldNumber, valueDataType); +//% result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; +//% } +//% } +//% size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); +//% result += tagSize * count; +//% return result; +//%} +//% +//%- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream +//% asField:(GPBFieldDescriptor *)field { +//% GPBDataType valueDataType = GPBGetFieldDataType(field); +//% uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); +//% for (int i = 0; i < 2; ++i) { +//% if (BOOL_DICT_HAS##HELPER(i, )) { +//% // Write the tag. +//% [outputStream writeInt32NoTag:tag]; +//% // Write the size of the message. +//% size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); +//% msgSize += ComputeDict##VALUE_NAME##FieldSize(_values[i], kMapValueFieldNumber, valueDataType); +//% [outputStream writeInt32NoTag:(int32_t)msgSize]; +//% // Write the fields. +//% WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); +//% WriteDict##VALUE_NAME##Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); +//% } +//% } +//%} +//% +//%BOOL_DICT_MUTATIONS_##HELPER(VALUE_NAME, VALUE_TYPE) +//% +//%@end +//% + + +// +// Helpers for PODs +// + +//%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_NAME, VALUE_TYPE, KHELPER) +//%- (BOOL)get##VALUE_NAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key { +//% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; +//% if (wrapped && value) { +//% *value = UNWRAP##VALUE_NAME(wrapped); +//% } +//% return (wrapped != NULL); +//%} +//%PDDM-DEFINE WRAPPEDPOD(VALUE) +//%@(VALUE) +//%PDDM-DEFINE UNWRAPUInt32(VALUE) +//%[VALUE unsignedIntValue] +//%PDDM-DEFINE UNWRAPInt32(VALUE) +//%[VALUE intValue] +//%PDDM-DEFINE UNWRAPUInt64(VALUE) +//%[VALUE unsignedLongLongValue] +//%PDDM-DEFINE UNWRAPInt64(VALUE) +//%[VALUE longLongValue] +//%PDDM-DEFINE UNWRAPBool(VALUE) +//%[VALUE boolValue] +//%PDDM-DEFINE UNWRAPFloat(VALUE) +//%[VALUE floatValue] +//%PDDM-DEFINE UNWRAPDouble(VALUE) +//%[VALUE doubleValue] +//%PDDM-DEFINE UNWRAPEnum(VALUE) +//%[VALUE intValue] +//%PDDM-DEFINE TEXT_FORMAT_OBJUInt32(VALUE) +//%[NSString stringWithFormat:@"%u", VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJInt32(VALUE) +//%[NSString stringWithFormat:@"%d", VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJUInt64(VALUE) +//%[NSString stringWithFormat:@"%llu", VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJInt64(VALUE) +//%[NSString stringWithFormat:@"%lld", VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJBool(VALUE) +//%(VALUE ? @"true" : @"false") +//%PDDM-DEFINE TEXT_FORMAT_OBJFloat(VALUE) +//%[NSString stringWithFormat:@"%.*g", FLT_DIG, VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJDouble(VALUE) +//%[NSString stringWithFormat:@"%.*lg", DBL_DIG, VALUE] +//%PDDM-DEFINE TEXT_FORMAT_OBJEnum(VALUE) +//%@(VALUE) +//%PDDM-DEFINE ENUM_TYPEPOD(TYPE) +//%NSNumber * +//%PDDM-DEFINE NEQ_POD(VAL1, VAL2) +//%VAL1 != VAL2 +//%PDDM-DEFINE EXTRA_METHODS_POD(KEY_NAME, VALUE_NAME) +// Empty +//%PDDM-DEFINE BOOL_EXTRA_METHODS_POD(KEY_NAME, VALUE_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD(KEY_NAME, VALUE_NAME) +//%SERIAL_DATA_FOR_ENTRY_POD_##VALUE_NAME(KEY_NAME) +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_UInt32(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Int32(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_UInt64(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Int64(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Bool(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Float(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Double(KEY_NAME) +// Empty +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Enum(KEY_NAME) +//%- (NSData *)serializedDataForUnknownValue:(int32_t)value +//% forKey:(GPBGenericValue *)key +//% keyDataType:(GPBDataType)keyDataType { +//% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(key->value##KEY_NAME, kMapKeyFieldNumber, keyDataType); +//% msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); +//% NSMutableData *data = [NSMutableData dataWithLength:msgSize]; +//% GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; +//% WriteDict##KEY_NAME##Field(outputStream, key->value##KEY_NAME, kMapKeyFieldNumber, keyDataType); +//% WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); +//% [outputStream release]; +//% return data; +//%} +//% +//%PDDM-DEFINE GPBVALUE_POD(VALUE_NAME) +//%value##VALUE_NAME +//%PDDM-DEFINE DICTIONARY_VALIDATE_VALUE_POD(VALUE_NAME, EXTRA_INDENT) +// Empty +//%PDDM-DEFINE DICTIONARY_VALIDATE_KEY_POD(KEY_NAME, EXTRA_INDENT) +// Empty + +//%PDDM-DEFINE BOOL_DICT_HAS_STORAGE_POD() +//% BOOL _valueSet[2]; +//% +//%PDDM-DEFINE BOOL_DICT_INITS_POD(VALUE_NAME, VALUE_TYPE) +//%- (instancetype)initWith##VALUE_NAME##s:(const VALUE_TYPE [])values +//% ##VALUE_NAME$S## forKeys:(const BOOL [])keys +//% ##VALUE_NAME$S## count:(NSUInteger)count { +//% self = [super init]; +//% if (self) { +//% for (NSUInteger i = 0; i < count; ++i) { +//% int idx = keys[i] ? 1 : 0; +//% _values[idx] = values[i]; +//% _valueSet[idx] = YES; +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary { +//% self = [self initWith##VALUE_NAME##s:NULL forKeys:NULL count:0]; +//% if (self) { +//% if (dictionary) { +//% for (int i = 0; i < 2; ++i) { +//% if (dictionary->_valueSet[i]) { +//% _values[i] = dictionary->_values[i]; +//% _valueSet[i] = YES; +//% } +//% } +//% } +//% } +//% return self; +//%} +//%PDDM-DEFINE BOOL_DICT_DEALLOCPOD() +//%#if !defined(NS_BLOCK_ASSERTIONS) +//%- (void)dealloc { +//% NSAssert(!_autocreator, +//% @"%@: Autocreator must be cleared before release, autocreator: %@", +//% [self class], _autocreator); +//% [super dealloc]; +//%} +//%#endif // !defined(NS_BLOCK_ASSERTIONS) +//%PDDM-DEFINE BOOL_DICT_W_HASPOD(IDX, REF) +//%BOOL_DICT_HASPOD(IDX, REF) +//%PDDM-DEFINE BOOL_DICT_HASPOD(IDX, REF) +//%REF##_valueSet[IDX] +//%PDDM-DEFINE BOOL_VALUE_FOR_KEY_POD(VALUE_NAME, VALUE_TYPE) +//%- (BOOL)get##VALUE_NAME##:(VALUE_TYPE *)value forKey:(BOOL)key { +//% int idx = (key ? 1 : 0); +//% if (_valueSet[idx]) { +//% if (value) { +//% *value = _values[idx]; +//% } +//% return YES; +//% } +//% return NO; +//%} +//%PDDM-DEFINE BOOL_SET_GPBVALUE_FOR_KEY_POD(VALUE_NAME, VALUE_TYPE, VisP) +//%- (void)setGPBGenericValue:(GPBGenericValue *)value +//% forGPBGenericValueKey:(GPBGenericValue *)key { +//% int idx = (key->valueBool ? 1 : 0); +//% _values[idx] = value->value##VALUE_NAME; +//% _valueSet[idx] = YES; +//%} +//%PDDM-DEFINE BOOL_DICT_MUTATIONS_POD(VALUE_NAME, VALUE_TYPE) +//%- (void)addEntriesFromDictionary:(GPBBool##VALUE_NAME##Dictionary *)otherDictionary { +//% if (otherDictionary) { +//% for (int i = 0; i < 2; ++i) { +//% if (otherDictionary->_valueSet[i]) { +//% _valueSet[i] = YES; +//% _values[i] = otherDictionary->_values[i]; +//% } +//% } +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//% } +//%} +//% +//%- (void)set##VALUE_NAME:(VALUE_TYPE)value forKey:(BOOL)key { +//% int idx = (key ? 1 : 0); +//% _values[idx] = value; +//% _valueSet[idx] = YES; +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//%} +//% +//%- (void)remove##VALUE_NAME##ForKey:(BOOL)aKey { +//% _valueSet[aKey ? 1 : 0] = NO; +//%} +//% +//%- (void)removeAll { +//% _valueSet[0] = NO; +//% _valueSet[1] = NO; +//%} +//%PDDM-DEFINE STR_FORMAT_POD(VALUE_NAME) +//%STR_FORMAT_##VALUE_NAME() +//%PDDM-DEFINE STR_FORMAT_UInt32() +//%%u +//%PDDM-DEFINE STR_FORMAT_Int32() +//%%d +//%PDDM-DEFINE STR_FORMAT_UInt64() +//%%llu +//%PDDM-DEFINE STR_FORMAT_Int64() +//%%lld +//%PDDM-DEFINE STR_FORMAT_Bool() +//%%d +//%PDDM-DEFINE STR_FORMAT_Float() +//%%f +//%PDDM-DEFINE STR_FORMAT_Double() +//%%lf + +// +// Helpers for Objects +// + +//%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_NAME, VALUE_TYPE, KHELPER) +//%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key { +//% VALUE_TYPE result = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; +//% return result; +//%} +//%PDDM-DEFINE WRAPPEDOBJECT(VALUE) +//%VALUE +//%PDDM-DEFINE UNWRAPString(VALUE) +//%VALUE +//%PDDM-DEFINE UNWRAPObject(VALUE) +//%VALUE +//%PDDM-DEFINE TEXT_FORMAT_OBJString(VALUE) +//%VALUE +//%PDDM-DEFINE TEXT_FORMAT_OBJObject(VALUE) +//%VALUE +//%PDDM-DEFINE ENUM_TYPEOBJECT(TYPE) +//%ENUM_TYPEOBJECT_##TYPE() +//%PDDM-DEFINE ENUM_TYPEOBJECT_NSString() +//%NSString * +//%PDDM-DEFINE ENUM_TYPEOBJECT_id() +//%id ## +//%PDDM-DEFINE NEQ_OBJECT(VAL1, VAL2) +//%![VAL1 isEqual:VAL2] +//%PDDM-DEFINE EXTRA_METHODS_OBJECT(KEY_NAME, VALUE_NAME) +//%- (BOOL)isInitialized { +//% for (GPBMessage *msg in [_dictionary objectEnumerator]) { +//% if (!msg.initialized) { +//% return NO; +//% } +//% } +//% return YES; +//%} +//% +//%- (instancetype)deepCopyWithZone:(NSZone *)zone { +//% GPB##KEY_NAME##VALUE_NAME##Dictionary *newDict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% NSEnumerator *keys = [_dictionary keyEnumerator]; +//% id aKey; +//% NSMutableDictionary *internalDict = newDict->_dictionary; +//% while ((aKey = [keys nextObject])) { +//% GPBMessage *msg = _dictionary[aKey]; +//% GPBMessage *copiedMsg = [msg copyWithZone:zone]; +//% [internalDict setObject:copiedMsg forKey:aKey]; +//% [copiedMsg release]; +//% } +//% return newDict; +//%} +//% +//% +//%PDDM-DEFINE BOOL_EXTRA_METHODS_OBJECT(KEY_NAME, VALUE_NAME) +//%- (BOOL)isInitialized { +//% if (_values[0] && ![_values[0] isInitialized]) { +//% return NO; +//% } +//% if (_values[1] && ![_values[1] isInitialized]) { +//% return NO; +//% } +//% return YES; +//%} +//% +//%- (instancetype)deepCopyWithZone:(NSZone *)zone { +//% GPB##KEY_NAME##VALUE_NAME##Dictionary *newDict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% for (int i = 0; i < 2; ++i) { +//% if (_values[i] != nil) { +//% newDict->_values[i] = [_values[i] copyWithZone:zone]; +//% } +//% } +//% return newDict; +//%} +//% +//% +//%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_OBJECT(KEY_NAME, VALUE_NAME) +// Empty +//%PDDM-DEFINE GPBVALUE_OBJECT(VALUE_NAME) +//%valueString +//%PDDM-DEFINE DICTIONARY_VALIDATE_VALUE_OBJECT(VALUE_NAME, EXTRA_INDENT) +//%##EXTRA_INDENT$S## if (!##VALUE_NAME) { +//%##EXTRA_INDENT$S## [NSException raise:NSInvalidArgumentException +//%##EXTRA_INDENT$S## format:@"Attempting to add nil object to a Dictionary"]; +//%##EXTRA_INDENT$S## } +//% +//%PDDM-DEFINE DICTIONARY_VALIDATE_KEY_OBJECT(KEY_NAME, EXTRA_INDENT) +//%##EXTRA_INDENT$S## if (!##KEY_NAME) { +//%##EXTRA_INDENT$S## [NSException raise:NSInvalidArgumentException +//%##EXTRA_INDENT$S## format:@"Attempting to add nil key to a Dictionary"]; +//%##EXTRA_INDENT$S## } +//% + +//%PDDM-DEFINE BOOL_DICT_HAS_STORAGE_OBJECT() +// Empty +//%PDDM-DEFINE BOOL_DICT_INITS_OBJECT(VALUE_NAME, VALUE_TYPE) +//%- (instancetype)initWithObjects:(const VALUE_TYPE [])objects +//% forKeys:(const BOOL [])keys +//% count:(NSUInteger)count { +//% self = [super init]; +//% if (self) { +//% for (NSUInteger i = 0; i < count; ++i) { +//% if (!objects[i]) { +//% [NSException raise:NSInvalidArgumentException +//% format:@"Attempting to add nil object to a Dictionary"]; +//% } +//% int idx = keys[i] ? 1 : 0; +//% [_values[idx] release]; +//% _values[idx] = (VALUE_TYPE)[objects[i] retain]; +//% } +//% } +//% return self; +//%} +//% +//%- (instancetype)initWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary { +//% self = [self initWithObjects:NULL forKeys:NULL count:0]; +//% if (self) { +//% if (dictionary) { +//% _values[0] = [dictionary->_values[0] retain]; +//% _values[1] = [dictionary->_values[1] retain]; +//% } +//% } +//% return self; +//%} +//%PDDM-DEFINE BOOL_DICT_DEALLOCOBJECT() +//%- (void)dealloc { +//% NSAssert(!_autocreator, +//% @"%@: Autocreator must be cleared before release, autocreator: %@", +//% [self class], _autocreator); +//% [_values[0] release]; +//% [_values[1] release]; +//% [super dealloc]; +//%} +//%PDDM-DEFINE BOOL_DICT_W_HASOBJECT(IDX, REF) +//%(BOOL_DICT_HASOBJECT(IDX, REF)) +//%PDDM-DEFINE BOOL_DICT_HASOBJECT(IDX, REF) +//%REF##_values[IDX] != nil +//%PDDM-DEFINE BOOL_VALUE_FOR_KEY_OBJECT(VALUE_NAME, VALUE_TYPE) +//%- (VALUE_TYPE)objectForKey:(BOOL)key { +//% return _values[key ? 1 : 0]; +//%} +//%PDDM-DEFINE BOOL_SET_GPBVALUE_FOR_KEY_OBJECT(VALUE_NAME, VALUE_TYPE, VisP) +//%- (void)setGPBGenericValue:(GPBGenericValue *)value +//% forGPBGenericValueKey:(GPBGenericValue *)key { +//% int idx = (key->valueBool ? 1 : 0); +//% [_values[idx] release]; +//% _values[idx] = [value->valueString retain]; +//%} + +//%PDDM-DEFINE BOOL_DICT_MUTATIONS_OBJECT(VALUE_NAME, VALUE_TYPE) +//%- (void)addEntriesFromDictionary:(GPBBool##VALUE_NAME##Dictionary *)otherDictionary { +//% if (otherDictionary) { +//% for (int i = 0; i < 2; ++i) { +//% if (otherDictionary->_values[i] != nil) { +//% [_values[i] release]; +//% _values[i] = [otherDictionary->_values[i] retain]; +//% } +//% } +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//% } +//%} +//% +//%- (void)setObject:(VALUE_TYPE)object forKey:(BOOL)key { +//% if (!object) { +//% [NSException raise:NSInvalidArgumentException +//% format:@"Attempting to add nil object to a Dictionary"]; +//% } +//% int idx = (key ? 1 : 0); +//% [_values[idx] release]; +//% _values[idx] = [object retain]; +//% if (_autocreator) { +//% GPBAutocreatedDictionaryModified(_autocreator, self); +//% } +//%} +//% +//%- (void)removeObjectForKey:(BOOL)aKey { +//% int idx = (aKey ? 1 : 0); +//% [_values[idx] release]; +//% _values[idx] = nil; +//%} +//% +//%- (void)removeAll { +//% for (int i = 0; i < 2; ++i) { +//% [_values[i] release]; +//% _values[i] = nil; +//% } +//%} +//%PDDM-DEFINE STR_FORMAT_OBJECT(VALUE_NAME) +//%%@ + + +//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt32, uint32_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - UInt32 -> UInt32 + +@implementation GPBUInt32UInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32UInt32Dictionary class]]) { + return NO; + } + GPBUInt32UInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(uint32_t key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue unsignedIntValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + uint32_t unwrappedValue = [aValue unsignedIntValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt32sUsingBlock:^(uint32_t key, uint32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%u", value]); + }]; +} + +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedIntValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32UInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Int32 + +@implementation GPBUInt32Int32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32Int32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32Int32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32Int32Dictionary class]]) { + return NO; + } + GPBUInt32Int32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(uint32_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt32sUsingBlock:^(uint32_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%d", value]); + }]; +} + +- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32Int32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> UInt64 + +@implementation GPBUInt32UInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32UInt64Dictionary class]]) { + return NO; + } + GPBUInt32UInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(uint32_t key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue unsignedLongLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + uint64_t unwrappedValue = [aValue unsignedLongLongValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt64sUsingBlock:^(uint32_t key, uint64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%llu", value]); + }]; +} + +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedLongLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32UInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Int64 + +@implementation GPBUInt32Int64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32Int64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32Int64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32Int64Dictionary class]]) { + return NO; + } + GPBUInt32Int64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(uint32_t key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue longLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + int64_t unwrappedValue = [aValue longLongValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt64sUsingBlock:^(uint32_t key, int64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%lld", value]); + }]; +} + +- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped longLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32Int64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Bool + +@implementation GPBUInt32BoolDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32BoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32BoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32BoolDictionary class]]) { + return NO; + } + GPBUInt32BoolDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(uint32_t key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue boolValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + BOOL unwrappedValue = [aValue boolValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueBool) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndBoolsUsingBlock:^(uint32_t key, BOOL value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], (value ? @"true" : @"false")); + }]; +} + +- (BOOL)getBool:(nullable BOOL *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped boolValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32BoolDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Float + +@implementation GPBUInt32FloatDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32FloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32FloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32FloatDictionary class]]) { + return NO; + } + GPBUInt32FloatDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(uint32_t key, float value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue floatValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + float unwrappedValue = [aValue floatValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndFloatsUsingBlock:^(uint32_t key, float value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); + }]; +} + +- (BOOL)getFloat:(nullable float *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped floatValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32FloatDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Double + +@implementation GPBUInt32DoubleDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32DoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32DoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32DoubleDictionary class]]) { + return NO; + } + GPBUInt32DoubleDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(uint32_t key, double value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue doubleValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + double unwrappedValue = [aValue doubleValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndDoublesUsingBlock:^(uint32_t key, double value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); + }]; +} + +- (BOOL)getDouble:(nullable double *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped doubleValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt32DoubleDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt32 -> Enum + +@implementation GPBUInt32EnumDictionary { + @package + NSMutableDictionary *_dictionary; + GPBEnumValidationFunc _validationFunc; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + if (count && rawValues && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32EnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32EnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32EnumDictionary class]]) { + return NO; + } + GPBUInt32EnumDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(uint32_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedIntValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictUInt32FieldSize(key->valueUInt32, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictUInt32Field(outputStream, key->valueUInt32, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndRawValuesUsingBlock:^(uint32_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], @(value)); + }]; +} + +- (BOOL)getEnum:(int32_t *)value forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + int32_t result = [wrapped intValue]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return (wrapped != NULL); +} + +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(uint32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && rawValue) { + *rawValue = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(uint32_t key, int32_t value, BOOL *stop))block { + GPBEnumValidationFunc func = _validationFunc; + BOOL stop = NO; + NSEnumerator *keys = [_dictionary keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = _dictionary[aKey]; + int32_t unwrapped = [aValue intValue]; + if (!func(unwrapped)) { + unwrapped = kGPBUnrecognizedEnumeratorValue; + } + block([aKey unsignedIntValue], unwrapped, &stop); + if (stop) { + break; + } + } +} + +- (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setRawValue:(int32_t)value forKey:(uint32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +- (void)setEnum:(int32_t)value forKey:(uint32_t)key { + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBUInt32EnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +@end + +#pragma mark - UInt32 -> Object + +@implementation GPBUInt32ObjectDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && objects && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!objects[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:objects[i] forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt32ObjectDictionary *)dictionary { + self = [self initWithObjects:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt32ObjectDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt32ObjectDictionary class]]) { + return NO; + } + GPBUInt32ObjectDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(uint32_t key, id object, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + block([aKey unsignedIntValue], aObject, &stop); + if (stop) { + break; + } + } +} + +- (BOOL)isInitialized { + for (GPBMessage *msg in [_dictionary objectEnumerator]) { + if (!msg.initialized) { + return NO; + } + } + return YES; +} + +- (instancetype)deepCopyWithZone:(NSZone *)zone { + GPBUInt32ObjectDictionary *newDict = + [[GPBUInt32ObjectDictionary alloc] init]; + NSEnumerator *keys = [_dictionary keyEnumerator]; + id aKey; + NSMutableDictionary *internalDict = newDict->_dictionary; + while ((aKey = [keys nextObject])) { + GPBMessage *msg = _dictionary[aKey]; + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [internalDict setObject:copiedMsg forKey:aKey]; + [copiedMsg release]; + } + return newDict; +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint32_t unwrappedKey = [aKey unsignedIntValue]; + id unwrappedValue = aObject; + size_t msgSize = ComputeDictUInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:value->valueString forKey:@(key->valueUInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndObjectsUsingBlock:^(uint32_t key, id object, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%u", key], object); + }]; +} + +- (id)objectForKey:(uint32_t)key { + id result = [_dictionary objectForKey:@(key)]; + return result; +} + +- (void)addEntriesFromDictionary:(GPBUInt32ObjectDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setObject:(id)object forKey:(uint32_t)key { + if (!object) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:object forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(uint32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int32, int32_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Int32 -> UInt32 + +@implementation GPBInt32UInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32UInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32UInt32Dictionary class]]) { + return NO; + } + GPBInt32UInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(int32_t key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue unsignedIntValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + uint32_t unwrappedValue = [aValue unsignedIntValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt32sUsingBlock:^(int32_t key, uint32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%u", value]); + }]; +} + +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedIntValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32UInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Int32 + +@implementation GPBInt32Int32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32Int32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32Int32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32Int32Dictionary class]]) { + return NO; + } + GPBInt32Int32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(int32_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt32sUsingBlock:^(int32_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%d", value]); + }]; +} + +- (BOOL)getInt32:(nullable int32_t *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32Int32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> UInt64 + +@implementation GPBInt32UInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32UInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32UInt64Dictionary class]]) { + return NO; + } + GPBInt32UInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(int32_t key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue unsignedLongLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + uint64_t unwrappedValue = [aValue unsignedLongLongValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt64sUsingBlock:^(int32_t key, uint64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%llu", value]); + }]; +} + +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedLongLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32UInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Int64 + +@implementation GPBInt32Int64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32Int64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32Int64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32Int64Dictionary class]]) { + return NO; + } + GPBInt32Int64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(int32_t key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue longLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + int64_t unwrappedValue = [aValue longLongValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt64sUsingBlock:^(int32_t key, int64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%lld", value]); + }]; +} + +- (BOOL)getInt64:(nullable int64_t *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped longLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32Int64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Bool + +@implementation GPBInt32BoolDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32BoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32BoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32BoolDictionary class]]) { + return NO; + } + GPBInt32BoolDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(int32_t key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue boolValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + BOOL unwrappedValue = [aValue boolValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueBool) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndBoolsUsingBlock:^(int32_t key, BOOL value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], (value ? @"true" : @"false")); + }]; +} + +- (BOOL)getBool:(nullable BOOL *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped boolValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32BoolDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Float + +@implementation GPBInt32FloatDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32FloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32FloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32FloatDictionary class]]) { + return NO; + } + GPBInt32FloatDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(int32_t key, float value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue floatValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + float unwrappedValue = [aValue floatValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndFloatsUsingBlock:^(int32_t key, float value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); + }]; +} + +- (BOOL)getFloat:(nullable float *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped floatValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32FloatDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Double + +@implementation GPBInt32DoubleDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32DoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32DoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32DoubleDictionary class]]) { + return NO; + } + GPBInt32DoubleDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(int32_t key, double value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue doubleValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + double unwrappedValue = [aValue doubleValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndDoublesUsingBlock:^(int32_t key, double value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); + }]; +} + +- (BOOL)getDouble:(nullable double *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped doubleValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt32DoubleDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int32 -> Enum + +@implementation GPBInt32EnumDictionary { + @package + NSMutableDictionary *_dictionary; + GPBEnumValidationFunc _validationFunc; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + if (count && rawValues && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32EnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32EnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32EnumDictionary class]]) { + return NO; + } + GPBInt32EnumDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(int32_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey intValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictInt32FieldSize(key->valueInt32, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictInt32Field(outputStream, key->valueInt32, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndRawValuesUsingBlock:^(int32_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], @(value)); + }]; +} + +- (BOOL)getEnum:(int32_t *)value forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + int32_t result = [wrapped intValue]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return (wrapped != NULL); +} + +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(int32_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && rawValue) { + *rawValue = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(int32_t key, int32_t value, BOOL *stop))block { + GPBEnumValidationFunc func = _validationFunc; + BOOL stop = NO; + NSEnumerator *keys = [_dictionary keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = _dictionary[aKey]; + int32_t unwrapped = [aValue intValue]; + if (!func(unwrapped)) { + unwrapped = kGPBUnrecognizedEnumeratorValue; + } + block([aKey intValue], unwrapped, &stop); + if (stop) { + break; + } + } +} + +- (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setRawValue:(int32_t)value forKey:(int32_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +- (void)setEnum:(int32_t)value forKey:(int32_t)key { + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBInt32EnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +@end + +#pragma mark - Int32 -> Object + +@implementation GPBInt32ObjectDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const int32_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && objects && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!objects[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:objects[i] forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt32ObjectDictionary *)dictionary { + self = [self initWithObjects:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt32ObjectDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt32ObjectDictionary class]]) { + return NO; + } + GPBInt32ObjectDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(int32_t key, id object, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + block([aKey intValue], aObject, &stop); + if (stop) { + break; + } + } +} + +- (BOOL)isInitialized { + for (GPBMessage *msg in [_dictionary objectEnumerator]) { + if (!msg.initialized) { + return NO; + } + } + return YES; +} + +- (instancetype)deepCopyWithZone:(NSZone *)zone { + GPBInt32ObjectDictionary *newDict = + [[GPBInt32ObjectDictionary alloc] init]; + NSEnumerator *keys = [_dictionary keyEnumerator]; + id aKey; + NSMutableDictionary *internalDict = newDict->_dictionary; + while ((aKey = [keys nextObject])) { + GPBMessage *msg = _dictionary[aKey]; + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [internalDict setObject:copiedMsg forKey:aKey]; + [copiedMsg release]; + } + return newDict; +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int32_t unwrappedKey = [aKey intValue]; + id unwrappedValue = aObject; + size_t msgSize = ComputeDictInt32FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt32Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:value->valueString forKey:@(key->valueInt32)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndObjectsUsingBlock:^(int32_t key, id object, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%d", key], object); + }]; +} + +- (id)objectForKey:(int32_t)key { + id result = [_dictionary objectForKey:@(key)]; + return result; +} + +- (void)addEntriesFromDictionary:(GPBInt32ObjectDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setObject:(id)object forKey:(int32_t)key { + if (!object) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:object forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(int32_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt64, uint64_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - UInt64 -> UInt32 + +@implementation GPBUInt64UInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64UInt32Dictionary class]]) { + return NO; + } + GPBUInt64UInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(uint64_t key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue unsignedIntValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + uint32_t unwrappedValue = [aValue unsignedIntValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt32sUsingBlock:^(uint64_t key, uint32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%u", value]); + }]; +} + +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedIntValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64UInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Int32 + +@implementation GPBUInt64Int32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64Int32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64Int32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64Int32Dictionary class]]) { + return NO; + } + GPBUInt64Int32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(uint64_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt32sUsingBlock:^(uint64_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%d", value]); + }]; +} + +- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64Int32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> UInt64 + +@implementation GPBUInt64UInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64UInt64Dictionary class]]) { + return NO; + } + GPBUInt64UInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(uint64_t key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue unsignedLongLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + uint64_t unwrappedValue = [aValue unsignedLongLongValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt64sUsingBlock:^(uint64_t key, uint64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%llu", value]); + }]; +} + +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedLongLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64UInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Int64 + +@implementation GPBUInt64Int64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64Int64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64Int64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64Int64Dictionary class]]) { + return NO; + } + GPBUInt64Int64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(uint64_t key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue longLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + int64_t unwrappedValue = [aValue longLongValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt64sUsingBlock:^(uint64_t key, int64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%lld", value]); + }]; +} + +- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped longLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64Int64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Bool + +@implementation GPBUInt64BoolDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64BoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64BoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64BoolDictionary class]]) { + return NO; + } + GPBUInt64BoolDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(uint64_t key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue boolValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + BOOL unwrappedValue = [aValue boolValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueBool) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndBoolsUsingBlock:^(uint64_t key, BOOL value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], (value ? @"true" : @"false")); + }]; +} + +- (BOOL)getBool:(nullable BOOL *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped boolValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64BoolDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Float + +@implementation GPBUInt64FloatDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64FloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64FloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64FloatDictionary class]]) { + return NO; + } + GPBUInt64FloatDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(uint64_t key, float value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue floatValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + float unwrappedValue = [aValue floatValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndFloatsUsingBlock:^(uint64_t key, float value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); + }]; +} + +- (BOOL)getFloat:(nullable float *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped floatValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64FloatDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Double + +@implementation GPBUInt64DoubleDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64DoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64DoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64DoubleDictionary class]]) { + return NO; + } + GPBUInt64DoubleDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(uint64_t key, double value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue doubleValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + double unwrappedValue = [aValue doubleValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndDoublesUsingBlock:^(uint64_t key, double value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); + }]; +} + +- (BOOL)getDouble:(nullable double *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped doubleValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBUInt64DoubleDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - UInt64 -> Enum + +@implementation GPBUInt64EnumDictionary { + @package + NSMutableDictionary *_dictionary; + GPBEnumValidationFunc _validationFunc; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + if (count && rawValues && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64EnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64EnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64EnumDictionary class]]) { + return NO; + } + GPBUInt64EnumDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(uint64_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey unsignedLongLongValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictUInt64FieldSize(key->valueUInt64, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictUInt64Field(outputStream, key->valueUInt64, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndRawValuesUsingBlock:^(uint64_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], @(value)); + }]; +} + +- (BOOL)getEnum:(int32_t *)value forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + int32_t result = [wrapped intValue]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return (wrapped != NULL); +} + +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(uint64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && rawValue) { + *rawValue = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(uint64_t key, int32_t value, BOOL *stop))block { + GPBEnumValidationFunc func = _validationFunc; + BOOL stop = NO; + NSEnumerator *keys = [_dictionary keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = _dictionary[aKey]; + int32_t unwrapped = [aValue intValue]; + if (!func(unwrapped)) { + unwrapped = kGPBUnrecognizedEnumeratorValue; + } + block([aKey unsignedLongLongValue], unwrapped, &stop); + if (stop) { + break; + } + } +} + +- (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setRawValue:(int32_t)value forKey:(uint64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +- (void)setEnum:(int32_t)value forKey:(uint64_t)key { + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBUInt64EnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +@end + +#pragma mark - UInt64 -> Object + +@implementation GPBUInt64ObjectDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const uint64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && objects && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!objects[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:objects[i] forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBUInt64ObjectDictionary *)dictionary { + self = [self initWithObjects:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBUInt64ObjectDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBUInt64ObjectDictionary class]]) { + return NO; + } + GPBUInt64ObjectDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(uint64_t key, id object, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + block([aKey unsignedLongLongValue], aObject, &stop); + if (stop) { + break; + } + } +} + +- (BOOL)isInitialized { + for (GPBMessage *msg in [_dictionary objectEnumerator]) { + if (!msg.initialized) { + return NO; + } + } + return YES; +} + +- (instancetype)deepCopyWithZone:(NSZone *)zone { + GPBUInt64ObjectDictionary *newDict = + [[GPBUInt64ObjectDictionary alloc] init]; + NSEnumerator *keys = [_dictionary keyEnumerator]; + id aKey; + NSMutableDictionary *internalDict = newDict->_dictionary; + while ((aKey = [keys nextObject])) { + GPBMessage *msg = _dictionary[aKey]; + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [internalDict setObject:copiedMsg forKey:aKey]; + [copiedMsg release]; + } + return newDict; +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + uint64_t unwrappedKey = [aKey unsignedLongLongValue]; + id unwrappedValue = aObject; + size_t msgSize = ComputeDictUInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictUInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:value->valueString forKey:@(key->valueUInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndObjectsUsingBlock:^(uint64_t key, id object, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%llu", key], object); + }]; +} + +- (id)objectForKey:(uint64_t)key { + id result = [_dictionary objectForKey:@(key)]; + return result; +} + +- (void)addEntriesFromDictionary:(GPBUInt64ObjectDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setObject:(id)object forKey:(uint64_t)key { + if (!object) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:object forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(uint64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int64, int64_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Int64 -> UInt32 + +@implementation GPBInt64UInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64UInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64UInt32Dictionary class]]) { + return NO; + } + GPBInt64UInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(int64_t key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue unsignedIntValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + uint32_t unwrappedValue = [aValue unsignedIntValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt32sUsingBlock:^(int64_t key, uint32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%u", value]); + }]; +} + +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedIntValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64UInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Int32 + +@implementation GPBInt64Int32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64Int32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64Int32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64Int32Dictionary class]]) { + return NO; + } + GPBInt64Int32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(int64_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt32sUsingBlock:^(int64_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%d", value]); + }]; +} + +- (BOOL)getInt32:(nullable int32_t *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64Int32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> UInt64 + +@implementation GPBInt64UInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64UInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64UInt64Dictionary class]]) { + return NO; + } + GPBInt64UInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(int64_t key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue unsignedLongLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + uint64_t unwrappedValue = [aValue unsignedLongLongValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt64sUsingBlock:^(int64_t key, uint64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%llu", value]); + }]; +} + +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped unsignedLongLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64UInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Int64 + +@implementation GPBInt64Int64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64Int64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64Int64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64Int64Dictionary class]]) { + return NO; + } + GPBInt64Int64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(int64_t key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue longLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + int64_t unwrappedValue = [aValue longLongValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt64sUsingBlock:^(int64_t key, int64_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%lld", value]); + }]; +} + +- (BOOL)getInt64:(nullable int64_t *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped longLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64Int64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Bool + +@implementation GPBInt64BoolDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64BoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64BoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64BoolDictionary class]]) { + return NO; + } + GPBInt64BoolDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(int64_t key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue boolValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + BOOL unwrappedValue = [aValue boolValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueBool) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndBoolsUsingBlock:^(int64_t key, BOOL value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], (value ? @"true" : @"false")); + }]; +} + +- (BOOL)getBool:(nullable BOOL *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped boolValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64BoolDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Float + +@implementation GPBInt64FloatDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64FloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64FloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64FloatDictionary class]]) { + return NO; + } + GPBInt64FloatDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(int64_t key, float value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue floatValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + float unwrappedValue = [aValue floatValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndFloatsUsingBlock:^(int64_t key, float value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); + }]; +} + +- (BOOL)getFloat:(nullable float *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped floatValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64FloatDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Double + +@implementation GPBInt64DoubleDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64DoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64DoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64DoubleDictionary class]]) { + return NO; + } + GPBInt64DoubleDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(int64_t key, double value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue doubleValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + double unwrappedValue = [aValue doubleValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndDoublesUsingBlock:^(int64_t key, double value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); + }]; +} + +- (BOOL)getDouble:(nullable double *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + *value = [wrapped doubleValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBInt64DoubleDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - Int64 -> Enum + +@implementation GPBInt64EnumDictionary { + @package + NSMutableDictionary *_dictionary; + GPBEnumValidationFunc _validationFunc; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + if (count && rawValues && keys) { + for (NSUInteger i = 0; i < count; ++i) { + [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64EnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64EnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64EnumDictionary class]]) { + return NO; + } + GPBInt64EnumDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(int64_t key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block([aKey longLongValue], [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictInt64FieldSize(key->valueInt64, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictInt64Field(outputStream, key->valueInt64, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndRawValuesUsingBlock:^(int64_t key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], @(value)); + }]; +} + +- (BOOL)getEnum:(int32_t *)value forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && value) { + int32_t result = [wrapped intValue]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return (wrapped != NULL); +} + +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(int64_t)key { + NSNumber *wrapped = [_dictionary objectForKey:@(key)]; + if (wrapped && rawValue) { + *rawValue = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(int64_t key, int32_t value, BOOL *stop))block { + GPBEnumValidationFunc func = _validationFunc; + BOOL stop = NO; + NSEnumerator *keys = [_dictionary keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = _dictionary[aKey]; + int32_t unwrapped = [aValue intValue]; + if (!func(unwrapped)) { + unwrapped = kGPBUnrecognizedEnumeratorValue; + } + block([aKey longLongValue], unwrapped, &stop); + if (stop) { + break; + } + } +} + +- (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setRawValue:(int32_t)value forKey:(int64_t)key { + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +- (void)setEnum:(int32_t)value forKey:(int64_t)key { + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBInt64EnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + + [_dictionary setObject:@(value) forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +@end + +#pragma mark - Int64 -> Object + +@implementation GPBInt64ObjectDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const int64_t [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && objects && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!objects[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:objects[i] forKey:@(keys[i])]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBInt64ObjectDictionary *)dictionary { + self = [self initWithObjects:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBInt64ObjectDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBInt64ObjectDictionary class]]) { + return NO; + } + GPBInt64ObjectDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(int64_t key, id object, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + block([aKey longLongValue], aObject, &stop); + if (stop) { + break; + } + } +} + +- (BOOL)isInitialized { + for (GPBMessage *msg in [_dictionary objectEnumerator]) { + if (!msg.initialized) { + return NO; + } + } + return YES; +} + +- (instancetype)deepCopyWithZone:(NSZone *)zone { + GPBInt64ObjectDictionary *newDict = + [[GPBInt64ObjectDictionary alloc] init]; + NSEnumerator *keys = [_dictionary keyEnumerator]; + id aKey; + NSMutableDictionary *internalDict = newDict->_dictionary; + while ((aKey = [keys nextObject])) { + GPBMessage *msg = _dictionary[aKey]; + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [internalDict setObject:copiedMsg forKey:aKey]; + [copiedMsg release]; + } + return newDict; +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSNumber *aKey; + while ((aKey = [keys nextObject])) { + id aObject = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + int64_t unwrappedKey = [aKey longLongValue]; + id unwrappedValue = aObject; + size_t msgSize = ComputeDictInt64FieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictObjectFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictInt64Field(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictObjectField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:value->valueString forKey:@(key->valueInt64)]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndObjectsUsingBlock:^(int64_t key, id object, BOOL *stop) { + #pragma unused(stop) + block([NSString stringWithFormat:@"%lld", key], object); + }]; +} + +- (id)objectForKey:(int64_t)key { + id result = [_dictionary objectForKey:@(key)]; + return result; +} + +- (void)addEntriesFromDictionary:(GPBInt64ObjectDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setObject:(id)object forKey:(int64_t)key { + if (!object) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + [_dictionary setObject:object forKey:@(key)]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(int64_t)aKey { + [_dictionary removeObjectForKey:@(aKey)]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +//%PDDM-EXPAND DICTIONARY_POD_IMPL_FOR_KEY(String, NSString, *, OBJECT) +// This block of code is generated, do not edit it directly. + +#pragma mark - String -> UInt32 + +@implementation GPBStringUInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringUInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringUInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringUInt32Dictionary class]]) { + return NO; + } + GPBStringUInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(NSString *key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue unsignedIntValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + uint32_t unwrappedValue = [aValue unsignedIntValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt32) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt32sUsingBlock:^(NSString *key, uint32_t value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%u", value]); + }]; +} + +- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped unsignedIntValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringUInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Int32 + +@implementation GPBStringInt32Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringInt32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringInt32Dictionary class]]) { + return NO; + } + GPBStringInt32Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(NSString *key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt32FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt32Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt32) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt32sUsingBlock:^(NSString *key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%d", value]); + }]; +} + +- (BOOL)getInt32:(nullable int32_t *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringInt32Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> UInt64 + +@implementation GPBStringUInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringUInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringUInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringUInt64Dictionary class]]) { + return NO; + } + GPBStringUInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(NSString *key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue unsignedLongLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + uint64_t unwrappedValue = [aValue unsignedLongLongValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictUInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictUInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueUInt64) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndUInt64sUsingBlock:^(NSString *key, uint64_t value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%llu", value]); + }]; +} + +- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped unsignedLongLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringUInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Int64 + +@implementation GPBStringInt64Dictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringInt64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringInt64Dictionary class]]) { + return NO; + } + GPBStringInt64Dictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(NSString *key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue longLongValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + int64_t unwrappedValue = [aValue longLongValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictInt64FieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictInt64Field(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueInt64) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndInt64sUsingBlock:^(NSString *key, int64_t value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%lld", value]); + }]; +} + +- (BOOL)getInt64:(nullable int64_t *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped longLongValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringInt64Dictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Bool + +@implementation GPBStringBoolDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringBoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringBoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringBoolDictionary class]]) { + return NO; + } + GPBStringBoolDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(NSString *key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue boolValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + BOOL unwrappedValue = [aValue boolValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictBoolFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictBoolField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueBool) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndBoolsUsingBlock:^(NSString *key, BOOL value, BOOL *stop) { + #pragma unused(stop) + block(key, (value ? @"true" : @"false")); + }]; +} + +- (BOOL)getBool:(nullable BOOL *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped boolValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringBoolDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Float + +@implementation GPBStringFloatDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringFloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringFloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringFloatDictionary class]]) { + return NO; + } + GPBStringFloatDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(NSString *key, float value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue floatValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + float unwrappedValue = [aValue floatValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictFloatFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictFloatField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueFloat) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndFloatsUsingBlock:^(NSString *key, float value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); + }]; +} + +- (BOOL)getFloat:(nullable float *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped floatValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringFloatDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Double + +@implementation GPBStringDoubleDictionary { + @package + NSMutableDictionary *_dictionary; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + if (count && values && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(values[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringDoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringDoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringDoubleDictionary class]]) { + return NO; + } + GPBStringDoubleDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(NSString *key, double value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue doubleValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + double unwrappedValue = [aValue doubleValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictDoubleFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictDoubleField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueDouble) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndDoublesUsingBlock:^(NSString *key, double value, BOOL *stop) { + #pragma unused(stop) + block(key, [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); + }]; +} + +- (BOOL)getDouble:(nullable double *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + *value = [wrapped doubleValue]; + } + return (wrapped != NULL); +} + +- (void)addEntriesFromDictionary:(GPBStringDoubleDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +@end + +#pragma mark - String -> Enum + +@implementation GPBStringEnumDictionary { + @package + NSMutableDictionary *_dictionary; + GPBEnumValidationFunc _validationFunc; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const NSString * [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] init]; + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + if (count && rawValues && keys) { + for (NSUInteger i = 0; i < count; ++i) { + if (!keys[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(rawValues[i]) forKey:keys[i]]; + } + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBStringEnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBStringEnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBStringEnumDictionary class]]) { + return NO; + } + GPBStringEnumDictionary *otherDictionary = other; + return [_dictionary isEqual:otherDictionary->_dictionary]; +} + +- (NSUInteger)hash { + return _dictionary.count; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; +} + +- (NSUInteger)count { + return _dictionary.count; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(NSString *key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + block(aKey, [aValue intValue], &stop); + if (stop) { + break; + } + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + NSDictionary *internal = _dictionary; + NSUInteger count = internal.count; + if (count == 0) { + return 0; + } + + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + size_t result = 0; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + GPBDataType keyDataType = field.mapKeyDataType; + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + NSDictionary *internal = _dictionary; + NSEnumerator *keys = [internal keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = internal[aKey]; + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + NSString *unwrappedKey = aKey; + int32_t unwrappedValue = [aValue intValue]; + size_t msgSize = ComputeDictStringFieldSize(unwrappedKey, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(unwrappedValue, kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictStringField(outputStream, unwrappedKey, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, unwrappedValue, kMapValueFieldNumber, valueDataType); + } +} + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictStringFieldSize(key->valueString, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictStringField(outputStream, key->valueString, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + [_dictionary setObject:@(value->valueEnum) forKey:key->valueString]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + [self enumerateKeysAndRawValuesUsingBlock:^(NSString *key, int32_t value, BOOL *stop) { + #pragma unused(stop) + block(key, @(value)); + }]; +} + +- (BOOL)getEnum:(int32_t *)value forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && value) { + int32_t result = [wrapped intValue]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return (wrapped != NULL); +} + +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(NSString *)key { + NSNumber *wrapped = [_dictionary objectForKey:key]; + if (wrapped && rawValue) { + *rawValue = [wrapped intValue]; + } + return (wrapped != NULL); +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(NSString *key, int32_t value, BOOL *stop))block { + GPBEnumValidationFunc func = _validationFunc; + BOOL stop = NO; + NSEnumerator *keys = [_dictionary keyEnumerator]; + NSString *aKey; + while ((aKey = [keys nextObject])) { + NSNumber *aValue = _dictionary[aKey]; + int32_t unwrapped = [aValue intValue]; + if (!func(unwrapped)) { + unwrapped = kGPBUnrecognizedEnumeratorValue; + } + block(aKey, unwrapped, &stop); + if (stop) { + break; + } + } +} + +- (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary { + if (otherDictionary) { + [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setRawValue:(int32_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(NSString *)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +- (void)removeAll { + [_dictionary removeAllObjects]; +} + +- (void)setEnum:(int32_t)value forKey:(NSString *)key { + if (!key) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil key to a Dictionary"]; + } + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBStringEnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + + [_dictionary setObject:@(value) forKey:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +@end + +//%PDDM-EXPAND-END (5 expansions) + + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt32, uint32_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> UInt32 + +@implementation GPBBoolUInt32Dictionary { + @package + uint32_t _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt32s:(const uint32_t [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolUInt32Dictionary *)dictionary { + self = [self initWithUInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt32s:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolUInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolUInt32Dictionary class]]) { + return NO; + } + GPBBoolUInt32Dictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %u", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %u", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getUInt32:(uint32_t *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueUInt32; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%u", _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%u", _values[1]]); + } +} + +- (void)enumerateKeysAndUInt32sUsingBlock: + (void (^)(BOOL key, uint32_t value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictUInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictUInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictUInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolUInt32Dictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt32:(uint32_t)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt32ForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int32, int32_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Int32 + +@implementation GPBBoolInt32Dictionary { + @package + int32_t _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt32s:(const int32_t [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolInt32Dictionary *)dictionary { + self = [self initWithInt32s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt32s:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolInt32Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolInt32Dictionary class]]) { + return NO; + } + GPBBoolInt32Dictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %d", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %d", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getInt32:(int32_t *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueInt32; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%d", _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%d", _values[1]]); + } +} + +- (void)enumerateKeysAndInt32sUsingBlock: + (void (^)(BOOL key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolInt32Dictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt32:(int32_t)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt32ForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt64, uint64_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> UInt64 + +@implementation GPBBoolUInt64Dictionary { + @package + uint64_t _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithUInt64s:(const uint64_t [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolUInt64Dictionary *)dictionary { + self = [self initWithUInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithUInt64s:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolUInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolUInt64Dictionary class]]) { + return NO; + } + GPBBoolUInt64Dictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %llu", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %llu", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getUInt64:(uint64_t *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueUInt64; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%llu", _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%llu", _values[1]]); + } +} + +- (void)enumerateKeysAndUInt64sUsingBlock: + (void (^)(BOOL key, uint64_t value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictUInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictUInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictUInt64Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolUInt64Dictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setUInt64:(uint64_t)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeUInt64ForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int64, int64_t) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Int64 + +@implementation GPBBoolInt64Dictionary { + @package + int64_t _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithInt64s:(const int64_t [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolInt64Dictionary *)dictionary { + self = [self initWithInt64s:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithInt64s:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolInt64Dictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolInt64Dictionary class]]) { + return NO; + } + GPBBoolInt64Dictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %lld", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %lld", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getInt64:(int64_t *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueInt64; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%lld", _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%lld", _values[1]]); + } +} + +- (void)enumerateKeysAndInt64sUsingBlock: + (void (^)(BOOL key, int64_t value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictInt64Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolInt64Dictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setInt64:(int64_t)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeInt64ForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Bool, BOOL) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Bool + +@implementation GPBBoolBoolDictionary { + @package + BOOL _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithBools:(const BOOL [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolBoolDictionary *)dictionary { + self = [self initWithBools:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithBools:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolBoolDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolBoolDictionary class]]) { + return NO; + } + GPBBoolBoolDictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %d", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %d", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getBool:(BOOL *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueBool; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", (_values[0] ? @"true" : @"false")); + } + if (_valueSet[1]) { + block(@"true", (_values[1] ? @"true" : @"false")); + } +} + +- (void)enumerateKeysAndBoolsUsingBlock: + (void (^)(BOOL key, BOOL value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictBoolFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictBoolFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictBoolField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolBoolDictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setBool:(BOOL)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeBoolForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Float, float) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Float + +@implementation GPBBoolFloatDictionary { + @package + float _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithFloats:(const float [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolFloatDictionary *)dictionary { + self = [self initWithFloats:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithFloats:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolFloatDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolFloatDictionary class]]) { + return NO; + } + GPBBoolFloatDictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %f", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %f", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getFloat:(float *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueFloat; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%.*g", FLT_DIG, _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%.*g", FLT_DIG, _values[1]]); + } +} + +- (void)enumerateKeysAndFloatsUsingBlock: + (void (^)(BOOL key, float value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictFloatFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictFloatFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictFloatField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolFloatDictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setFloat:(float)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeFloatForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Double, double) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Double + +@implementation GPBBoolDoubleDictionary { + @package + double _values[2]; + BOOL _valueSet[2]; +} + +- (instancetype)init { + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithDoubles:(const double [])values + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = values[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolDoubleDictionary *)dictionary { + self = [self initWithDoubles:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithDoubles:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolDoubleDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolDoubleDictionary class]]) { + return NO; + } + GPBBoolDoubleDictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %lf", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %lf", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getDouble:(double *)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + *value = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueDouble; + _valueSet[idx] = YES; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", [NSString stringWithFormat:@"%.*lg", DBL_DIG, _values[0]]); + } + if (_valueSet[1]) { + block(@"true", [NSString stringWithFormat:@"%.*lg", DBL_DIG, _values[1]]); + } +} + +- (void)enumerateKeysAndDoublesUsingBlock: + (void (^)(BOOL key, double value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictDoubleFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictDoubleFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictDoubleField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolDoubleDictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setDouble:(double)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeDoubleForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(Object, id) +// This block of code is generated, do not edit it directly. + +#pragma mark - Bool -> Object + +@implementation GPBBoolObjectDictionary { + @package + id _values[2]; +} + +- (instancetype)init { + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + for (NSUInteger i = 0; i < count; ++i) { + if (!objects[i]) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + int idx = keys[i] ? 1 : 0; + [_values[idx] release]; + _values[idx] = (id)[objects[i] retain]; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolObjectDictionary *)dictionary { + self = [self initWithObjects:NULL forKeys:NULL count:0]; + if (self) { + if (dictionary) { + _values[0] = [dictionary->_values[0] retain]; + _values[1] = [dictionary->_values[1] retain]; + } + } + return self; +} + +- (instancetype)initWithCapacity:(NSUInteger)numItems { + #pragma unused(numItems) + return [self initWithObjects:NULL forKeys:NULL count:0]; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_values[0] release]; + [_values[1] release]; + [super dealloc]; +} + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolObjectDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolObjectDictionary class]]) { + return NO; + } + GPBBoolObjectDictionary *otherDictionary = other; + if (((_values[0] != nil) != (otherDictionary->_values[0] != nil)) || + ((_values[1] != nil) != (otherDictionary->_values[1] != nil))) { + return NO; + } + if (((_values[0] != nil) && (![_values[0] isEqual:otherDictionary->_values[0]])) || + ((_values[1] != nil) && (![_values[1] isEqual:otherDictionary->_values[1]]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return ((_values[0] != nil) ? 1 : 0) + ((_values[1] != nil) ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if ((_values[0] != nil)) { + [result appendFormat:@"NO: %@", _values[0]]; + } + if ((_values[1] != nil)) { + [result appendFormat:@"YES: %@", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return ((_values[0] != nil) ? 1 : 0) + ((_values[1] != nil) ? 1 : 0); +} + +- (id)objectForKey:(BOOL)key { + return _values[key ? 1 : 0]; +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + [_values[idx] release]; + _values[idx] = [value->valueString retain]; +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_values[0] != nil) { + block(@"false", _values[0]); + } + if ((_values[1] != nil)) { + block(@"true", _values[1]); + } +} + +- (void)enumerateKeysAndObjectsUsingBlock: + (void (^)(BOOL key, id object, BOOL *stop))block { + BOOL stop = NO; + if (_values[0] != nil) { + block(NO, _values[0], &stop); + } + if (!stop && (_values[1] != nil)) { + block(YES, _values[1], &stop); + } +} + +- (BOOL)isInitialized { + if (_values[0] && ![_values[0] isInitialized]) { + return NO; + } + if (_values[1] && ![_values[1] isInitialized]) { + return NO; + } + return YES; +} + +- (instancetype)deepCopyWithZone:(NSZone *)zone { + GPBBoolObjectDictionary *newDict = + [[GPBBoolObjectDictionary alloc] init]; + for (int i = 0; i < 2; ++i) { + if (_values[i] != nil) { + newDict->_values[i] = [_values[i] copyWithZone:zone]; + } + } + return newDict; +} + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_values[i] != nil) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictObjectFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_values[i] != nil) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictObjectFieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictObjectField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)addEntriesFromDictionary:(GPBBoolObjectDictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_values[i] != nil) { + [_values[i] release]; + _values[i] = [otherDictionary->_values[i] retain]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setObject:(id)object forKey:(BOOL)key { + if (!object) { + [NSException raise:NSInvalidArgumentException + format:@"Attempting to add nil object to a Dictionary"]; + } + int idx = (key ? 1 : 0); + [_values[idx] release]; + _values[idx] = [object retain]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(BOOL)aKey { + int idx = (aKey ? 1 : 0); + [_values[idx] release]; + _values[idx] = nil; +} + +- (void)removeAll { + for (int i = 0; i < 2; ++i) { + [_values[i] release]; + _values[i] = nil; + } +} + +@end + +//%PDDM-EXPAND-END (8 expansions) + +#pragma mark - Bool -> Enum + +@implementation GPBBoolEnumDictionary { + @package + GPBEnumValidationFunc _validationFunc; + int32_t _values[2]; + BOOL _valueSet[2]; +} + +@synthesize validationFunc = _validationFunc; + +- (instancetype)init { + return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + rawValues:(const int32_t [])rawValues + forKeys:(const BOOL [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); + for (NSUInteger i = 0; i < count; ++i) { + int idx = keys[i] ? 1 : 0; + _values[idx] = rawValues[i]; + _valueSet[idx] = YES; + } + } + return self; +} + +- (instancetype)initWithDictionary:(GPBBoolEnumDictionary *)dictionary { + self = [self initWithValidationFunction:dictionary.validationFunc + rawValues:NULL + forKeys:NULL + count:0]; + if (self) { + if (dictionary) { + for (int i = 0; i < 2; ++i) { + if (dictionary->_valueSet[i]) { + _values[i] = dictionary->_values[i]; + _valueSet[i] = YES; + } + } + } + } + return self; +} + +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func + capacity:(NSUInteger)numItems { +#pragma unused(numItems) + return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; +} + +#if !defined(NS_BLOCK_ASSERTIONS) +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [super dealloc]; +} +#endif // !defined(NS_BLOCK_ASSERTIONS) + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[GPBBoolEnumDictionary allocWithZone:zone] initWithDictionary:self]; +} + +- (BOOL)isEqual:(id)other { + if (self == other) { + return YES; + } + if (![other isKindOfClass:[GPBBoolEnumDictionary class]]) { + return NO; + } + GPBBoolEnumDictionary *otherDictionary = other; + if ((_valueSet[0] != otherDictionary->_valueSet[0]) || + (_valueSet[1] != otherDictionary->_valueSet[1])) { + return NO; + } + if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || + (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { + return NO; + } + return YES; +} + +- (NSUInteger)hash { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; + if (_valueSet[0]) { + [result appendFormat:@"NO: %d", _values[0]]; + } + if (_valueSet[1]) { + [result appendFormat:@"YES: %d", _values[1]]; + } + [result appendString:@" }"]; + return result; +} + +- (NSUInteger)count { + return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); +} + +- (BOOL)getEnum:(int32_t*)value forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (value) { + int32_t result = _values[idx]; + if (!_validationFunc(result)) { + result = kGPBUnrecognizedEnumeratorValue; + } + *value = result; + } + return YES; + } + return NO; +} + +- (BOOL)getRawValue:(int32_t*)rawValue forKey:(BOOL)key { + int idx = (key ? 1 : 0); + if (_valueSet[idx]) { + if (rawValue) { + *rawValue = _values[idx]; + } + return YES; + } + return NO; +} + +- (void)enumerateKeysAndRawValuesUsingBlock: + (void (^)(BOOL key, int32_t value, BOOL *stop))block { + BOOL stop = NO; + if (_valueSet[0]) { + block(NO, _values[0], &stop); + } + if (!stop && _valueSet[1]) { + block(YES, _values[1], &stop); + } +} + +- (void)enumerateKeysAndEnumsUsingBlock: + (void (^)(BOOL key, int32_t rawValue, BOOL *stop))block { + BOOL stop = NO; + GPBEnumValidationFunc func = _validationFunc; + int32_t validatedValue; + if (_valueSet[0]) { + validatedValue = _values[0]; + if (!func(validatedValue)) { + validatedValue = kGPBUnrecognizedEnumeratorValue; + } + block(NO, validatedValue, &stop); + } + if (!stop && _valueSet[1]) { + validatedValue = _values[1]; + if (!func(validatedValue)) { + validatedValue = kGPBUnrecognizedEnumeratorValue; + } + block(YES, validatedValue, &stop); + } +} + +//%PDDM-EXPAND SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) +// This block of code is generated, do not edit it directly. + +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType { + size_t msgSize = ComputeDictBoolFieldSize(key->valueBool, kMapKeyFieldNumber, keyDataType); + msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); + NSMutableData *data = [NSMutableData dataWithLength:msgSize]; + GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; + WriteDictBoolField(outputStream, key->valueBool, kMapKeyFieldNumber, keyDataType); + WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); + [outputStream release]; + return data; +} + +//%PDDM-EXPAND-END SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) + +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSUInteger count = 0; + size_t result = 0; + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + ++count; + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; + } + } + size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); + result += tagSize * count; + return result; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field { + GPBDataType valueDataType = GPBGetFieldDataType(field); + uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); + for (int i = 0; i < 2; ++i) { + if (_valueSet[i]) { + // Write the tag. + [outputStream writeInt32NoTag:tag]; + // Write the size of the message. + size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); + [outputStream writeInt32NoTag:(int32_t)msgSize]; + // Write the fields. + WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); + WriteDictInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); + } + } +} + +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { + if (_valueSet[0]) { + block(@"false", @(_values[0])); + } + if (_valueSet[1]) { + block(@"true", @(_values[1])); + } +} + +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key { + int idx = (key->valueBool ? 1 : 0); + _values[idx] = value->valueInt32; + _valueSet[idx] = YES; +} + +- (void)addRawEntriesFromDictionary:(GPBBoolEnumDictionary *)otherDictionary { + if (otherDictionary) { + for (int i = 0; i < 2; ++i) { + if (otherDictionary->_valueSet[i]) { + _valueSet[i] = YES; + _values[i] = otherDictionary->_values[i]; + } + } + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } + } +} + +- (void)setEnum:(int32_t)value forKey:(BOOL)key { + if (!_validationFunc(value)) { + [NSException raise:NSInvalidArgumentException + format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", + value]; + } + int idx = (key ? 1 : 0); + _values[idx] = value; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)setRawValue:(int32_t)rawValue forKey:(BOOL)key { + int idx = (key ? 1 : 0); + _values[idx] = rawValue; + _valueSet[idx] = YES; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeEnumForKey:(BOOL)aKey { + _valueSet[aKey ? 1 : 0] = NO; +} + +- (void)removeAll { + _valueSet[0] = NO; + _valueSet[1] = NO; +} + +@end + +#pragma mark - NSDictionary Subclass + +@implementation GPBAutocreatedDictionary { + NSMutableDictionary *_dictionary; +} + +- (void)dealloc { + NSAssert(!_autocreator, + @"%@: Autocreator must be cleared before release, autocreator: %@", + [self class], _autocreator); + [_dictionary release]; + [super dealloc]; +} + +#pragma mark Required NSDictionary overrides + +- (instancetype)initWithObjects:(const id [])objects + forKeys:(const id [])keys + count:(NSUInteger)count { + self = [super init]; + if (self) { + _dictionary = [[NSMutableDictionary alloc] initWithObjects:objects + forKeys:keys + count:count]; + } + return self; +} + +- (NSUInteger)count { + return [_dictionary count]; +} + +- (id)objectForKey:(id)aKey { + return [_dictionary objectForKey:aKey]; +} + +- (NSEnumerator *)keyEnumerator { + if (_dictionary == nil) { + _dictionary = [[NSMutableDictionary alloc] init]; + } + return [_dictionary keyEnumerator]; +} + +#pragma mark Required NSMutableDictionary overrides + +// Only need to call GPBAutocreatedDictionaryModified() when adding things +// since we only autocreate empty dictionaries. + +- (void)setObject:(id)anObject forKey:(id)aKey { + if (_dictionary == nil) { + _dictionary = [[NSMutableDictionary alloc] init]; + } + [_dictionary setObject:anObject forKey:aKey]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)removeObjectForKey:(id)aKey { + [_dictionary removeObjectForKey:aKey]; +} + +#pragma mark Extra things hooked + +- (id)copyWithZone:(NSZone *)zone { + if (_dictionary == nil) { + return [[NSMutableDictionary allocWithZone:zone] init]; + } + return [_dictionary copyWithZone:zone]; +} + +- (id)mutableCopyWithZone:(NSZone *)zone { + if (_dictionary == nil) { + return [[NSMutableDictionary allocWithZone:zone] init]; + } + return [_dictionary mutableCopyWithZone:zone]; +} + +// Not really needed, but subscripting is likely common enough it doesn't hurt +// to ensure it goes directly to the real NSMutableDictionary. +- (id)objectForKeyedSubscript:(id)key { + return [_dictionary objectForKeyedSubscript:key]; +} + +// Not really needed, but subscripting is likely common enough it doesn't hurt +// to ensure it goes directly to the real NSMutableDictionary. +- (void)setObject:(id)obj forKeyedSubscript:(id)key { + if (_dictionary == nil) { + _dictionary = [[NSMutableDictionary alloc] init]; + } + [_dictionary setObject:obj forKeyedSubscript:key]; + if (_autocreator) { + GPBAutocreatedDictionaryModified(_autocreator, self); + } +} + +- (void)enumerateKeysAndObjectsUsingBlock:(void (NS_NOESCAPE ^)(id key, + id obj, + BOOL *stop))block { + [_dictionary enumerateKeysAndObjectsUsingBlock:block]; +} + +- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts + usingBlock:(void (NS_NOESCAPE ^)(id key, + id obj, + BOOL *stop))block { + [_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block]; +} + +@end + +#pragma clang diagnostic pop diff --git a/My Mind/Pods/Protobuf/objectivec/GPBDictionary_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBDictionary_PackagePrivate.h new file mode 100644 index 0000000..7b921e8 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBDictionary_PackagePrivate.h @@ -0,0 +1,488 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBDictionary.h" + +@class GPBCodedInputStream; +@class GPBCodedOutputStream; +@class GPBExtensionRegistry; +@class GPBFieldDescriptor; + +@protocol GPBDictionaryInternalsProtocol +- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field; +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream + asField:(GPBFieldDescriptor *)field; +- (void)setGPBGenericValue:(GPBGenericValue *)value + forGPBGenericValueKey:(GPBGenericValue *)key; +- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block; +@end + +//%PDDM-DEFINE DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(KEY_NAME) +//%DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(KEY_NAME) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Object, Object) +//%PDDM-DEFINE DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(KEY_NAME) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, UInt32, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Int32, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, UInt64, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Int64, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Bool, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Float, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Double, Basic) +//%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Enum, Enum) + +//%PDDM-DEFINE DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, VALUE_NAME, HELPER) +//%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary () { +//% @package +//% GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +//%} +//%EXTRA_DICTIONARY_PRIVATE_INTERFACES_##HELPER()@end +//% + +//%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Basic() +// Empty +//%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Object() +//%- (BOOL)isInitialized; +//%- (instancetype)deepCopyWithZone:(NSZone *)zone +//% __attribute__((ns_returns_retained)); +//% +//%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Enum() +//%- (NSData *)serializedDataForUnknownValue:(int32_t)value +//% forKey:(GPBGenericValue *)key +//% keyDataType:(GPBDataType)keyDataType; +//% + +//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt32) +// This block of code is generated, do not edit it directly. + +@interface GPBUInt32UInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32Int32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32UInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32Int64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32BoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32FloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32DoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt32EnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +@interface GPBUInt32ObjectDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (BOOL)isInitialized; +- (instancetype)deepCopyWithZone:(NSZone *)zone + __attribute__((ns_returns_retained)); +@end + +//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int32) +// This block of code is generated, do not edit it directly. + +@interface GPBInt32UInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32Int32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32UInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32Int64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32BoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32FloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32DoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt32EnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +@interface GPBInt32ObjectDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (BOOL)isInitialized; +- (instancetype)deepCopyWithZone:(NSZone *)zone + __attribute__((ns_returns_retained)); +@end + +//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt64) +// This block of code is generated, do not edit it directly. + +@interface GPBUInt64UInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64Int32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64UInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64Int64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64BoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64FloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64DoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBUInt64EnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +@interface GPBUInt64ObjectDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (BOOL)isInitialized; +- (instancetype)deepCopyWithZone:(NSZone *)zone + __attribute__((ns_returns_retained)); +@end + +//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int64) +// This block of code is generated, do not edit it directly. + +@interface GPBInt64UInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64Int32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64UInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64Int64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64BoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64FloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64DoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBInt64EnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +@interface GPBInt64ObjectDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (BOOL)isInitialized; +- (instancetype)deepCopyWithZone:(NSZone *)zone + __attribute__((ns_returns_retained)); +@end + +//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Bool) +// This block of code is generated, do not edit it directly. + +@interface GPBBoolUInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolUInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolBoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolFloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolDoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBBoolEnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +@interface GPBBoolObjectDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (BOOL)isInitialized; +- (instancetype)deepCopyWithZone:(NSZone *)zone + __attribute__((ns_returns_retained)); +@end + +//%PDDM-EXPAND DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(String) +// This block of code is generated, do not edit it directly. + +@interface GPBStringUInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringInt32Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringUInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringInt64Dictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringBoolDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringFloatDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringDoubleDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +@interface GPBStringEnumDictionary () { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +- (NSData *)serializedDataForUnknownValue:(int32_t)value + forKey:(GPBGenericValue *)key + keyDataType:(GPBDataType)keyDataType; +@end + +//%PDDM-EXPAND-END (6 expansions) + +#pragma mark - NSDictionary Subclass + +@interface GPBAutocreatedDictionary : NSMutableDictionary { + @package + GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; +} +@end + +#pragma mark - Helpers + +CF_EXTERN_C_BEGIN + +// Helper to compute size when an NSDictionary is used for the map instead +// of a custom type. +size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, + GPBFieldDescriptor *field); + +// Helper to write out when an NSDictionary is used for the map instead +// of a custom type. +void GPBDictionaryWriteToStreamInternalHelper( + GPBCodedOutputStream *outputStream, NSDictionary *dict, + GPBFieldDescriptor *field); + +// Helper to check message initialization when an NSDictionary is used for +// the map instead of a custom type. +BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, + GPBFieldDescriptor *field); + +// Helper to read a map instead. +void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, + GPBExtensionRegistry *registry, + GPBFieldDescriptor *field, + GPBMessage *parentMessage); + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.h b/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.h new file mode 100644 index 0000000..2b980ae --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.h @@ -0,0 +1,50 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBDescriptor.h" + +@class GPBCodedInputStream; +@class GPBCodedOutputStream; +@class GPBExtensionRegistry; + +void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, + BOOL isPackedOnStream, + GPBCodedInputStream *input, + GPBExtensionRegistry *extensionRegistry, + GPBMessage *message); + +size_t GPBComputeExtensionSerializedSizeIncludingTag( + GPBExtensionDescriptor *extension, id value); + +void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, + id value, + GPBCodedOutputStream *output); diff --git a/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.m b/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.m new file mode 100644 index 0000000..290c82a --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBExtensionInternals.m @@ -0,0 +1,391 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBExtensionInternals.h" + +#import + +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream_PackagePrivate.h" +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" + +static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, + GPBCodedInputStream *input, + GPBExtensionRegistry *extensionRegistry, + GPBMessage *existingValue) + __attribute__((ns_returns_retained)); + +GPB_INLINE size_t DataTypeSize(GPBDataType dataType) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wswitch-enum" + switch (dataType) { + case GPBDataTypeBool: + return 1; + case GPBDataTypeFixed32: + case GPBDataTypeSFixed32: + case GPBDataTypeFloat: + return 4; + case GPBDataTypeFixed64: + case GPBDataTypeSFixed64: + case GPBDataTypeDouble: + return 8; + default: + return 0; + } +#pragma clang diagnostic pop +} + +static size_t ComputePBSerializedSizeNoTagOfObject(GPBDataType dataType, id object) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + return GPBCompute##TYPE##SizeNoTag([(NSNumber *)object ACCESSOR]); +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ + return GPBCompute##TYPE##SizeNoTag(object); + switch (dataType) { + FIELD_CASE(Bool, boolValue) + FIELD_CASE(Float, floatValue) + FIELD_CASE(Double, doubleValue) + FIELD_CASE(Int32, intValue) + FIELD_CASE(SFixed32, intValue) + FIELD_CASE(SInt32, intValue) + FIELD_CASE(Enum, intValue) + FIELD_CASE(Int64, longLongValue) + FIELD_CASE(SInt64, longLongValue) + FIELD_CASE(SFixed64, longLongValue) + FIELD_CASE(UInt32, unsignedIntValue) + FIELD_CASE(Fixed32, unsignedIntValue) + FIELD_CASE(UInt64, unsignedLongLongValue) + FIELD_CASE(Fixed64, unsignedLongLongValue) + FIELD_CASE2(Bytes) + FIELD_CASE2(String) + FIELD_CASE2(Message) + FIELD_CASE2(Group) + } +#undef FIELD_CASE +#undef FIELD_CASE2 +} + +static size_t ComputeSerializedSizeIncludingTagOfObject( + GPBExtensionDescription *description, id object) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + return GPBCompute##TYPE##Size(description->fieldNumber, \ + [(NSNumber *)object ACCESSOR]); +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ + return GPBCompute##TYPE##Size(description->fieldNumber, object); + switch (description->dataType) { + FIELD_CASE(Bool, boolValue) + FIELD_CASE(Float, floatValue) + FIELD_CASE(Double, doubleValue) + FIELD_CASE(Int32, intValue) + FIELD_CASE(SFixed32, intValue) + FIELD_CASE(SInt32, intValue) + FIELD_CASE(Enum, intValue) + FIELD_CASE(Int64, longLongValue) + FIELD_CASE(SInt64, longLongValue) + FIELD_CASE(SFixed64, longLongValue) + FIELD_CASE(UInt32, unsignedIntValue) + FIELD_CASE(Fixed32, unsignedIntValue) + FIELD_CASE(UInt64, unsignedLongLongValue) + FIELD_CASE(Fixed64, unsignedLongLongValue) + FIELD_CASE2(Bytes) + FIELD_CASE2(String) + FIELD_CASE2(Group) + case GPBDataTypeMessage: + if (GPBExtensionIsWireFormat(description)) { + return GPBComputeMessageSetExtensionSize(description->fieldNumber, + object); + } else { + return GPBComputeMessageSize(description->fieldNumber, object); + } + } +#undef FIELD_CASE +#undef FIELD_CASE2 +} + +static size_t ComputeSerializedSizeIncludingTagOfArray( + GPBExtensionDescription *description, NSArray *values) { + if (GPBExtensionIsPacked(description)) { + size_t size = 0; + size_t typeSize = DataTypeSize(description->dataType); + if (typeSize != 0) { + size = values.count * typeSize; + } else { + for (id value in values) { + size += + ComputePBSerializedSizeNoTagOfObject(description->dataType, value); + } + } + return size + GPBComputeTagSize(description->fieldNumber) + + GPBComputeRawVarint32SizeForInteger(size); + } else { + size_t size = 0; + for (id value in values) { + size += ComputeSerializedSizeIncludingTagOfObject(description, value); + } + return size; + } +} + +static void WriteObjectIncludingTagToCodedOutputStream( + id object, GPBExtensionDescription *description, + GPBCodedOutputStream *output) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + [output write##TYPE:description->fieldNumber \ + value:[(NSNumber *)object ACCESSOR]]; \ + return; +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ + [output write##TYPE:description->fieldNumber value:object]; \ + return; + switch (description->dataType) { + FIELD_CASE(Bool, boolValue) + FIELD_CASE(Float, floatValue) + FIELD_CASE(Double, doubleValue) + FIELD_CASE(Int32, intValue) + FIELD_CASE(SFixed32, intValue) + FIELD_CASE(SInt32, intValue) + FIELD_CASE(Enum, intValue) + FIELD_CASE(Int64, longLongValue) + FIELD_CASE(SInt64, longLongValue) + FIELD_CASE(SFixed64, longLongValue) + FIELD_CASE(UInt32, unsignedIntValue) + FIELD_CASE(Fixed32, unsignedIntValue) + FIELD_CASE(UInt64, unsignedLongLongValue) + FIELD_CASE(Fixed64, unsignedLongLongValue) + FIELD_CASE2(Bytes) + FIELD_CASE2(String) + FIELD_CASE2(Group) + case GPBDataTypeMessage: + if (GPBExtensionIsWireFormat(description)) { + [output writeMessageSetExtension:description->fieldNumber value:object]; + } else { + [output writeMessage:description->fieldNumber value:object]; + } + return; + } +#undef FIELD_CASE +#undef FIELD_CASE2 +} + +static void WriteObjectNoTagToCodedOutputStream( + id object, GPBExtensionDescription *description, + GPBCodedOutputStream *output) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + [output write##TYPE##NoTag:[(NSNumber *)object ACCESSOR]]; \ + return; +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ + [output write##TYPE##NoTag:object]; \ + return; + switch (description->dataType) { + FIELD_CASE(Bool, boolValue) + FIELD_CASE(Float, floatValue) + FIELD_CASE(Double, doubleValue) + FIELD_CASE(Int32, intValue) + FIELD_CASE(SFixed32, intValue) + FIELD_CASE(SInt32, intValue) + FIELD_CASE(Enum, intValue) + FIELD_CASE(Int64, longLongValue) + FIELD_CASE(SInt64, longLongValue) + FIELD_CASE(SFixed64, longLongValue) + FIELD_CASE(UInt32, unsignedIntValue) + FIELD_CASE(Fixed32, unsignedIntValue) + FIELD_CASE(UInt64, unsignedLongLongValue) + FIELD_CASE(Fixed64, unsignedLongLongValue) + FIELD_CASE2(Bytes) + FIELD_CASE2(String) + FIELD_CASE2(Message) + case GPBDataTypeGroup: + [output writeGroupNoTag:description->fieldNumber value:object]; + return; + } +#undef FIELD_CASE +#undef FIELD_CASE2 +} + +static void WriteArrayIncludingTagsToCodedOutputStream( + NSArray *values, GPBExtensionDescription *description, + GPBCodedOutputStream *output) { + if (GPBExtensionIsPacked(description)) { + [output writeTag:description->fieldNumber + format:GPBWireFormatLengthDelimited]; + size_t dataSize = 0; + size_t typeSize = DataTypeSize(description->dataType); + if (typeSize != 0) { + dataSize = values.count * typeSize; + } else { + for (id value in values) { + dataSize += + ComputePBSerializedSizeNoTagOfObject(description->dataType, value); + } + } + [output writeRawVarintSizeTAs32:dataSize]; + for (id value in values) { + WriteObjectNoTagToCodedOutputStream(value, description, output); + } + } else { + for (id value in values) { + WriteObjectIncludingTagToCodedOutputStream(value, description, output); + } + } +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, + BOOL isPackedOnStream, + GPBCodedInputStream *input, + GPBExtensionRegistry *extensionRegistry, + GPBMessage *message) { + GPBExtensionDescription *description = extension->description_; + GPBCodedInputStreamState *state = &input->state_; + if (isPackedOnStream) { + NSCAssert(GPBExtensionIsRepeated(description), + @"How was it packed if it isn't repeated?"); + int32_t length = GPBCodedInputStreamReadInt32(state); + size_t limit = GPBCodedInputStreamPushLimit(state, length); + while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { + id value = NewSingleValueFromInputStream(extension, + input, + extensionRegistry, + nil); + [message addExtension:extension value:value]; + [value release]; + } + GPBCodedInputStreamPopLimit(state, limit); + } else { + id existingValue = nil; + BOOL isRepeated = GPBExtensionIsRepeated(description); + if (!isRepeated && GPBDataTypeIsMessage(description->dataType)) { + existingValue = [message getExistingExtension:extension]; + } + id value = NewSingleValueFromInputStream(extension, + input, + extensionRegistry, + existingValue); + if (isRepeated) { + [message addExtension:extension value:value]; + } else { + [message setExtension:extension value:value]; + } + [value release]; + } +} + +void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, + id value, + GPBCodedOutputStream *output) { + GPBExtensionDescription *description = extension->description_; + if (GPBExtensionIsRepeated(description)) { + WriteArrayIncludingTagsToCodedOutputStream(value, description, output); + } else { + WriteObjectIncludingTagToCodedOutputStream(value, description, output); + } +} + +size_t GPBComputeExtensionSerializedSizeIncludingTag( + GPBExtensionDescriptor *extension, id value) { + GPBExtensionDescription *description = extension->description_; + if (GPBExtensionIsRepeated(description)) { + return ComputeSerializedSizeIncludingTagOfArray(description, value); + } else { + return ComputeSerializedSizeIncludingTagOfObject(description, value); + } +} + +// Note that this returns a retained value intentionally. +static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, + GPBCodedInputStream *input, + GPBExtensionRegistry *extensionRegistry, + GPBMessage *existingValue) { + GPBExtensionDescription *description = extension->description_; + GPBCodedInputStreamState *state = &input->state_; + switch (description->dataType) { + case GPBDataTypeBool: return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)]; + case GPBDataTypeFixed32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)]; + case GPBDataTypeSFixed32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)]; + case GPBDataTypeFloat: return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)]; + case GPBDataTypeFixed64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)]; + case GPBDataTypeSFixed64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)]; + case GPBDataTypeDouble: return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)]; + case GPBDataTypeInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)]; + case GPBDataTypeInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)]; + case GPBDataTypeSInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)]; + case GPBDataTypeSInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)]; + case GPBDataTypeUInt32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)]; + case GPBDataTypeUInt64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)]; + case GPBDataTypeBytes: return GPBCodedInputStreamReadRetainedBytes(state); + case GPBDataTypeString: return GPBCodedInputStreamReadRetainedString(state); + case GPBDataTypeEnum: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)]; + case GPBDataTypeGroup: + case GPBDataTypeMessage: { + GPBMessage *message; + if (existingValue) { + message = [existingValue retain]; + } else { + GPBDescriptor *decriptor = [extension.msgClass descriptor]; + message = [[decriptor.messageClass alloc] init]; + } + + if (description->dataType == GPBDataTypeGroup) { + [input readGroup:description->fieldNumber + message:message + extensionRegistry:extensionRegistry]; + } else { + // description->dataType == GPBDataTypeMessage + if (GPBExtensionIsWireFormat(description)) { + // For MessageSet fields the message length will have already been + // read. + [message mergeFromCodedInputStream:input + extensionRegistry:extensionRegistry]; + } else { + [input readMessage:message extensionRegistry:extensionRegistry]; + } + } + + return message; + } + } + + return nil; +} + +#pragma clang diagnostic pop diff --git a/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.h b/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.h new file mode 100644 index 0000000..d79632d --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.h @@ -0,0 +1,87 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +@class GPBDescriptor; +@class GPBExtensionDescriptor; + +NS_ASSUME_NONNULL_BEGIN + +/** + * A table of known extensions, searchable by name or field number. When + * parsing a protocol message that might have extensions, you must provide a + * GPBExtensionRegistry in which you have registered any extensions that you + * want to be able to parse. Otherwise, those extensions will just be treated + * like unknown fields. + * + * The *Root classes provide `+extensionRegistry` for the extensions defined + * in a given file *and* all files it imports. You can also create a + * GPBExtensionRegistry, and merge those registries to handle parsing + * extensions defined from non overlapping files. + * + * ``` + * GPBExtensionRegistry *registry = [[MyProtoFileRoot extensionRegistry] copy]; + * [registry addExtension:[OtherMessage neededExtension]]; // Not in MyProtoFile + * NSError *parseError; + * MyMessage *msg = [MyMessage parseData:data extensionRegistry:registry error:&parseError]; + * ``` + **/ +@interface GPBExtensionRegistry : NSObject + +/** + * Adds the given GPBExtensionDescriptor to this registry. + * + * @param extension The extension description to add. + **/ +- (void)addExtension:(GPBExtensionDescriptor *)extension; + +/** + * Adds all the extensions from another registry to this registry. + * + * @param registry The registry to merge into this registry. + **/ +- (void)addExtensions:(GPBExtensionRegistry *)registry; + +/** + * Looks for the extension registered for the given field number on a given + * GPBDescriptor. + * + * @param descriptor The descriptor to look for a registered extension on. + * @param fieldNumber The field number of the extension to look for. + * + * @return The registered GPBExtensionDescriptor or nil if none was found. + **/ +- (nullable GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor + fieldNumber:(NSInteger)fieldNumber; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.m b/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.m new file mode 100644 index 0000000..b056a52 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBExtensionRegistry.m @@ -0,0 +1,130 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBExtensionRegistry.h" + +#import "GPBBootstrap.h" +#import "GPBDescriptor.h" + +@implementation GPBExtensionRegistry { + NSMutableDictionary *mutableClassMap_; +} + +- (instancetype)init { + if ((self = [super init])) { + mutableClassMap_ = [[NSMutableDictionary alloc] init]; + } + return self; +} + +- (void)dealloc { + [mutableClassMap_ release]; + [super dealloc]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (instancetype)copyWithZone:(NSZone *)zone { + GPBExtensionRegistry *result = [[[self class] allocWithZone:zone] init]; + [result addExtensions:self]; + return result; +} + +- (void)addExtension:(GPBExtensionDescriptor *)extension { + if (extension == nil) { + return; + } + + Class containingMessageClass = extension.containingMessageClass; + CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) + [mutableClassMap_ objectForKey:containingMessageClass]; + if (extensionMap == nil) { + // Use a custom dictionary here because the keys are numbers and conversion + // back and forth from NSNumber isn't worth the cost. + extensionMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, + &kCFTypeDictionaryValueCallBacks); + [mutableClassMap_ setObject:(id)extensionMap + forKey:(id)containingMessageClass]; + CFRelease(extensionMap); + } + + ssize_t key = extension.fieldNumber; + CFDictionarySetValue(extensionMap, (const void *)key, extension); +} + +- (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor + fieldNumber:(NSInteger)fieldNumber { + Class messageClass = descriptor.messageClass; + CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) + [mutableClassMap_ objectForKey:messageClass]; + ssize_t key = fieldNumber; + GPBExtensionDescriptor *result = + (extensionMap + ? CFDictionaryGetValue(extensionMap, (const void *)key) + : nil); + return result; +} + +static void CopyKeyValue(const void *key, const void *value, void *context) { + CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)context; + CFDictionarySetValue(extensionMap, key, value); +} + +- (void)addExtensions:(GPBExtensionRegistry *)registry { + if (registry == nil) { + // In the case where there are no extensions just ignore. + return; + } + NSMutableDictionary *otherClassMap = registry->mutableClassMap_; + [otherClassMap enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL * stop) { +#pragma unused(stop) + Class containingMessageClass = key; + CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value; + + CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) + [mutableClassMap_ objectForKey:containingMessageClass]; + if (extensionMap == nil) { + extensionMap = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, otherExtensionMap); + [mutableClassMap_ setObject:(id)extensionMap + forKey:(id)containingMessageClass]; + CFRelease(extensionMap); + } else { + CFDictionaryApplyFunction(otherExtensionMap, CopyKeyValue, extensionMap); + } + }]; +} + +#pragma clang diagnostic pop + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBMessage.h b/My Mind/Pods/Protobuf/objectivec/GPBMessage.h new file mode 100644 index 0000000..276740d --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBMessage.h @@ -0,0 +1,470 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBBootstrap.h" + +@class GPBDescriptor; +@class GPBCodedInputStream; +@class GPBCodedOutputStream; +@class GPBExtensionDescriptor; +@class GPBExtensionRegistry; +@class GPBFieldDescriptor; +@class GPBUnknownFieldSet; + +NS_ASSUME_NONNULL_BEGIN + +CF_EXTERN_C_BEGIN + +/** NSError domain used for errors. */ +extern NSString *const GPBMessageErrorDomain; + +/** Error codes for NSErrors originated in GPBMessage. */ +typedef NS_ENUM(NSInteger, GPBMessageErrorCode) { + /** Uncategorized error. */ + GPBMessageErrorCodeOther = -100, + /** Message couldn't be serialized because it is missing required fields. */ + GPBMessageErrorCodeMissingRequiredField = -101, +}; + +/** + * Key under which the GPBMessage error's reason is stored inside the userInfo + * dictionary. + **/ +extern NSString *const GPBErrorReasonKey; + +CF_EXTERN_C_END + +/** + * Base class that each generated message subclasses from. + * + * @note @c NSCopying support is a "deep copy", in that all sub objects are + * copied. Just like you wouldn't want a UIView/NSView trying to + * exist in two places, you don't want a sub message to be a property + * property of two other messages. + * + * @note While the class support NSSecureCoding, if the message has any + * extensions, they will end up reloaded in @c unknownFields as there is + * no way for the @c NSCoding plumbing to pass through a + * @c GPBExtensionRegistry. To support extensions, instead of passing the + * calls off to the Message, simple store the result of @c data, and then + * when loading, fetch the data and use + * @c +parseFromData:extensionRegistry:error: to provide an extension + * registry. + **/ +@interface GPBMessage : NSObject + +// If you add an instance method/property to this class that may conflict with +// fields declared in protos, you need to update objective_helpers.cc. The main +// cases are methods that take no arguments, or setFoo:/hasFoo: type methods. + +/** + * The set of unknown fields for this message. + * + * Only messages from proto files declared with "proto2" syntax support unknown + * fields. For "proto3" syntax, any unknown fields found while parsing are + * dropped. + **/ +@property(nonatomic, copy, nullable) GPBUnknownFieldSet *unknownFields; + +/** + * Whether the message, along with all submessages, have the required fields + * set. This is only applicable for files declared with "proto2" syntax, as + * there are no required fields for "proto3" syntax. + **/ +@property(nonatomic, readonly, getter=isInitialized) BOOL initialized; + +/** + * @return An autoreleased message with the default values set. + **/ ++ (instancetype)message; + +/** + * Creates a new instance by parsing the provided data. This method should be + * sent to the generated message class that the data should be interpreted as. + * If there is an error the method returns nil and the error is returned in + * errorPtr (when provided). + * + * @note In DEBUG builds, the parsed message is checked to be sure all required + * fields were provided, and the parse will fail if some are missing. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param data The data to parse. + * @param errorPtr An optional error pointer to fill in with a failure reason if + * the data can not be parsed. + * + * @return A new instance of the generated class. + **/ ++ (nullable instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr; + +/** + * Creates a new instance by parsing the data. This method should be sent to + * the generated message class that the data should be interpreted as. If + * there is an error the method returns nil and the error is returned in + * errorPtr (when provided). + * + * @note In DEBUG builds, the parsed message is checked to be sure all required + * fields were provided, and the parse will fail if some are missing. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param data The data to parse. + * @param extensionRegistry The extension registry to use to look up extensions. + * @param errorPtr An optional error pointer to fill in with a failure + * reason if the data can not be parsed. + * + * @return A new instance of the generated class. + **/ ++ (nullable instancetype)parseFromData:(NSData *)data + extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr; + +/** + * Creates a new instance by parsing the data from the given input stream. This + * method should be sent to the generated message class that the data should + * be interpreted as. If there is an error the method returns nil and the error + * is returned in errorPtr (when provided). + * + * @note In DEBUG builds, the parsed message is checked to be sure all required + * fields were provided, and the parse will fail if some are missing. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param input The stream to read data from. + * @param extensionRegistry The extension registry to use to look up extensions. + * @param errorPtr An optional error pointer to fill in with a failure + * reason if the data can not be parsed. + * + * @return A new instance of the generated class. + **/ ++ (nullable instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (nullable GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr; + +/** + * Creates a new instance by parsing the data from the given input stream. This + * method should be sent to the generated message class that the data should + * be interpreted as. If there is an error the method returns nil and the error + * is returned in errorPtr (when provided). + * + * @note Unlike the parseFrom... methods, this never checks to see if all of + * the required fields are set. So this method can be used to reload + * messages that may not be complete. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param input The stream to read data from. + * @param extensionRegistry The extension registry to use to look up extensions. + * @param errorPtr An optional error pointer to fill in with a failure + * reason if the data can not be parsed. + * + * @return A new instance of the generated class. + **/ ++ (nullable instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (nullable GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr; + +/** + * Initializes an instance by parsing the data. This method should be sent to + * the generated message class that the data should be interpreted as. If + * there is an error the method returns nil and the error is returned in + * errorPtr (when provided). + * + * @note In DEBUG builds, the parsed message is checked to be sure all required + * fields were provided, and the parse will fail if some are missing. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param data The data to parse. + * @param errorPtr An optional error pointer to fill in with a failure reason if + * the data can not be parsed. + * + * @return An initialized instance of the generated class. + **/ +- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr; + +/** + * Initializes an instance by parsing the data. This method should be sent to + * the generated message class that the data should be interpreted as. If + * there is an error the method returns nil and the error is returned in + * errorPtr (when provided). + * + * @note In DEBUG builds, the parsed message is checked to be sure all required + * fields were provided, and the parse will fail if some are missing. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param data The data to parse. + * @param extensionRegistry The extension registry to use to look up extensions. + * @param errorPtr An optional error pointer to fill in with a failure + * reason if the data can not be parsed. + * + * @return An initialized instance of the generated class. + **/ +- (nullable instancetype)initWithData:(NSData *)data + extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr; + +/** + * Initializes an instance by parsing the data from the given input stream. This + * method should be sent to the generated message class that the data should + * be interpreted as. If there is an error the method returns nil and the error + * is returned in errorPtr (when provided). + * + * @note Unlike the parseFrom... methods, this never checks to see if all of + * the required fields are set. So this method can be used to reload + * messages that may not be complete. + * + * @note The errors returned are likely coming from the domain and codes listed + * at the top of this file and GPBCodedInputStream.h. + * + * @param input The stream to read data from. + * @param extensionRegistry The extension registry to use to look up extensions. + * @param errorPtr An optional error pointer to fill in with a failure + * reason if the data can not be parsed. + * + * @return An initialized instance of the generated class. + **/ +- (nullable instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (nullable GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr; + +/** + * Parses the given data as this message's class, and merges those values into + * this message. + * + * @param data The binary representation of the message to merge. + * @param extensionRegistry The extension registry to use to look up extensions. + * + * @exception GPBCodedInputStreamException Exception thrown when parsing was + * unsuccessful. + **/ +- (void)mergeFromData:(NSData *)data + extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; + +/** + * Merges the fields from another message (of the same type) into this + * message. + * + * @param other Message to merge into this message. + **/ +- (void)mergeFrom:(GPBMessage *)other; + +/** + * Writes out the message to the given coded output stream. + * + * @param output The coded output stream into which to write the message. + * + * @note This can raise the GPBCodedOutputStreamException_* exceptions. + * + **/ +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output; + +/** + * Writes out the message to the given output stream. + * + * @param output The output stream into which to write the message. + * + * @note This can raise the GPBCodedOutputStreamException_* exceptions. + **/ +- (void)writeToOutputStream:(NSOutputStream *)output; + +/** + * Writes out a varint for the message size followed by the the message to + * the given output stream. + * + * @param output The coded output stream into which to write the message. + * + * @note This can raise the GPBCodedOutputStreamException_* exceptions. + **/ +- (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output; + +/** + * Writes out a varint for the message size followed by the the message to + * the given output stream. + * + * @param output The output stream into which to write the message. + * + * @note This can raise the GPBCodedOutputStreamException_* exceptions. + **/ +- (void)writeDelimitedToOutputStream:(NSOutputStream *)output; + +/** + * Serializes the message to an NSData. + * + * If there is an error while generating the data, nil is returned. + * + * @note This value is not cached, so if you are using it repeatedly, cache + * it yourself. + * + * @note In DEBUG ONLY, the message is also checked for all required field, + * if one is missing, nil will be returned. + * + * @return The binary representation of the message. + **/ +- (nullable NSData *)data; + +/** + * Serializes a varint with the message size followed by the message data, + * returning that as an NSData. + * + * @note This value is not cached, so if you are using it repeatedly, it is + * recommended to keep a local copy. + * + * @return The binary representation of the size along with the message. + **/ +- (NSData *)delimitedData; + +/** + * Calculates the size of the object if it were serialized. + * + * This is not a cached value. If you are following a pattern like this: + * + * ``` + * size_t size = [aMsg serializedSize]; + * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)]; + * [foo writeSize:size]; + * [foo appendData:[aMsg data]]; + * ``` + * + * you would be better doing: + * + * ``` + * NSData *data = [aMsg data]; + * NSUInteger size = [aMsg length]; + * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)]; + * [foo writeSize:size]; + * [foo appendData:data]; + * ``` + * + * @return The size of the message in it's binary representation. + **/ +- (size_t)serializedSize; + +/** + * @return The descriptor for the message class. + **/ ++ (GPBDescriptor *)descriptor; + +/** + * Return the descriptor for the message. + **/ +- (GPBDescriptor *)descriptor; + +/** + * @return An array with the extension descriptors that are currently set on the + * message. + **/ +- (NSArray *)extensionsCurrentlySet; + +/** + * Checks whether there is an extension set on the message which matches the + * given extension descriptor. + * + * @param extension Extension descriptor to check if it's set on the message. + * + * @return Whether the extension is currently set on the message. + **/ +- (BOOL)hasExtension:(GPBExtensionDescriptor *)extension; + +/* + * Fetches the given extension's value for this message. + * + * Extensions use boxed values (NSNumbers) for PODs and NSMutableArrays for + * repeated fields. If the extension is a Message one will be auto created for + * you and returned similar to fields. + * + * @param extension The extension descriptor of the extension to fetch. + * + * @return The extension matching the given descriptor, or nil if none found. + **/ +- (nullable id)getExtension:(GPBExtensionDescriptor *)extension; + +/** + * Sets the given extension's value for this message. This only applies for + * single field extensions (i.e. - not repeated fields). + * + * Extensions use boxed values (NSNumbers). + * + * @param extension The extension descriptor under which to set the value. + * @param value The value to be set as the extension. + **/ +- (void)setExtension:(GPBExtensionDescriptor *)extension + value:(nullable id)value; + +/** + * Adds the given value to the extension for this message. This only applies + * to repeated field extensions. If the field is a repeated POD type, the value + * should be an NSNumber. + * + * @param extension The extension descriptor under which to add the value. + * @param value The value to be added to the repeated extension. + **/ +- (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value; + +/** + * Replaces the value at the given index with the given value for the extension + * on this message. This only applies to repeated field extensions. If the field + * is a repeated POD type, the value is should be an NSNumber. + * + * @param extension The extension descriptor under which to replace the value. + * @param index The index of the extension to be replaced. + * @param value The value to be replaced in the repeated extension. + **/ +- (void)setExtension:(GPBExtensionDescriptor *)extension + index:(NSUInteger)index + value:(id)value; + +/** + * Clears the given extension for this message. + * + * @param extension The extension descriptor to be cleared from this message. + **/ +- (void)clearExtension:(GPBExtensionDescriptor *)extension; + +/** + * Resets all of the fields of this message to their default values. + **/ +- (void)clear; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBMessage.m b/My Mind/Pods/Protobuf/objectivec/GPBMessage.m new file mode 100644 index 0000000..db5d3b6 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBMessage.m @@ -0,0 +1,3317 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBMessage_PackagePrivate.h" + +#import +#import +#import + +#import "GPBArray_PackagePrivate.h" +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream_PackagePrivate.h" +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBDictionary_PackagePrivate.h" +#import "GPBExtensionInternals.h" +#import "GPBExtensionRegistry.h" +#import "GPBRootObject_PackagePrivate.h" +#import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +NSString *const GPBMessageErrorDomain = + GPBNSStringifySymbol(GPBMessageErrorDomain); + +NSString *const GPBErrorReasonKey = @"Reason"; + +static NSString *const kGPBDataCoderKey = @"GPBData"; + +// +// PLEASE REMEMBER: +// +// This is the base class for *all* messages generated, so any selector defined, +// *public* or *private* could end up colliding with a proto message field. So +// avoid using selectors that could match a property, use C functions to hide +// them, etc. +// + +@interface GPBMessage () { + @package + GPBUnknownFieldSet *unknownFields_; + NSMutableDictionary *extensionMap_; + NSMutableDictionary *autocreatedExtensionMap_; + + // If the object was autocreated, we remember the creator so that if we get + // mutated, we can inform the creator to make our field visible. + GPBMessage *autocreator_; + GPBFieldDescriptor *autocreatorField_; + GPBExtensionDescriptor *autocreatorExtension_; + + // A lock to provide mutual exclusion from internal data that can be modified + // by *read* operations such as getters (autocreation of message fields and + // message extensions, not setting of values). Used to guarantee thread safety + // for concurrent reads on the message. + // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have + // pointed out that they are vulnerable to live locking on iOS in cases of + // priority inversion: + // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/ + // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html + // Use of readOnlySemaphore_ must be prefaced by a call to + // GPBPrepareReadOnlySemaphore to ensure it has been created. This allows + // readOnlySemaphore_ to be only created when actually needed. + _Atomic(dispatch_semaphore_t) readOnlySemaphore_; +} +@end + +static id CreateArrayForField(GPBFieldDescriptor *field, + GPBMessage *autocreator) + __attribute__((ns_returns_retained)); +static id GetOrCreateArrayIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax); +static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); +static id CreateMapForField(GPBFieldDescriptor *field, + GPBMessage *autocreator) + __attribute__((ns_returns_retained)); +static id GetOrCreateMapIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax); +static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); +static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, + NSZone *zone) + __attribute__((ns_returns_retained)); + +#ifdef DEBUG +static NSError *MessageError(NSInteger code, NSDictionary *userInfo) { + return [NSError errorWithDomain:GPBMessageErrorDomain + code:code + userInfo:userInfo]; +} +#endif + +static NSError *ErrorFromException(NSException *exception) { + NSError *error = nil; + + if ([exception.name isEqual:GPBCodedInputStreamException]) { + NSDictionary *exceptionInfo = exception.userInfo; + error = exceptionInfo[GPBCodedInputStreamUnderlyingErrorKey]; + } + + if (!error) { + NSString *reason = exception.reason; + NSDictionary *userInfo = nil; + if ([reason length]) { + userInfo = @{ GPBErrorReasonKey : reason }; + } + + error = [NSError errorWithDomain:GPBMessageErrorDomain + code:GPBMessageErrorCodeOther + userInfo:userInfo]; + } + return error; +} + +static void CheckExtension(GPBMessage *self, + GPBExtensionDescriptor *extension) { + if (![self isKindOfClass:extension.containingMessageClass]) { + [NSException + raise:NSInvalidArgumentException + format:@"Extension %@ used on wrong class (%@ instead of %@)", + extension.singletonName, + [self class], extension.containingMessageClass]; + } +} + +static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, + NSZone *zone) { + if (extensionMap.count == 0) { + return nil; + } + NSMutableDictionary *result = [[NSMutableDictionary allocWithZone:zone] + initWithCapacity:extensionMap.count]; + + for (GPBExtensionDescriptor *extension in extensionMap) { + id value = [extensionMap objectForKey:extension]; + BOOL isMessageExtension = GPBExtensionIsMessage(extension); + + if (extension.repeated) { + if (isMessageExtension) { + NSMutableArray *list = + [[NSMutableArray alloc] initWithCapacity:[value count]]; + for (GPBMessage *listValue in value) { + GPBMessage *copiedValue = [listValue copyWithZone:zone]; + [list addObject:copiedValue]; + [copiedValue release]; + } + [result setObject:list forKey:extension]; + [list release]; + } else { + NSMutableArray *copiedValue = [value mutableCopyWithZone:zone]; + [result setObject:copiedValue forKey:extension]; + [copiedValue release]; + } + } else { + if (isMessageExtension) { + GPBMessage *copiedValue = [value copyWithZone:zone]; + [result setObject:copiedValue forKey:extension]; + [copiedValue release]; + } else { + [result setObject:value forKey:extension]; + } + } + } + + return result; +} + +static id CreateArrayForField(GPBFieldDescriptor *field, + GPBMessage *autocreator) { + id result; + GPBDataType fieldDataType = GPBGetFieldDataType(field); + switch (fieldDataType) { + case GPBDataTypeBool: + result = [[GPBBoolArray alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBUInt32Array alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBInt32Array alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBUInt64Array alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBInt64Array alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBFloatArray alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBDoubleArray alloc] init]; + break; + + case GPBDataTypeEnum: + result = [[GPBEnumArray alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + + case GPBDataTypeBytes: + case GPBDataTypeGroup: + case GPBDataTypeMessage: + case GPBDataTypeString: + if (autocreator) { + result = [[GPBAutocreatedArray alloc] init]; + } else { + result = [[NSMutableArray alloc] init]; + } + break; + } + + if (autocreator) { + if (GPBDataTypeIsObject(fieldDataType)) { + GPBAutocreatedArray *autoArray = result; + autoArray->_autocreator = autocreator; + } else { + GPBInt32Array *gpbArray = result; + gpbArray->_autocreator = autocreator; + } + } + + return result; +} + +static id CreateMapForField(GPBFieldDescriptor *field, + GPBMessage *autocreator) { + id result; + GPBDataType keyDataType = field.mapKeyDataType; + GPBDataType valueDataType = GPBGetFieldDataType(field); + switch (keyDataType) { + case GPBDataTypeBool: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBBoolBoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBBoolUInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBBoolInt32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBBoolUInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBBoolInt64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBBoolFloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBBoolDoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBBoolEnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + result = [[GPBBoolObjectDictionary alloc] init]; + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBUInt32BoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBUInt32UInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBUInt32Int32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBUInt32UInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBUInt32Int64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBUInt32FloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBUInt32DoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBUInt32EnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + result = [[GPBUInt32ObjectDictionary alloc] init]; + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBInt32BoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBInt32UInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBInt32Int32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBInt32UInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBInt32Int64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBInt32FloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBInt32DoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBInt32EnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + result = [[GPBInt32ObjectDictionary alloc] init]; + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBUInt64BoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBUInt64UInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBUInt64Int32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBUInt64UInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBUInt64Int64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBUInt64FloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBUInt64DoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBUInt64EnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + result = [[GPBUInt64ObjectDictionary alloc] init]; + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBInt64BoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBInt64UInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBInt64Int32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBInt64UInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBInt64Int64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBInt64FloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBInt64DoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBInt64EnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + result = [[GPBInt64ObjectDictionary alloc] init]; + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + case GPBDataTypeString: + switch (valueDataType) { + case GPBDataTypeBool: + result = [[GPBStringBoolDictionary alloc] init]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + result = [[GPBStringUInt32Dictionary alloc] init]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + result = [[GPBStringInt32Dictionary alloc] init]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + result = [[GPBStringUInt64Dictionary alloc] init]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + result = [[GPBStringInt64Dictionary alloc] init]; + break; + case GPBDataTypeFloat: + result = [[GPBStringFloatDictionary alloc] init]; + break; + case GPBDataTypeDouble: + result = [[GPBStringDoubleDictionary alloc] init]; + break; + case GPBDataTypeEnum: + result = [[GPBStringEnumDictionary alloc] + initWithValidationFunction:field.enumDescriptor.enumVerifier]; + break; + case GPBDataTypeBytes: + case GPBDataTypeMessage: + case GPBDataTypeString: + if (autocreator) { + result = [[GPBAutocreatedDictionary alloc] init]; + } else { + result = [[NSMutableDictionary alloc] init]; + } + break; + case GPBDataTypeGroup: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + break; + + case GPBDataTypeFloat: + case GPBDataTypeDouble: + case GPBDataTypeEnum: + case GPBDataTypeBytes: + case GPBDataTypeGroup: + case GPBDataTypeMessage: + NSCAssert(NO, @"shouldn't happen"); + return nil; + } + + if (autocreator) { + if ((keyDataType == GPBDataTypeString) && + GPBDataTypeIsObject(valueDataType)) { + GPBAutocreatedDictionary *autoDict = result; + autoDict->_autocreator = autocreator; + } else { + GPBInt32Int32Dictionary *gpbDict = result; + gpbDict->_autocreator = autocreator; + } + } + + return result; +} + +#if !defined(__clang_analyzer__) +// These functions are blocked from the analyzer because the analyzer sees the +// GPBSetRetainedObjectIvarWithFieldInternal() call as consuming the array/map, +// so use of the array/map after the call returns is flagged as a use after +// free. +// But GPBSetRetainedObjectIvarWithFieldInternal() is "consuming" the retain +// count be holding onto the object (it is transfering it), the object is +// still valid after returning from the call. The other way to avoid this +// would be to add a -retain/-autorelease, but that would force every +// repeated/map field parsed into the autorelease pool which is both a memory +// and performance hit. + +static id GetOrCreateArrayIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax) { + id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!array) { + // No lock needed, this is called from places expecting to mutate + // so no threading protection is needed. + array = CreateArrayForField(field, nil); + GPBSetRetainedObjectIvarWithFieldInternal(self, field, array, syntax); + } + return array; +} + +// This is like GPBGetObjectIvarWithField(), but for arrays, it should +// only be used to wire the method into the class. +static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { + id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!array) { + // Check again after getting the lock. + GPBPrepareReadOnlySemaphore(self); + dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); + array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!array) { + array = CreateArrayForField(field, self); + GPBSetAutocreatedRetainedObjectIvarWithField(self, field, array); + } + dispatch_semaphore_signal(self->readOnlySemaphore_); + } + return array; +} + +static id GetOrCreateMapIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax) { + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!dict) { + // No lock needed, this is called from places expecting to mutate + // so no threading protection is needed. + dict = CreateMapForField(field, nil); + GPBSetRetainedObjectIvarWithFieldInternal(self, field, dict, syntax); + } + return dict; +} + +// This is like GPBGetObjectIvarWithField(), but for maps, it should +// only be used to wire the method into the class. +static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!dict) { + // Check again after getting the lock. + GPBPrepareReadOnlySemaphore(self); + dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); + dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!dict) { + dict = CreateMapForField(field, self); + GPBSetAutocreatedRetainedObjectIvarWithField(self, field, dict); + } + dispatch_semaphore_signal(self->readOnlySemaphore_); + } + return dict; +} + +#endif // !defined(__clang_analyzer__) + +GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, + GPBMessage *autocreator, + GPBFieldDescriptor *field) { + GPBMessage *message = [[msgClass alloc] init]; + message->autocreator_ = autocreator; + message->autocreatorField_ = [field retain]; + return message; +} + +static GPBMessage *CreateMessageWithAutocreatorForExtension( + Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension) + __attribute__((ns_returns_retained)); + +static GPBMessage *CreateMessageWithAutocreatorForExtension( + Class msgClass, GPBMessage *autocreator, + GPBExtensionDescriptor *extension) { + GPBMessage *message = [[msgClass alloc] init]; + message->autocreator_ = autocreator; + message->autocreatorExtension_ = [extension retain]; + return message; +} + +BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent) { + return (message->autocreator_ == parent); +} + +void GPBBecomeVisibleToAutocreator(GPBMessage *self) { + // Message objects that are implicitly created by accessing a message field + // are initially not visible via the hasX selector. This method makes them + // visible. + if (self->autocreator_) { + // This will recursively make all parent messages visible until it reaches a + // super-creator that's visible. + if (self->autocreatorField_) { + GPBFileSyntax syntax = [self->autocreator_ descriptor].file.syntax; + GPBSetObjectIvarWithFieldInternal(self->autocreator_, + self->autocreatorField_, self, syntax); + } else { + [self->autocreator_ setExtension:self->autocreatorExtension_ value:self]; + } + } +} + +void GPBAutocreatedArrayModified(GPBMessage *self, id array) { + // When one of our autocreated arrays adds elements, make it visible. + GPBDescriptor *descriptor = [[self class] descriptor]; + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (field.fieldType == GPBFieldTypeRepeated) { + id curArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (curArray == array) { + if (GPBFieldDataTypeIsObject(field)) { + GPBAutocreatedArray *autoArray = array; + autoArray->_autocreator = nil; + } else { + GPBInt32Array *gpbArray = array; + gpbArray->_autocreator = nil; + } + GPBBecomeVisibleToAutocreator(self); + return; + } + } + } + NSCAssert(NO, @"Unknown autocreated %@ for %@.", [array class], self); +} + +void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) { + // When one of our autocreated dicts adds elements, make it visible. + GPBDescriptor *descriptor = [[self class] descriptor]; + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (field.fieldType == GPBFieldTypeMap) { + id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (curDict == dictionary) { + if ((field.mapKeyDataType == GPBDataTypeString) && + GPBFieldDataTypeIsObject(field)) { + GPBAutocreatedDictionary *autoDict = dictionary; + autoDict->_autocreator = nil; + } else { + GPBInt32Int32Dictionary *gpbDict = dictionary; + gpbDict->_autocreator = nil; + } + GPBBecomeVisibleToAutocreator(self); + return; + } + } + } + NSCAssert(NO, @"Unknown autocreated %@ for %@.", [dictionary class], self); +} + +void GPBClearMessageAutocreator(GPBMessage *self) { + if ((self == nil) || !self->autocreator_) { + return; + } + +#if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS) + // Either the autocreator must have its "has" flag set to YES, or it must be + // NO and not equal to ourselves. + BOOL autocreatorHas = + (self->autocreatorField_ + ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_) + : [self->autocreator_ hasExtension:self->autocreatorExtension_]); + GPBMessage *autocreatorFieldValue = + (self->autocreatorField_ + ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, + self->autocreatorField_) + : [self->autocreator_->autocreatedExtensionMap_ + objectForKey:self->autocreatorExtension_]); + NSCAssert(autocreatorHas || autocreatorFieldValue != self, + @"Cannot clear autocreator because it still refers to self, self: %@.", + self); + +#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) + + self->autocreator_ = nil; + [self->autocreatorField_ release]; + self->autocreatorField_ = nil; + [self->autocreatorExtension_ release]; + self->autocreatorExtension_ = nil; +} + +// Call this before using the readOnlySemaphore_. This ensures it is created only once. +void GPBPrepareReadOnlySemaphore(GPBMessage *self) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + + // Create the semaphore on demand (rather than init) as developers might not cause them + // to be needed, and the heap usage can add up. The atomic swap is used to avoid needing + // another lock around creating it. + if (self->readOnlySemaphore_ == nil) { + dispatch_semaphore_t worker = dispatch_semaphore_create(1); + dispatch_semaphore_t expected = nil; + if (!atomic_compare_exchange_strong(&self->readOnlySemaphore_, &expected, worker)) { + dispatch_release(worker); + } +#if defined(__clang_analyzer__) + // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked + // (doesn't seem to know about atomic_compare_exchange_strong); so just + // for the analyzer, let it think worker is also released in this case. + else { dispatch_release(worker); } +#endif + } + +#pragma clang diagnostic pop +} + +static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { + if (!self->unknownFields_) { + self->unknownFields_ = [[GPBUnknownFieldSet alloc] init]; + GPBBecomeVisibleToAutocreator(self); + } + return self->unknownFields_; +} + +@implementation GPBMessage + ++ (void)initialize { + Class pbMessageClass = [GPBMessage class]; + if ([self class] == pbMessageClass) { + // This is here to start up the "base" class descriptor. + [self descriptor]; + // Message shares extension method resolving with GPBRootObject so insure + // it is started up at the same time. + (void)[GPBRootObject class]; + } else if ([self superclass] == pbMessageClass) { + // This is here to start up all the "message" subclasses. Just needs to be + // done for the messages, not any of the subclasses. + // This must be done in initialize to enforce thread safety of start up of + // the protocol buffer library. + // Note: The generated code for -descriptor calls + // +[GPBDescriptor allocDescriptorForClass:...], passing the GPBRootObject + // subclass for the file. That call chain is what ensures that *Root class + // is started up to support extension resolution off the message class + // (+resolveClassMethod: below) in a thread safe manner. + [self descriptor]; + } +} + ++ (instancetype)allocWithZone:(NSZone *)zone { + // Override alloc to allocate our classes with the additional storage + // required for the instance variables. + GPBDescriptor *descriptor = [self descriptor]; + return NSAllocateObject(self, descriptor->storageSize_, zone); +} + ++ (instancetype)alloc { + return [self allocWithZone:nil]; +} + ++ (GPBDescriptor *)descriptor { + // This is thread safe because it is called from +initialize. + static GPBDescriptor *descriptor = NULL; + static GPBFileDescriptor *fileDescriptor = NULL; + if (!descriptor) { + // Use a dummy file that marks it as proto2 syntax so when used generically + // it supports unknowns/etc. + fileDescriptor = + [[GPBFileDescriptor alloc] initWithPackage:@"internal" + syntax:GPBFileSyntaxProto2]; + + descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class] + rootClass:Nil + file:fileDescriptor + fields:NULL + fieldCount:0 + storageSize:0 + flags:0]; + } + return descriptor; +} + ++ (instancetype)message { + return [[[self alloc] init] autorelease]; +} + +- (instancetype)init { + if ((self = [super init])) { + messageStorage_ = (GPBMessage_StoragePtr)( + ((uint8_t *)self) + class_getInstanceSize([self class])); + } + + return self; +} + +- (instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr { + return [self initWithData:data extensionRegistry:nil error:errorPtr]; +} + +- (instancetype)initWithData:(NSData *)data + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr { + if ((self = [self init])) { + @try { + [self mergeFromData:data extensionRegistry:extensionRegistry]; + if (errorPtr) { + *errorPtr = nil; + } + } + @catch (NSException *exception) { + [self release]; + self = nil; + if (errorPtr) { + *errorPtr = ErrorFromException(exception); + } + } +#ifdef DEBUG + if (self && !self.initialized) { + [self release]; + self = nil; + if (errorPtr) { + *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); + } + } +#endif + } + return self; +} + +- (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr { + if ((self = [self init])) { + @try { + [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; + if (errorPtr) { + *errorPtr = nil; + } + } + @catch (NSException *exception) { + [self release]; + self = nil; + if (errorPtr) { + *errorPtr = ErrorFromException(exception); + } + } +#ifdef DEBUG + if (self && !self.initialized) { + [self release]; + self = nil; + if (errorPtr) { + *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); + } + } +#endif + } + return self; +} + +- (void)dealloc { + [self internalClear:NO]; + NSCAssert(!autocreator_, @"Autocreator was not cleared before dealloc."); + if (readOnlySemaphore_) { + dispatch_release(readOnlySemaphore_); + } + [super dealloc]; +} + +- (void)copyFieldsInto:(GPBMessage *)message + zone:(NSZone *)zone + descriptor:(GPBDescriptor *)descriptor { + // Copy all the storage... + memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_); + + GPBFileSyntax syntax = descriptor.file.syntax; + + // Loop over the fields doing fixup... + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (GPBFieldIsMapOrArray(field)) { + id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (value) { + // We need to copy the array/map, but the catch is for message fields, + // we also need to ensure all the messages as those need copying also. + id newValue; + if (GPBFieldDataTypeIsMessage(field)) { + if (field.fieldType == GPBFieldTypeRepeated) { + NSArray *existingArray = (NSArray *)value; + NSMutableArray *newArray = + [[NSMutableArray alloc] initWithCapacity:existingArray.count]; + newValue = newArray; + for (GPBMessage *msg in existingArray) { + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [newArray addObject:copiedMsg]; + [copiedMsg release]; + } + } else { + if (field.mapKeyDataType == GPBDataTypeString) { + // Map is an NSDictionary. + NSDictionary *existingDict = value; + NSMutableDictionary *newDict = [[NSMutableDictionary alloc] + initWithCapacity:existingDict.count]; + newValue = newDict; + [existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, + GPBMessage *msg, + BOOL *stop) { +#pragma unused(stop) + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [newDict setObject:copiedMsg forKey:key]; + [copiedMsg release]; + }]; + } else { + // Is one of the GPB*ObjectDictionary classes. Type doesn't + // matter, just need one to invoke the selector. + GPBInt32ObjectDictionary *existingDict = value; + newValue = [existingDict deepCopyWithZone:zone]; + } + } + } else { + // Not messages (but is a map/array)... + if (field.fieldType == GPBFieldTypeRepeated) { + if (GPBFieldDataTypeIsObject(field)) { + // NSArray + newValue = [value mutableCopyWithZone:zone]; + } else { + // GPB*Array + newValue = [value copyWithZone:zone]; + } + } else { + if ((field.mapKeyDataType == GPBDataTypeString) && + GPBFieldDataTypeIsObject(field)) { + // NSDictionary + newValue = [value mutableCopyWithZone:zone]; + } else { + // Is one of the GPB*Dictionary classes. Type doesn't matter, + // just need one to invoke the selector. + GPBInt32Int32Dictionary *existingDict = value; + newValue = [existingDict copyWithZone:zone]; + } + } + } + // We retain here because the memcpy picked up the pointer value and + // the next call to SetRetainedObject... will release the current value. + [value retain]; + GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, + syntax); + } + } else if (GPBFieldDataTypeIsMessage(field)) { + // For object types, if we have a value, copy it. If we don't, + // zero it to remove the pointer to something that was autocreated + // (and the ptr just got memcpyed). + if (GPBGetHasIvarField(self, field)) { + GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBMessage *newValue = [value copyWithZone:zone]; + // We retain here because the memcpy picked up the pointer value and + // the next call to SetRetainedObject... will release the current value. + [value retain]; + GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, + syntax); + } else { + uint8_t *storage = (uint8_t *)message->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + *typePtr = NULL; + } + } else if (GPBFieldDataTypeIsObject(field) && + GPBGetHasIvarField(self, field)) { + // A set string/data value (message picked off above), copy it. + id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + id newValue = [value copyWithZone:zone]; + // We retain here because the memcpy picked up the pointer value and + // the next call to SetRetainedObject... will release the current value. + [value retain]; + GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, + syntax); + } else { + // memcpy took care of the rest of the primitive fields if they were set. + } + } // for (field in descriptor->fields_) +} + +- (id)copyWithZone:(NSZone *)zone { + GPBDescriptor *descriptor = [self descriptor]; + GPBMessage *result = [[descriptor.messageClass allocWithZone:zone] init]; + + [self copyFieldsInto:result zone:zone descriptor:descriptor]; + // Make immutable copies of the extra bits. + result->unknownFields_ = [unknownFields_ copyWithZone:zone]; + result->extensionMap_ = CloneExtensionMap(extensionMap_, zone); + return result; +} + +- (void)clear { + [self internalClear:YES]; +} + +- (void)internalClear:(BOOL)zeroStorage { + GPBDescriptor *descriptor = [self descriptor]; + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (GPBFieldIsMapOrArray(field)) { + id arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (arrayOrMap) { + if (field.fieldType == GPBFieldTypeRepeated) { + if (GPBFieldDataTypeIsObject(field)) { + if ([arrayOrMap isKindOfClass:[GPBAutocreatedArray class]]) { + GPBAutocreatedArray *autoArray = arrayOrMap; + if (autoArray->_autocreator == self) { + autoArray->_autocreator = nil; + } + } + } else { + // Type doesn't matter, it is a GPB*Array. + GPBInt32Array *gpbArray = arrayOrMap; + if (gpbArray->_autocreator == self) { + gpbArray->_autocreator = nil; + } + } + } else { + if ((field.mapKeyDataType == GPBDataTypeString) && + GPBFieldDataTypeIsObject(field)) { + if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) { + GPBAutocreatedDictionary *autoDict = arrayOrMap; + if (autoDict->_autocreator == self) { + autoDict->_autocreator = nil; + } + } + } else { + // Type doesn't matter, it is a GPB*Dictionary. + GPBInt32Int32Dictionary *gpbDict = arrayOrMap; + if (gpbDict->_autocreator == self) { + gpbDict->_autocreator = nil; + } + } + } + [arrayOrMap release]; + } + } else if (GPBFieldDataTypeIsMessage(field)) { + GPBClearAutocreatedMessageIvarWithField(self, field); + GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [value release]; + } else if (GPBFieldDataTypeIsObject(field) && + GPBGetHasIvarField(self, field)) { + id value = GPBGetObjectIvarWithField(self, field); + [value release]; + } + } + + // GPBClearMessageAutocreator() expects that its caller has already been + // removed from autocreatedExtensionMap_ so we set to nil first. + NSArray *autocreatedValues = [autocreatedExtensionMap_ allValues]; + [autocreatedExtensionMap_ release]; + autocreatedExtensionMap_ = nil; + + // Since we're clearing all of our extensions, make sure that we clear the + // autocreator on any that we've created so they no longer refer to us. + for (GPBMessage *value in autocreatedValues) { + NSCAssert(GPBWasMessageAutocreatedBy(value, self), + @"Autocreated extension does not refer back to self."); + GPBClearMessageAutocreator(value); + } + + [extensionMap_ release]; + extensionMap_ = nil; + [unknownFields_ release]; + unknownFields_ = nil; + + // Note that clearing does not affect autocreator_. If we are being cleared + // because of a dealloc, then autocreator_ should be nil anyway. If we are + // being cleared because someone explicitly clears us, we don't want to + // sever our relationship with our autocreator. + + if (zeroStorage) { + memset(messageStorage_, 0, descriptor->storageSize_); + } +} + +- (BOOL)isInitialized { + GPBDescriptor *descriptor = [self descriptor]; + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (field.isRequired) { + if (!GPBGetHasIvarField(self, field)) { + return NO; + } + } + if (GPBFieldDataTypeIsMessage(field)) { + GPBFieldType fieldType = field.fieldType; + if (fieldType == GPBFieldTypeSingle) { + if (field.isRequired) { + GPBMessage *message = GPBGetMessageMessageField(self, field); + if (!message.initialized) { + return NO; + } + } else { + NSAssert(field.isOptional, + @"%@: Single message field %@ not required or optional?", + [self class], field.name); + if (GPBGetHasIvarField(self, field)) { + GPBMessage *message = GPBGetMessageMessageField(self, field); + if (!message.initialized) { + return NO; + } + } + } + } else if (fieldType == GPBFieldTypeRepeated) { + NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + for (GPBMessage *message in array) { + if (!message.initialized) { + return NO; + } + } + } else { // fieldType == GPBFieldTypeMap + if (field.mapKeyDataType == GPBDataTypeString) { + NSDictionary *map = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) { + return NO; + } + } else { + // Real type is GPB*ObjectDictionary, exact type doesn't matter. + GPBInt32ObjectDictionary *map = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (map && ![map isInitialized]) { + return NO; + } + } + } + } + } + + __block BOOL result = YES; + [extensionMap_ + enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, + id obj, + BOOL *stop) { + if (GPBExtensionIsMessage(extension)) { + if (extension.isRepeated) { + for (GPBMessage *msg in obj) { + if (!msg.initialized) { + result = NO; + *stop = YES; + break; + } + } + } else { + GPBMessage *asMsg = obj; + if (!asMsg.initialized) { + result = NO; + *stop = YES; + } + } + } + }]; + return result; +} + +- (GPBDescriptor *)descriptor { + return [[self class] descriptor]; +} + +- (NSData *)data { +#ifdef DEBUG + if (!self.initialized) { + return nil; + } +#endif + NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]]; + GPBCodedOutputStream *stream = + [[GPBCodedOutputStream alloc] initWithData:data]; + @try { + [self writeToCodedOutputStream:stream]; + } + @catch (NSException *exception) { + // This really shouldn't happen. The only way writeToCodedOutputStream: + // could throw is if something in the library has a bug and the + // serializedSize was wrong. +#ifdef DEBUG + NSLog(@"%@: Internal exception while building message data: %@", + [self class], exception); +#endif + data = nil; + } + [stream release]; + return data; +} + +- (NSData *)delimitedData { + size_t serializedSize = [self serializedSize]; + size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize); + NSMutableData *data = + [NSMutableData dataWithLength:(serializedSize + varintSize)]; + GPBCodedOutputStream *stream = + [[GPBCodedOutputStream alloc] initWithData:data]; + @try { + [self writeDelimitedToCodedOutputStream:stream]; + } + @catch (NSException *exception) { + // This really shouldn't happen. The only way writeToCodedOutputStream: + // could throw is if something in the library has a bug and the + // serializedSize was wrong. +#ifdef DEBUG + NSLog(@"%@: Internal exception while building message delimitedData: %@", + [self class], exception); +#endif + // If it happens, truncate. + data.length = 0; + } + [stream release]; + return data; +} + +- (void)writeToOutputStream:(NSOutputStream *)output { + GPBCodedOutputStream *stream = + [[GPBCodedOutputStream alloc] initWithOutputStream:output]; + [self writeToCodedOutputStream:stream]; + [stream release]; +} + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output { + GPBDescriptor *descriptor = [self descriptor]; + NSArray *fieldsArray = descriptor->fields_; + NSUInteger fieldCount = fieldsArray.count; + const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; + NSUInteger extensionRangesCount = descriptor.extensionRangesCount; + for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { + if (i == fieldCount) { + [self writeExtensionsToCodedOutputStream:output + range:extensionRanges[j++]]; + } else if (j == extensionRangesCount || + GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { + [self writeField:fieldsArray[i++] toCodedOutputStream:output]; + } else { + [self writeExtensionsToCodedOutputStream:output + range:extensionRanges[j++]]; + } + } + if (descriptor.isWireFormat) { + [unknownFields_ writeAsMessageSetTo:output]; + } else { + [unknownFields_ writeToCodedOutputStream:output]; + } +} + +- (void)writeDelimitedToOutputStream:(NSOutputStream *)output { + GPBCodedOutputStream *codedOutput = + [[GPBCodedOutputStream alloc] initWithOutputStream:output]; + [self writeDelimitedToCodedOutputStream:codedOutput]; + [codedOutput release]; +} + +- (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output { + [output writeRawVarintSizeTAs32:[self serializedSize]]; + [self writeToCodedOutputStream:output]; +} + +- (void)writeField:(GPBFieldDescriptor *)field + toCodedOutputStream:(GPBCodedOutputStream *)output { + GPBFieldType fieldType = field.fieldType; + if (fieldType == GPBFieldTypeSingle) { + BOOL has = GPBGetHasIvarField(self, field); + if (!has) { + return; + } + } + uint32_t fieldNumber = GPBFieldNumber(field); + +//%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE) +//%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE) +//%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE) +//% case GPBDataType##TYPE: +//% if (fieldType == GPBFieldTypeRepeated) { +//% uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; +//% GPB##ARRAY_TYPE##Array *array = +//% GPBGetObjectIvarWithFieldNoAutocreate(self, field); +//% [output write##TYPE##Array:fieldNumber values:array tag:tag]; +//% } else if (fieldType == GPBFieldTypeSingle) { +//% [output write##TYPE:fieldNumber +//% TYPE$S value:GPBGetMessage##REAL_TYPE##Field(self, field)]; +//% } else { // fieldType == GPBFieldTypeMap +//% // Exact type here doesn't matter. +//% GPBInt32##ARRAY_TYPE##Dictionary *dict = +//% GPBGetObjectIvarWithFieldNoAutocreate(self, field); +//% [dict writeToCodedOutputStream:output asField:field]; +//% } +//% break; +//% +//%PDDM-DEFINE FIELD_CASE2(TYPE) +//% case GPBDataType##TYPE: +//% if (fieldType == GPBFieldTypeRepeated) { +//% NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); +//% [output write##TYPE##Array:fieldNumber values:array]; +//% } else if (fieldType == GPBFieldTypeSingle) { +//% // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check +//% // again. +//% [output write##TYPE:fieldNumber +//% TYPE$S value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; +//% } else { // fieldType == GPBFieldTypeMap +//% // Exact type here doesn't matter. +//% id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); +//% GPBDataType mapKeyDataType = field.mapKeyDataType; +//% if (mapKeyDataType == GPBDataTypeString) { +//% GPBDictionaryWriteToStreamInternalHelper(output, dict, field); +//% } else { +//% [dict writeToCodedOutputStream:output asField:field]; +//% } +//% } +//% break; +//% + + switch (GPBGetFieldDataType(field)) { + +//%PDDM-EXPAND FIELD_CASE(Bool, Bool) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeBool: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBBoolArray *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeBoolArray:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeBool:fieldNumber + value:GPBGetMessageBoolField(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32BoolDictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeFixed32: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBUInt32Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeFixed32Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeFixed32:fieldNumber + value:GPBGetMessageUInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32UInt32Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(SFixed32, Int32) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeSFixed32: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt32Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeSFixed32Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeSFixed32:fieldNumber + value:GPBGetMessageInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int32Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Float, Float) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeFloat: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBFloatArray *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeFloatArray:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeFloat:fieldNumber + value:GPBGetMessageFloatField(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32FloatDictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeFixed64: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBUInt64Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeFixed64Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeFixed64:fieldNumber + value:GPBGetMessageUInt64Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32UInt64Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(SFixed64, Int64) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeSFixed64: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt64Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeSFixed64Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeSFixed64:fieldNumber + value:GPBGetMessageInt64Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int64Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Double, Double) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeDouble: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBDoubleArray *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeDoubleArray:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeDouble:fieldNumber + value:GPBGetMessageDoubleField(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32DoubleDictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Int32, Int32) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeInt32: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt32Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeInt32Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeInt32:fieldNumber + value:GPBGetMessageInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int32Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(Int64, Int64) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeInt64: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt64Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeInt64Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeInt64:fieldNumber + value:GPBGetMessageInt64Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int64Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(SInt32, Int32) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeSInt32: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt32Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeSInt32Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeSInt32:fieldNumber + value:GPBGetMessageInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int32Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(SInt64, Int64) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeSInt64: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBInt64Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeSInt64Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeSInt64:fieldNumber + value:GPBGetMessageInt64Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32Int64Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(UInt32, UInt32) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeUInt32: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBUInt32Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeUInt32Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeUInt32:fieldNumber + value:GPBGetMessageUInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32UInt32Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE(UInt64, UInt64) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeUInt64: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBUInt64Array *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeUInt64Array:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeUInt64:fieldNumber + value:GPBGetMessageUInt64Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32UInt64Dictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeEnum: + if (fieldType == GPBFieldTypeRepeated) { + uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; + GPBEnumArray *array = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeEnumArray:fieldNumber values:array tag:tag]; + } else if (fieldType == GPBFieldTypeSingle) { + [output writeEnum:fieldNumber + value:GPBGetMessageInt32Field(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + GPBInt32EnumDictionary *dict = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [dict writeToCodedOutputStream:output asField:field]; + } + break; + +//%PDDM-EXPAND FIELD_CASE2(Bytes) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeBytes: + if (fieldType == GPBFieldTypeRepeated) { + NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeBytesArray:fieldNumber values:array]; + } else if (fieldType == GPBFieldTypeSingle) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check + // again. + [output writeBytes:fieldNumber + value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBDataType mapKeyDataType = field.mapKeyDataType; + if (mapKeyDataType == GPBDataTypeString) { + GPBDictionaryWriteToStreamInternalHelper(output, dict, field); + } else { + [dict writeToCodedOutputStream:output asField:field]; + } + } + break; + +//%PDDM-EXPAND FIELD_CASE2(String) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeString: + if (fieldType == GPBFieldTypeRepeated) { + NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeStringArray:fieldNumber values:array]; + } else if (fieldType == GPBFieldTypeSingle) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check + // again. + [output writeString:fieldNumber + value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBDataType mapKeyDataType = field.mapKeyDataType; + if (mapKeyDataType == GPBDataTypeString) { + GPBDictionaryWriteToStreamInternalHelper(output, dict, field); + } else { + [dict writeToCodedOutputStream:output asField:field]; + } + } + break; + +//%PDDM-EXPAND FIELD_CASE2(Message) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeMessage: + if (fieldType == GPBFieldTypeRepeated) { + NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeMessageArray:fieldNumber values:array]; + } else if (fieldType == GPBFieldTypeSingle) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check + // again. + [output writeMessage:fieldNumber + value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBDataType mapKeyDataType = field.mapKeyDataType; + if (mapKeyDataType == GPBDataTypeString) { + GPBDictionaryWriteToStreamInternalHelper(output, dict, field); + } else { + [dict writeToCodedOutputStream:output asField:field]; + } + } + break; + +//%PDDM-EXPAND FIELD_CASE2(Group) +// This block of code is generated, do not edit it directly. + + case GPBDataTypeGroup: + if (fieldType == GPBFieldTypeRepeated) { + NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [output writeGroupArray:fieldNumber values:array]; + } else if (fieldType == GPBFieldTypeSingle) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check + // again. + [output writeGroup:fieldNumber + value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; + } else { // fieldType == GPBFieldTypeMap + // Exact type here doesn't matter. + id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBDataType mapKeyDataType = field.mapKeyDataType; + if (mapKeyDataType == GPBDataTypeString) { + GPBDictionaryWriteToStreamInternalHelper(output, dict, field); + } else { + [dict writeToCodedOutputStream:output asField:field]; + } + } + break; + +//%PDDM-EXPAND-END (18 expansions) + } +} + +#pragma mark - Extensions + +- (id)getExtension:(GPBExtensionDescriptor *)extension { + CheckExtension(self, extension); + id value = [extensionMap_ objectForKey:extension]; + if (value != nil) { + return value; + } + + // No default for repeated. + if (extension.isRepeated) { + return nil; + } + // Non messages get their default. + if (!GPBExtensionIsMessage(extension)) { + return extension.defaultValue; + } + + // Check for an autocreated value. + GPBPrepareReadOnlySemaphore(self); + dispatch_semaphore_wait(readOnlySemaphore_, DISPATCH_TIME_FOREVER); + value = [autocreatedExtensionMap_ objectForKey:extension]; + if (!value) { + // Auto create the message extensions to match normal fields. + value = CreateMessageWithAutocreatorForExtension(extension.msgClass, self, + extension); + + if (autocreatedExtensionMap_ == nil) { + autocreatedExtensionMap_ = [[NSMutableDictionary alloc] init]; + } + + // We can't simply call setExtension here because that would clear the new + // value's autocreator. + [autocreatedExtensionMap_ setObject:value forKey:extension]; + [value release]; + } + + dispatch_semaphore_signal(readOnlySemaphore_); + return value; +} + +- (id)getExistingExtension:(GPBExtensionDescriptor *)extension { + // This is an internal method so we don't need to call CheckExtension(). + return [extensionMap_ objectForKey:extension]; +} + +- (BOOL)hasExtension:(GPBExtensionDescriptor *)extension { +#if defined(DEBUG) && DEBUG + CheckExtension(self, extension); +#endif // DEBUG + return nil != [extensionMap_ objectForKey:extension]; +} + +- (NSArray *)extensionsCurrentlySet { + return [extensionMap_ allKeys]; +} + +- (void)writeExtensionsToCodedOutputStream:(GPBCodedOutputStream *)output + range:(GPBExtensionRange)range { + NSArray *sortedExtensions = [[extensionMap_ allKeys] + sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; + uint32_t start = range.start; + uint32_t end = range.end; + for (GPBExtensionDescriptor *extension in sortedExtensions) { + uint32_t fieldNumber = extension.fieldNumber; + if (fieldNumber >= start && fieldNumber < end) { + id value = [extensionMap_ objectForKey:extension]; + GPBWriteExtensionValueToOutputStream(extension, value, output); + } + } +} + +- (void)setExtension:(GPBExtensionDescriptor *)extension value:(id)value { + if (!value) { + [self clearExtension:extension]; + return; + } + + CheckExtension(self, extension); + + if (extension.repeated) { + [NSException raise:NSInvalidArgumentException + format:@"Must call addExtension() for repeated types."]; + } + + if (extensionMap_ == nil) { + extensionMap_ = [[NSMutableDictionary alloc] init]; + } + + // This pointless cast is for CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION. + // Without it, the compiler complains we're passing an id nullable when + // setObject:forKey: requires a id nonnull for the value. The check for + // !value at the start of the method ensures it isn't nil, but the check + // isn't smart enough to realize that. + [extensionMap_ setObject:(id)value forKey:extension]; + + GPBExtensionDescriptor *descriptor = extension; + + if (GPBExtensionIsMessage(descriptor) && !descriptor.isRepeated) { + GPBMessage *autocreatedValue = + [[autocreatedExtensionMap_ objectForKey:extension] retain]; + // Must remove from the map before calling GPBClearMessageAutocreator() so + // that GPBClearMessageAutocreator() knows its safe to clear. + [autocreatedExtensionMap_ removeObjectForKey:extension]; + GPBClearMessageAutocreator(autocreatedValue); + [autocreatedValue release]; + } + + GPBBecomeVisibleToAutocreator(self); +} + +- (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value { + CheckExtension(self, extension); + + if (!extension.repeated) { + [NSException raise:NSInvalidArgumentException + format:@"Must call setExtension() for singular types."]; + } + + if (extensionMap_ == nil) { + extensionMap_ = [[NSMutableDictionary alloc] init]; + } + NSMutableArray *list = [extensionMap_ objectForKey:extension]; + if (list == nil) { + list = [NSMutableArray array]; + [extensionMap_ setObject:list forKey:extension]; + } + + [list addObject:value]; + GPBBecomeVisibleToAutocreator(self); +} + +- (void)setExtension:(GPBExtensionDescriptor *)extension + index:(NSUInteger)idx + value:(id)value { + CheckExtension(self, extension); + + if (!extension.repeated) { + [NSException raise:NSInvalidArgumentException + format:@"Must call setExtension() for singular types."]; + } + + if (extensionMap_ == nil) { + extensionMap_ = [[NSMutableDictionary alloc] init]; + } + + NSMutableArray *list = [extensionMap_ objectForKey:extension]; + + [list replaceObjectAtIndex:idx withObject:value]; + GPBBecomeVisibleToAutocreator(self); +} + +- (void)clearExtension:(GPBExtensionDescriptor *)extension { + CheckExtension(self, extension); + + // Only become visible if there was actually a value to clear. + if ([extensionMap_ objectForKey:extension]) { + [extensionMap_ removeObjectForKey:extension]; + GPBBecomeVisibleToAutocreator(self); + } +} + +#pragma mark - mergeFrom + +- (void)mergeFromData:(NSData *)data + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; + [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; + [input checkLastTagWas:0]; + [input release]; +} + +#pragma mark - mergeDelimitedFrom + +- (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + GPBCodedInputStreamState *state = &input->state_; + if (GPBCodedInputStreamIsAtEnd(state)) { + return; + } + NSData *data = GPBCodedInputStreamReadRetainedBytesNoCopy(state); + if (data == nil) { + return; + } + [self mergeFromData:data extensionRegistry:extensionRegistry]; + [data release]; +} + +#pragma mark - Parse From Data Support + ++ (instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr { + return [self parseFromData:data extensionRegistry:nil error:errorPtr]; +} + ++ (instancetype)parseFromData:(NSData *)data + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr { + return [[[self alloc] initWithData:data + extensionRegistry:extensionRegistry + error:errorPtr] autorelease]; +} + ++ (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr { + return + [[[self alloc] initWithCodedInputStream:input + extensionRegistry:extensionRegistry + error:errorPtr] autorelease]; +} + +#pragma mark - Parse Delimited From Data Support + ++ (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (GPBExtensionRegistry *)extensionRegistry + error:(NSError **)errorPtr { + GPBMessage *message = [[[self alloc] init] autorelease]; + @try { + [message mergeDelimitedFromCodedInputStream:input + extensionRegistry:extensionRegistry]; + if (errorPtr) { + *errorPtr = nil; + } + } + @catch (NSException *exception) { + message = nil; + if (errorPtr) { + *errorPtr = ErrorFromException(exception); + } + } +#ifdef DEBUG + if (message && !message.initialized) { + message = nil; + if (errorPtr) { + *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); + } + } +#endif + return message; +} + +#pragma mark - Unknown Field Support + +- (GPBUnknownFieldSet *)unknownFields { + return unknownFields_; +} + +- (void)setUnknownFields:(GPBUnknownFieldSet *)unknownFields { + if (unknownFields != unknownFields_) { + [unknownFields_ release]; + unknownFields_ = [unknownFields copy]; + GPBBecomeVisibleToAutocreator(self); + } +} + +- (void)parseMessageSet:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + uint32_t typeId = 0; + NSData *rawBytes = nil; + GPBExtensionDescriptor *extension = nil; + GPBCodedInputStreamState *state = &input->state_; + while (true) { + uint32_t tag = GPBCodedInputStreamReadTag(state); + if (tag == 0) { + break; + } + + if (tag == GPBWireFormatMessageSetTypeIdTag) { + typeId = GPBCodedInputStreamReadUInt32(state); + if (typeId != 0) { + extension = [extensionRegistry extensionForDescriptor:[self descriptor] + fieldNumber:typeId]; + } + } else if (tag == GPBWireFormatMessageSetMessageTag) { + rawBytes = + [GPBCodedInputStreamReadRetainedBytesNoCopy(state) autorelease]; + } else { + if (![input skipField:tag]) { + break; + } + } + } + + [input checkLastTagWas:GPBWireFormatMessageSetItemEndTag]; + + if (rawBytes != nil && typeId != 0) { + if (extension != nil) { + GPBCodedInputStream *newInput = + [[GPBCodedInputStream alloc] initWithData:rawBytes]; + GPBExtensionMergeFromInputStream(extension, + extension.packable, + newInput, + extensionRegistry, + self); + [newInput release]; + } else { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + // rawBytes was created via a NoCopy, so it can be reusing a + // subrange of another NSData that might go out of scope as things + // unwind, so a copy is needed to ensure what is saved in the + // unknown fields stays valid. + NSData *cloned = [NSData dataWithData:rawBytes]; + [unknownFields mergeMessageSetMessage:typeId data:cloned]; + } + } +} + +- (BOOL)parseUnknownField:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + tag:(uint32_t)tag { + GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag); + int32_t fieldNumber = GPBWireFormatGetTagFieldNumber(tag); + + GPBDescriptor *descriptor = [self descriptor]; + GPBExtensionDescriptor *extension = + [extensionRegistry extensionForDescriptor:descriptor + fieldNumber:fieldNumber]; + if (extension == nil) { + if (descriptor.wireFormat && GPBWireFormatMessageSetItemTag == tag) { + [self parseMessageSet:input extensionRegistry:extensionRegistry]; + return YES; + } + } else { + if (extension.wireType == wireType) { + GPBExtensionMergeFromInputStream(extension, + extension.packable, + input, + extensionRegistry, + self); + return YES; + } + // Primitive, repeated types can be packed on unpacked on the wire, and are + // parsed either way. + if ([extension isRepeated] && + !GPBDataTypeIsObject(extension->description_->dataType) && + (extension.alternateWireType == wireType)) { + GPBExtensionMergeFromInputStream(extension, + !extension.packable, + input, + extensionRegistry, + self); + return YES; + } + } + if ([GPBUnknownFieldSet isFieldTag:tag]) { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + return [unknownFields mergeFieldFrom:tag input:input]; + } else { + return NO; + } +} + +- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + [unknownFields addUnknownMapEntry:fieldNum value:data]; +} + +#pragma mark - MergeFromCodedInputStream Support + +static void MergeSingleFieldFromCodedInputStream( + GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, + GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { + GPBDataType fieldDataType = GPBGetFieldDataType(field); + switch (fieldDataType) { +#define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \ + case GPBDataType##NAME: { \ + TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \ + GPBSet##FUNC_TYPE##IvarWithFieldInternal(self, field, val, syntax); \ + break; \ + } +#define CASE_SINGLE_OBJECT(NAME) \ + case GPBDataType##NAME: { \ + id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \ + GPBSetRetainedObjectIvarWithFieldInternal(self, field, val, syntax); \ + break; \ + } + CASE_SINGLE_POD(Bool, BOOL, Bool) + CASE_SINGLE_POD(Fixed32, uint32_t, UInt32) + CASE_SINGLE_POD(SFixed32, int32_t, Int32) + CASE_SINGLE_POD(Float, float, Float) + CASE_SINGLE_POD(Fixed64, uint64_t, UInt64) + CASE_SINGLE_POD(SFixed64, int64_t, Int64) + CASE_SINGLE_POD(Double, double, Double) + CASE_SINGLE_POD(Int32, int32_t, Int32) + CASE_SINGLE_POD(Int64, int64_t, Int64) + CASE_SINGLE_POD(SInt32, int32_t, Int32) + CASE_SINGLE_POD(SInt64, int64_t, Int64) + CASE_SINGLE_POD(UInt32, uint32_t, UInt32) + CASE_SINGLE_POD(UInt64, uint64_t, UInt64) + CASE_SINGLE_OBJECT(Bytes) + CASE_SINGLE_OBJECT(String) +#undef CASE_SINGLE_POD +#undef CASE_SINGLE_OBJECT + + case GPBDataTypeMessage: { + if (GPBGetHasIvarField(self, field)) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has + // check again. + GPBMessage *message = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [input readMessage:message extensionRegistry:extensionRegistry]; + } else { + GPBMessage *message = [[field.msgClass alloc] init]; + [input readMessage:message extensionRegistry:extensionRegistry]; + GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax); + } + break; + } + + case GPBDataTypeGroup: { + if (GPBGetHasIvarField(self, field)) { + // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has + // check again. + GPBMessage *message = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [input readGroup:GPBFieldNumber(field) + message:message + extensionRegistry:extensionRegistry]; + } else { + GPBMessage *message = [[field.msgClass alloc] init]; + [input readGroup:GPBFieldNumber(field) + message:message + extensionRegistry:extensionRegistry]; + GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax); + } + break; + } + + case GPBDataTypeEnum: { + int32_t val = GPBCodedInputStreamReadEnum(&input->state_); + if (GPBHasPreservingUnknownEnumSemantics(syntax) || + [field isValidEnumValue:val]) { + GPBSetInt32IvarWithFieldInternal(self, field, val, syntax); + } else { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; + } + } + } // switch +} + +static void MergeRepeatedPackedFieldFromCodedInputStream( + GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, + GPBCodedInputStream *input) { + GPBDataType fieldDataType = GPBGetFieldDataType(field); + GPBCodedInputStreamState *state = &input->state_; + id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax); + int32_t length = GPBCodedInputStreamReadInt32(state); + size_t limit = GPBCodedInputStreamPushLimit(state, length); + while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { + switch (fieldDataType) { +#define CASE_REPEATED_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \ + case GPBDataType##NAME: { \ + TYPE val = GPBCodedInputStreamRead##NAME(state); \ + [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \ + break; \ + } + CASE_REPEATED_PACKED_POD(Bool, BOOL, Bool) + CASE_REPEATED_PACKED_POD(Fixed32, uint32_t, UInt32) + CASE_REPEATED_PACKED_POD(SFixed32, int32_t, Int32) + CASE_REPEATED_PACKED_POD(Float, float, Float) + CASE_REPEATED_PACKED_POD(Fixed64, uint64_t, UInt64) + CASE_REPEATED_PACKED_POD(SFixed64, int64_t, Int64) + CASE_REPEATED_PACKED_POD(Double, double, Double) + CASE_REPEATED_PACKED_POD(Int32, int32_t, Int32) + CASE_REPEATED_PACKED_POD(Int64, int64_t, Int64) + CASE_REPEATED_PACKED_POD(SInt32, int32_t, Int32) + CASE_REPEATED_PACKED_POD(SInt64, int64_t, Int64) + CASE_REPEATED_PACKED_POD(UInt32, uint32_t, UInt32) + CASE_REPEATED_PACKED_POD(UInt64, uint64_t, UInt64) +#undef CASE_REPEATED_PACKED_POD + + case GPBDataTypeBytes: + case GPBDataTypeString: + case GPBDataTypeMessage: + case GPBDataTypeGroup: + NSCAssert(NO, @"Non primitive types can't be packed"); + break; + + case GPBDataTypeEnum: { + int32_t val = GPBCodedInputStreamReadEnum(state); + if (GPBHasPreservingUnknownEnumSemantics(syntax) || + [field isValidEnumValue:val]) { + [(GPBEnumArray*)genericArray addRawValue:val]; + } else { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; + } + break; + } + } // switch + } // while(BytesUntilLimit() > 0) + GPBCodedInputStreamPopLimit(state, limit); +} + +static void MergeRepeatedNotPackedFieldFromCodedInputStream( + GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, + GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { + GPBCodedInputStreamState *state = &input->state_; + id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax); + switch (GPBGetFieldDataType(field)) { +#define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \ + case GPBDataType##NAME: { \ + TYPE val = GPBCodedInputStreamRead##NAME(state); \ + [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \ + break; \ + } +#define CASE_REPEATED_NOT_PACKED_OBJECT(NAME) \ + case GPBDataType##NAME: { \ + id val = GPBCodedInputStreamReadRetained##NAME(state); \ + [(NSMutableArray*)genericArray addObject:val]; \ + [val release]; \ + break; \ + } + CASE_REPEATED_NOT_PACKED_POD(Bool, BOOL, Bool) + CASE_REPEATED_NOT_PACKED_POD(Fixed32, uint32_t, UInt32) + CASE_REPEATED_NOT_PACKED_POD(SFixed32, int32_t, Int32) + CASE_REPEATED_NOT_PACKED_POD(Float, float, Float) + CASE_REPEATED_NOT_PACKED_POD(Fixed64, uint64_t, UInt64) + CASE_REPEATED_NOT_PACKED_POD(SFixed64, int64_t, Int64) + CASE_REPEATED_NOT_PACKED_POD(Double, double, Double) + CASE_REPEATED_NOT_PACKED_POD(Int32, int32_t, Int32) + CASE_REPEATED_NOT_PACKED_POD(Int64, int64_t, Int64) + CASE_REPEATED_NOT_PACKED_POD(SInt32, int32_t, Int32) + CASE_REPEATED_NOT_PACKED_POD(SInt64, int64_t, Int64) + CASE_REPEATED_NOT_PACKED_POD(UInt32, uint32_t, UInt32) + CASE_REPEATED_NOT_PACKED_POD(UInt64, uint64_t, UInt64) + CASE_REPEATED_NOT_PACKED_OBJECT(Bytes) + CASE_REPEATED_NOT_PACKED_OBJECT(String) +#undef CASE_REPEATED_NOT_PACKED_POD +#undef CASE_NOT_PACKED_OBJECT + case GPBDataTypeMessage: { + GPBMessage *message = [[field.msgClass alloc] init]; + [input readMessage:message extensionRegistry:extensionRegistry]; + [(NSMutableArray*)genericArray addObject:message]; + [message release]; + break; + } + case GPBDataTypeGroup: { + GPBMessage *message = [[field.msgClass alloc] init]; + [input readGroup:GPBFieldNumber(field) + message:message + extensionRegistry:extensionRegistry]; + [(NSMutableArray*)genericArray addObject:message]; + [message release]; + break; + } + case GPBDataTypeEnum: { + int32_t val = GPBCodedInputStreamReadEnum(state); + if (GPBHasPreservingUnknownEnumSemantics(syntax) || + [field isValidEnumValue:val]) { + [(GPBEnumArray*)genericArray addRawValue:val]; + } else { + GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); + [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; + } + break; + } + } // switch +} + +- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + GPBDescriptor *descriptor = [self descriptor]; + GPBFileSyntax syntax = descriptor.file.syntax; + GPBCodedInputStreamState *state = &input->state_; + uint32_t tag = 0; + NSUInteger startingIndex = 0; + NSArray *fields = descriptor->fields_; + NSUInteger numFields = fields.count; + while (YES) { + BOOL merged = NO; + tag = GPBCodedInputStreamReadTag(state); + if (tag == 0) { + break; // Reached end. + } + for (NSUInteger i = 0; i < numFields; ++i) { + if (startingIndex >= numFields) startingIndex = 0; + GPBFieldDescriptor *fieldDescriptor = fields[startingIndex]; + if (GPBFieldTag(fieldDescriptor) == tag) { + GPBFieldType fieldType = fieldDescriptor.fieldType; + if (fieldType == GPBFieldTypeSingle) { + MergeSingleFieldFromCodedInputStream(self, fieldDescriptor, syntax, + input, extensionRegistry); + // Well formed protos will only have a single field once, advance + // the starting index to the next field. + startingIndex += 1; + } else if (fieldType == GPBFieldTypeRepeated) { + if (fieldDescriptor.isPackable) { + MergeRepeatedPackedFieldFromCodedInputStream( + self, fieldDescriptor, syntax, input); + // Well formed protos will only have a repeated field that is + // packed once, advance the starting index to the next field. + startingIndex += 1; + } else { + MergeRepeatedNotPackedFieldFromCodedInputStream( + self, fieldDescriptor, syntax, input, extensionRegistry); + } + } else { // fieldType == GPBFieldTypeMap + // GPB*Dictionary or NSDictionary, exact type doesn't matter at this + // point. + id map = GetOrCreateMapIvarWithField(self, fieldDescriptor, syntax); + [input readMapEntry:map + extensionRegistry:extensionRegistry + field:fieldDescriptor + parentMessage:self]; + } + merged = YES; + break; + } else { + startingIndex += 1; + } + } // for(i < numFields) + + if (!merged && (tag != 0)) { + // Primitive, repeated types can be packed on unpacked on the wire, and + // are parsed either way. The above loop covered tag in the preferred + // for, so this need to check the alternate form. + for (NSUInteger i = 0; i < numFields; ++i) { + if (startingIndex >= numFields) startingIndex = 0; + GPBFieldDescriptor *fieldDescriptor = fields[startingIndex]; + if ((fieldDescriptor.fieldType == GPBFieldTypeRepeated) && + !GPBFieldDataTypeIsObject(fieldDescriptor) && + (GPBFieldAlternateTag(fieldDescriptor) == tag)) { + BOOL alternateIsPacked = !fieldDescriptor.isPackable; + if (alternateIsPacked) { + MergeRepeatedPackedFieldFromCodedInputStream( + self, fieldDescriptor, syntax, input); + // Well formed protos will only have a repeated field that is + // packed once, advance the starting index to the next field. + startingIndex += 1; + } else { + MergeRepeatedNotPackedFieldFromCodedInputStream( + self, fieldDescriptor, syntax, input, extensionRegistry); + } + merged = YES; + break; + } else { + startingIndex += 1; + } + } + } + + if (!merged) { + if (tag == 0) { + // zero signals EOF / limit reached + return; + } else { + if (![self parseUnknownField:input + extensionRegistry:extensionRegistry + tag:tag]) { + // it's an endgroup tag + return; + } + } + } // if(!merged) + + } // while(YES) +} + +#pragma mark - MergeFrom Support + +- (void)mergeFrom:(GPBMessage *)other { + Class selfClass = [self class]; + Class otherClass = [other class]; + if (!([selfClass isSubclassOfClass:otherClass] || + [otherClass isSubclassOfClass:selfClass])) { + [NSException raise:NSInvalidArgumentException + format:@"Classes must match %@ != %@", selfClass, otherClass]; + } + + // We assume something will be done and become visible. + GPBBecomeVisibleToAutocreator(self); + + GPBDescriptor *descriptor = [[self class] descriptor]; + GPBFileSyntax syntax = descriptor.file.syntax; + + for (GPBFieldDescriptor *field in descriptor->fields_) { + GPBFieldType fieldType = field.fieldType; + if (fieldType == GPBFieldTypeSingle) { + int32_t hasIndex = GPBFieldHasIndex(field); + uint32_t fieldNumber = GPBFieldNumber(field); + if (!GPBGetHasIvar(other, hasIndex, fieldNumber)) { + // Other doesn't have the field set, on to the next. + continue; + } + GPBDataType fieldDataType = GPBGetFieldDataType(field); + switch (fieldDataType) { + case GPBDataTypeBool: + GPBSetBoolIvarWithFieldInternal( + self, field, GPBGetMessageBoolField(other, field), syntax); + break; + case GPBDataTypeSFixed32: + case GPBDataTypeEnum: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + GPBSetInt32IvarWithFieldInternal( + self, field, GPBGetMessageInt32Field(other, field), syntax); + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + GPBSetUInt32IvarWithFieldInternal( + self, field, GPBGetMessageUInt32Field(other, field), syntax); + break; + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + GPBSetInt64IvarWithFieldInternal( + self, field, GPBGetMessageInt64Field(other, field), syntax); + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + GPBSetUInt64IvarWithFieldInternal( + self, field, GPBGetMessageUInt64Field(other, field), syntax); + break; + case GPBDataTypeFloat: + GPBSetFloatIvarWithFieldInternal( + self, field, GPBGetMessageFloatField(other, field), syntax); + break; + case GPBDataTypeDouble: + GPBSetDoubleIvarWithFieldInternal( + self, field, GPBGetMessageDoubleField(other, field), syntax); + break; + case GPBDataTypeBytes: + case GPBDataTypeString: { + id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field); + GPBSetObjectIvarWithFieldInternal(self, field, otherVal, syntax); + break; + } + case GPBDataTypeMessage: + case GPBDataTypeGroup: { + id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field); + if (GPBGetHasIvar(self, hasIndex, fieldNumber)) { + GPBMessage *message = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + [message mergeFrom:otherVal]; + } else { + GPBMessage *message = [otherVal copy]; + GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, + syntax); + } + break; + } + } // switch() + } else if (fieldType == GPBFieldTypeRepeated) { + // In the case of a list, they need to be appended, and there is no + // _hasIvar to worry about setting. + id otherArray = + GPBGetObjectIvarWithFieldNoAutocreate(other, field); + if (otherArray) { + GPBDataType fieldDataType = field->description_->dataType; + if (GPBDataTypeIsObject(fieldDataType)) { + NSMutableArray *resultArray = + GetOrCreateArrayIvarWithField(self, field, syntax); + [resultArray addObjectsFromArray:otherArray]; + } else if (fieldDataType == GPBDataTypeEnum) { + GPBEnumArray *resultArray = + GetOrCreateArrayIvarWithField(self, field, syntax); + [resultArray addRawValuesFromArray:otherArray]; + } else { + // The array type doesn't matter, that all implment + // -addValuesFromArray:. + GPBInt32Array *resultArray = + GetOrCreateArrayIvarWithField(self, field, syntax); + [resultArray addValuesFromArray:otherArray]; + } + } + } else { // fieldType = GPBFieldTypeMap + // In the case of a map, they need to be merged, and there is no + // _hasIvar to worry about setting. + id otherDict = GPBGetObjectIvarWithFieldNoAutocreate(other, field); + if (otherDict) { + GPBDataType keyDataType = field.mapKeyDataType; + GPBDataType valueDataType = field->description_->dataType; + if (GPBDataTypeIsObject(keyDataType) && + GPBDataTypeIsObject(valueDataType)) { + NSMutableDictionary *resultDict = + GetOrCreateMapIvarWithField(self, field, syntax); + [resultDict addEntriesFromDictionary:otherDict]; + } else if (valueDataType == GPBDataTypeEnum) { + // The exact type doesn't matter, just need to know it is a + // GPB*EnumDictionary. + GPBInt32EnumDictionary *resultDict = + GetOrCreateMapIvarWithField(self, field, syntax); + [resultDict addRawEntriesFromDictionary:otherDict]; + } else { + // The exact type doesn't matter, they all implement + // -addEntriesFromDictionary:. + GPBInt32Int32Dictionary *resultDict = + GetOrCreateMapIvarWithField(self, field, syntax); + [resultDict addEntriesFromDictionary:otherDict]; + } + } + } // if (fieldType)..else if...else + } // for(fields) + + // Unknown fields. + if (!unknownFields_) { + [self setUnknownFields:other.unknownFields]; + } else { + [unknownFields_ mergeUnknownFields:other.unknownFields]; + } + + // Extensions + + if (other->extensionMap_.count == 0) { + return; + } + + if (extensionMap_ == nil) { + extensionMap_ = + CloneExtensionMap(other->extensionMap_, NSZoneFromPointer(self)); + } else { + for (GPBExtensionDescriptor *extension in other->extensionMap_) { + id otherValue = [other->extensionMap_ objectForKey:extension]; + id value = [extensionMap_ objectForKey:extension]; + BOOL isMessageExtension = GPBExtensionIsMessage(extension); + + if (extension.repeated) { + NSMutableArray *list = value; + if (list == nil) { + list = [[NSMutableArray alloc] init]; + [extensionMap_ setObject:list forKey:extension]; + [list release]; + } + if (isMessageExtension) { + for (GPBMessage *otherListValue in otherValue) { + GPBMessage *copiedValue = [otherListValue copy]; + [list addObject:copiedValue]; + [copiedValue release]; + } + } else { + [list addObjectsFromArray:otherValue]; + } + } else { + if (isMessageExtension) { + if (value) { + [(GPBMessage *)value mergeFrom:(GPBMessage *)otherValue]; + } else { + GPBMessage *copiedValue = [otherValue copy]; + [extensionMap_ setObject:copiedValue forKey:extension]; + [copiedValue release]; + } + } else { + [extensionMap_ setObject:otherValue forKey:extension]; + } + } + + if (isMessageExtension && !extension.isRepeated) { + GPBMessage *autocreatedValue = + [[autocreatedExtensionMap_ objectForKey:extension] retain]; + // Must remove from the map before calling GPBClearMessageAutocreator() + // so that GPBClearMessageAutocreator() knows its safe to clear. + [autocreatedExtensionMap_ removeObjectForKey:extension]; + GPBClearMessageAutocreator(autocreatedValue); + [autocreatedValue release]; + } + } + } +} + +#pragma mark - isEqual: & hash Support + +- (BOOL)isEqual:(id)other { + if (other == self) { + return YES; + } + if (![other isKindOfClass:[GPBMessage class]]) { + return NO; + } + GPBMessage *otherMsg = other; + GPBDescriptor *descriptor = [[self class] descriptor]; + if ([[otherMsg class] descriptor] != descriptor) { + return NO; + } + uint8_t *selfStorage = (uint8_t *)messageStorage_; + uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_; + + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (GPBFieldIsMapOrArray(field)) { + // In the case of a list or map, there is no _hasIvar to worry about. + // NOTE: These are NSArray/GPB*Array or NSDictionary/GPB*Dictionary, but + // the type doesn't really matter as the objects all support -count and + // -isEqual:. + NSArray *resultMapOrArray = + GPBGetObjectIvarWithFieldNoAutocreate(self, field); + NSArray *otherMapOrArray = + GPBGetObjectIvarWithFieldNoAutocreate(other, field); + // nil and empty are equal + if (resultMapOrArray.count != 0 || otherMapOrArray.count != 0) { + if (![resultMapOrArray isEqual:otherMapOrArray]) { + return NO; + } + } + } else { // Single field + int32_t hasIndex = GPBFieldHasIndex(field); + uint32_t fieldNum = GPBFieldNumber(field); + BOOL selfHas = GPBGetHasIvar(self, hasIndex, fieldNum); + BOOL otherHas = GPBGetHasIvar(other, hasIndex, fieldNum); + if (selfHas != otherHas) { + return NO; // Differing has values, not equal. + } + if (!selfHas) { + // Same has values, was no, nothing else to check for this field. + continue; + } + // Now compare the values. + GPBDataType fieldDataType = GPBGetFieldDataType(field); + size_t fieldOffset = field->description_->offset; + switch (fieldDataType) { + case GPBDataTypeBool: { + // Bools are stored in has_bits to avoid needing explicit space in + // the storage structure. + // (the field number passed to the HasIvar helper doesn't really + // matter since the offset is never negative) + BOOL selfValue = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0); + BOOL otherValue = GPBGetHasIvar(other, (int32_t)(fieldOffset), 0); + if (selfValue != otherValue) { + return NO; + } + break; + } + case GPBDataTypeSFixed32: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + case GPBDataTypeEnum: + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + case GPBDataTypeFloat: { + GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits); + // These are all 32bit, signed/unsigned doesn't matter for equality. + uint32_t *selfValPtr = (uint32_t *)&selfStorage[fieldOffset]; + uint32_t *otherValPtr = (uint32_t *)&otherStorage[fieldOffset]; + if (*selfValPtr != *otherValPtr) { + return NO; + } + break; + } + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + case GPBDataTypeDouble: { + GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits); + // These are all 64bit, signed/unsigned doesn't matter for equality. + uint64_t *selfValPtr = (uint64_t *)&selfStorage[fieldOffset]; + uint64_t *otherValPtr = (uint64_t *)&otherStorage[fieldOffset]; + if (*selfValPtr != *otherValPtr) { + return NO; + } + break; + } + case GPBDataTypeBytes: + case GPBDataTypeString: + case GPBDataTypeMessage: + case GPBDataTypeGroup: { + // Type doesn't matter here, they all implement -isEqual:. + id *selfValPtr = (id *)&selfStorage[fieldOffset]; + id *otherValPtr = (id *)&otherStorage[fieldOffset]; + if (![*selfValPtr isEqual:*otherValPtr]) { + return NO; + } + break; + } + } // switch() + } // if(mapOrArray)...else + } // for(fields) + + // nil and empty are equal + if (extensionMap_.count != 0 || otherMsg->extensionMap_.count != 0) { + if (![extensionMap_ isEqual:otherMsg->extensionMap_]) { + return NO; + } + } + + // nil and empty are equal + GPBUnknownFieldSet *otherUnknowns = otherMsg->unknownFields_; + if ([unknownFields_ countOfFields] != 0 || + [otherUnknowns countOfFields] != 0) { + if (![unknownFields_ isEqual:otherUnknowns]) { + return NO; + } + } + + return YES; +} + +// It is very difficult to implement a generic hash for ProtoBuf messages that +// will perform well. If you need hashing on your ProtoBufs (eg you are using +// them as dictionary keys) you will probably want to implement a ProtoBuf +// message specific hash as a category on your protobuf class. Do not make it a +// category on GPBMessage as you will conflict with this hash, and will possibly +// override hash for all generated protobufs. A good implementation of hash will +// be really fast, so we would recommend only hashing protobufs that have an +// identifier field of some kind that you can easily hash. If you implement +// hash, we would strongly recommend overriding isEqual: in your category as +// well, as the default implementation of isEqual: is extremely slow, and may +// drastically affect performance in large sets. +- (NSUInteger)hash { + GPBDescriptor *descriptor = [[self class] descriptor]; + const NSUInteger prime = 19; + uint8_t *storage = (uint8_t *)messageStorage_; + + // Start with the descriptor and then mix it with some instance info. + // Hopefully that will give a spread based on classes and what fields are set. + NSUInteger result = (NSUInteger)descriptor; + + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (GPBFieldIsMapOrArray(field)) { + // Exact type doesn't matter, just check if there are any elements. + NSArray *mapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + NSUInteger count = mapOrArray.count; + if (count) { + // NSArray/NSDictionary use count, use the field number and the count. + result = prime * result + GPBFieldNumber(field); + result = prime * result + count; + } + } else if (GPBGetHasIvarField(self, field)) { + // Just using the field number seemed simple/fast, but then a small + // message class where all the same fields are always set (to different + // things would end up all with the same hash, so pull in some data). + GPBDataType fieldDataType = GPBGetFieldDataType(field); + size_t fieldOffset = field->description_->offset; + switch (fieldDataType) { + case GPBDataTypeBool: { + // Bools are stored in has_bits to avoid needing explicit space in + // the storage structure. + // (the field number passed to the HasIvar helper doesn't really + // matter since the offset is never negative) + BOOL value = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0); + result = prime * result + value; + break; + } + case GPBDataTypeSFixed32: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + case GPBDataTypeEnum: + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + case GPBDataTypeFloat: { + GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits); + // These are all 32bit, just mix it in. + uint32_t *valPtr = (uint32_t *)&storage[fieldOffset]; + result = prime * result + *valPtr; + break; + } + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + case GPBDataTypeDouble: { + GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits); + // These are all 64bit, just mix what fits into an NSUInteger in. + uint64_t *valPtr = (uint64_t *)&storage[fieldOffset]; + result = prime * result + (NSUInteger)(*valPtr); + break; + } + case GPBDataTypeBytes: + case GPBDataTypeString: { + // Type doesn't matter here, they both implement -hash:. + id *valPtr = (id *)&storage[fieldOffset]; + result = prime * result + [*valPtr hash]; + break; + } + + case GPBDataTypeMessage: + case GPBDataTypeGroup: { + GPBMessage **valPtr = (GPBMessage **)&storage[fieldOffset]; + // Could call -hash on the sub message, but that could recurse pretty + // deep; follow the lead of NSArray/NSDictionary and don't really + // recurse for hash, instead use the field number and the descriptor + // of the sub message. Yes, this could suck for a bunch of messages + // where they all only differ in the sub messages, but if you are + // using a message with sub messages for something that needs -hash, + // odds are you are also copying them as keys, and that deep copy + // will also suck. + result = prime * result + GPBFieldNumber(field); + result = prime * result + (NSUInteger)[[*valPtr class] descriptor]; + break; + } + } // switch() + } + } + + // Unknowns and extensions are not included. + + return result; +} + +#pragma mark - Description Support + +- (NSString *)description { + NSString *textFormat = GPBTextFormatForMessage(self, @" "); + NSString *description = [NSString + stringWithFormat:@"<%@ %p>: {\n%@}", [self class], self, textFormat]; + return description; +} + +#if defined(DEBUG) && DEBUG + +// Xcode 5.1 added support for custom quick look info. +// https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/CustomClassDisplay_in_QuickLook/CH01-quick_look_for_custom_objects/CH01-quick_look_for_custom_objects.html#//apple_ref/doc/uid/TP40014001-CH2-SW1 +- (id)debugQuickLookObject { + return GPBTextFormatForMessage(self, nil); +} + +#endif // DEBUG + +#pragma mark - SerializedSize + +- (size_t)serializedSize { + GPBDescriptor *descriptor = [[self class] descriptor]; + size_t result = 0; + + // Has check is done explicitly, so GPBGetObjectIvarWithFieldNoAutocreate() + // avoids doing the has check again. + + // Fields. + for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) { + GPBFieldType fieldType = fieldDescriptor.fieldType; + GPBDataType fieldDataType = GPBGetFieldDataType(fieldDescriptor); + + // Single Fields + if (fieldType == GPBFieldTypeSingle) { + BOOL selfHas = GPBGetHasIvarField(self, fieldDescriptor); + if (!selfHas) { + continue; // Nothing to do. + } + + uint32_t fieldNumber = GPBFieldNumber(fieldDescriptor); + + switch (fieldDataType) { +#define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \ + case GPBDataType##NAME: { \ + TYPE fieldVal = GPBGetMessage##FUNC_TYPE##Field(self, fieldDescriptor); \ + result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \ + break; \ + } +#define CASE_SINGLE_OBJECT(NAME) \ + case GPBDataType##NAME: { \ + id fieldVal = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); \ + result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \ + break; \ + } + CASE_SINGLE_POD(Bool, BOOL, Bool) + CASE_SINGLE_POD(Fixed32, uint32_t, UInt32) + CASE_SINGLE_POD(SFixed32, int32_t, Int32) + CASE_SINGLE_POD(Float, float, Float) + CASE_SINGLE_POD(Fixed64, uint64_t, UInt64) + CASE_SINGLE_POD(SFixed64, int64_t, Int64) + CASE_SINGLE_POD(Double, double, Double) + CASE_SINGLE_POD(Int32, int32_t, Int32) + CASE_SINGLE_POD(Int64, int64_t, Int64) + CASE_SINGLE_POD(SInt32, int32_t, Int32) + CASE_SINGLE_POD(SInt64, int64_t, Int64) + CASE_SINGLE_POD(UInt32, uint32_t, UInt32) + CASE_SINGLE_POD(UInt64, uint64_t, UInt64) + CASE_SINGLE_OBJECT(Bytes) + CASE_SINGLE_OBJECT(String) + CASE_SINGLE_OBJECT(Message) + CASE_SINGLE_OBJECT(Group) + CASE_SINGLE_POD(Enum, int32_t, Int32) +#undef CASE_SINGLE_POD +#undef CASE_SINGLE_OBJECT + } + + // Repeated Fields + } else if (fieldType == GPBFieldTypeRepeated) { + id genericArray = + GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); + NSUInteger count = [genericArray count]; + if (count == 0) { + continue; // Nothing to add. + } + __block size_t dataSize = 0; + + switch (fieldDataType) { +#define CASE_REPEATED_POD(NAME, TYPE, ARRAY_TYPE) \ + CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ) +#define CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ARRAY_ACCESSOR_NAME) \ + case GPBDataType##NAME: { \ + GPB##ARRAY_TYPE##Array *array = genericArray; \ + [array enumerate##ARRAY_ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { \ + _Pragma("unused(idx, stop)"); \ + dataSize += GPBCompute##NAME##SizeNoTag(value); \ + }]; \ + break; \ + } +#define CASE_REPEATED_OBJECT(NAME) \ + case GPBDataType##NAME: { \ + for (id value in genericArray) { \ + dataSize += GPBCompute##NAME##SizeNoTag(value); \ + } \ + break; \ + } + CASE_REPEATED_POD(Bool, BOOL, Bool) + CASE_REPEATED_POD(Fixed32, uint32_t, UInt32) + CASE_REPEATED_POD(SFixed32, int32_t, Int32) + CASE_REPEATED_POD(Float, float, Float) + CASE_REPEATED_POD(Fixed64, uint64_t, UInt64) + CASE_REPEATED_POD(SFixed64, int64_t, Int64) + CASE_REPEATED_POD(Double, double, Double) + CASE_REPEATED_POD(Int32, int32_t, Int32) + CASE_REPEATED_POD(Int64, int64_t, Int64) + CASE_REPEATED_POD(SInt32, int32_t, Int32) + CASE_REPEATED_POD(SInt64, int64_t, Int64) + CASE_REPEATED_POD(UInt32, uint32_t, UInt32) + CASE_REPEATED_POD(UInt64, uint64_t, UInt64) + CASE_REPEATED_OBJECT(Bytes) + CASE_REPEATED_OBJECT(String) + CASE_REPEATED_OBJECT(Message) + CASE_REPEATED_OBJECT(Group) + CASE_REPEATED_POD_EXTRA(Enum, int32_t, Enum, Raw) +#undef CASE_REPEATED_POD +#undef CASE_REPEATED_POD_EXTRA +#undef CASE_REPEATED_OBJECT + } // switch + result += dataSize; + size_t tagSize = GPBComputeTagSize(GPBFieldNumber(fieldDescriptor)); + if (fieldDataType == GPBDataTypeGroup) { + // Groups have both a start and an end tag. + tagSize *= 2; + } + if (fieldDescriptor.isPackable) { + result += tagSize; + result += GPBComputeSizeTSizeAsInt32NoTag(dataSize); + } else { + result += count * tagSize; + } + + // Map<> Fields + } else { // fieldType == GPBFieldTypeMap + if (GPBDataTypeIsObject(fieldDataType) && + (fieldDescriptor.mapKeyDataType == GPBDataTypeString)) { + // If key type was string, then the map is an NSDictionary. + NSDictionary *map = + GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); + if (map) { + result += GPBDictionaryComputeSizeInternalHelper(map, fieldDescriptor); + } + } else { + // Type will be GPB*GroupDictionary, exact type doesn't matter. + GPBInt32Int32Dictionary *map = + GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); + result += [map computeSerializedSizeAsField:fieldDescriptor]; + } + } + } // for(fields) + + // Add any unknown fields. + if (descriptor.wireFormat) { + result += [unknownFields_ serializedSizeAsMessageSet]; + } else { + result += [unknownFields_ serializedSize]; + } + + // Add any extensions. + for (GPBExtensionDescriptor *extension in extensionMap_) { + id value = [extensionMap_ objectForKey:extension]; + result += GPBComputeExtensionSerializedSizeIncludingTag(extension, value); + } + + return result; +} + +#pragma mark - Resolve Methods Support + +typedef struct ResolveIvarAccessorMethodResult { + IMP impToAdd; + SEL encodingSelector; +} ResolveIvarAccessorMethodResult; + +// |field| can be __unsafe_unretained because they are created at startup +// and are essentially global. No need to pay for retain/release when +// they are captured in blocks. +static void ResolveIvarGet(__unsafe_unretained GPBFieldDescriptor *field, + ResolveIvarAccessorMethodResult *result) { + GPBDataType fieldDataType = GPBGetFieldDataType(field); + switch (fieldDataType) { +#define CASE_GET(NAME, TYPE, TRUE_NAME) \ + case GPBDataType##NAME: { \ + result->impToAdd = imp_implementationWithBlock(^(id obj) { \ + return GPBGetMessage##TRUE_NAME##Field(obj, field); \ + }); \ + result->encodingSelector = @selector(get##NAME); \ + break; \ + } +#define CASE_GET_OBJECT(NAME, TYPE, TRUE_NAME) \ + case GPBDataType##NAME: { \ + result->impToAdd = imp_implementationWithBlock(^(id obj) { \ + return GPBGetObjectIvarWithField(obj, field); \ + }); \ + result->encodingSelector = @selector(get##NAME); \ + break; \ + } + CASE_GET(Bool, BOOL, Bool) + CASE_GET(Fixed32, uint32_t, UInt32) + CASE_GET(SFixed32, int32_t, Int32) + CASE_GET(Float, float, Float) + CASE_GET(Fixed64, uint64_t, UInt64) + CASE_GET(SFixed64, int64_t, Int64) + CASE_GET(Double, double, Double) + CASE_GET(Int32, int32_t, Int32) + CASE_GET(Int64, int64_t, Int64) + CASE_GET(SInt32, int32_t, Int32) + CASE_GET(SInt64, int64_t, Int64) + CASE_GET(UInt32, uint32_t, UInt32) + CASE_GET(UInt64, uint64_t, UInt64) + CASE_GET_OBJECT(Bytes, id, Object) + CASE_GET_OBJECT(String, id, Object) + CASE_GET_OBJECT(Message, id, Object) + CASE_GET_OBJECT(Group, id, Object) + CASE_GET(Enum, int32_t, Enum) +#undef CASE_GET + } +} + +// See comment about __unsafe_unretained on ResolveIvarGet. +static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field, + GPBFileSyntax syntax, + ResolveIvarAccessorMethodResult *result) { + GPBDataType fieldDataType = GPBGetFieldDataType(field); + switch (fieldDataType) { +#define CASE_SET(NAME, TYPE, TRUE_NAME) \ + case GPBDataType##NAME: { \ + result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \ + return GPBSet##TRUE_NAME##IvarWithFieldInternal(obj, field, value, syntax); \ + }); \ + result->encodingSelector = @selector(set##NAME:); \ + break; \ + } + CASE_SET(Bool, BOOL, Bool) + CASE_SET(Fixed32, uint32_t, UInt32) + CASE_SET(SFixed32, int32_t, Int32) + CASE_SET(Float, float, Float) + CASE_SET(Fixed64, uint64_t, UInt64) + CASE_SET(SFixed64, int64_t, Int64) + CASE_SET(Double, double, Double) + CASE_SET(Int32, int32_t, Int32) + CASE_SET(Int64, int64_t, Int64) + CASE_SET(SInt32, int32_t, Int32) + CASE_SET(SInt64, int64_t, Int64) + CASE_SET(UInt32, uint32_t, UInt32) + CASE_SET(UInt64, uint64_t, UInt64) + CASE_SET(Bytes, id, Object) + CASE_SET(String, id, Object) + CASE_SET(Message, id, Object) + CASE_SET(Group, id, Object) + CASE_SET(Enum, int32_t, Enum) +#undef CASE_SET + } +} + ++ (BOOL)resolveInstanceMethod:(SEL)sel { + const GPBDescriptor *descriptor = [self descriptor]; + if (!descriptor) { + return [super resolveInstanceMethod:sel]; + } + + // NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given + // message should not have has support (done in GPBDescriptor.m), so there is + // no need for checks here to see if has*/setHas* are allowed. + ResolveIvarAccessorMethodResult result = {NULL, NULL}; + + // See comment about __unsafe_unretained on ResolveIvarGet. + for (__unsafe_unretained GPBFieldDescriptor *field in descriptor->fields_) { + BOOL isMapOrArray = GPBFieldIsMapOrArray(field); + if (!isMapOrArray) { + // Single fields. + if (sel == field->getSel_) { + ResolveIvarGet(field, &result); + break; + } else if (sel == field->setSel_) { + ResolveIvarSet(field, descriptor.file.syntax, &result); + break; + } else if (sel == field->hasOrCountSel_) { + int32_t index = GPBFieldHasIndex(field); + uint32_t fieldNum = GPBFieldNumber(field); + result.impToAdd = imp_implementationWithBlock(^(id obj) { + return GPBGetHasIvar(obj, index, fieldNum); + }); + result.encodingSelector = @selector(getBool); + break; + } else if (sel == field->setHasSel_) { + result.impToAdd = imp_implementationWithBlock(^(id obj, BOOL value) { + if (value) { + [NSException raise:NSInvalidArgumentException + format:@"%@: %@ can only be set to NO (to clear field).", + [obj class], + NSStringFromSelector(field->setHasSel_)]; + } + GPBClearMessageField(obj, field); + }); + result.encodingSelector = @selector(setBool:); + break; + } else { + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof && (sel == oneof->caseSel_)) { + int32_t index = GPBFieldHasIndex(field); + result.impToAdd = imp_implementationWithBlock(^(id obj) { + return GPBGetHasOneof(obj, index); + }); + result.encodingSelector = @selector(getEnum); + break; + } + } + } else { + // map<>/repeated fields. + if (sel == field->getSel_) { + if (field.fieldType == GPBFieldTypeRepeated) { + result.impToAdd = imp_implementationWithBlock(^(id obj) { + return GetArrayIvarWithField(obj, field); + }); + } else { + result.impToAdd = imp_implementationWithBlock(^(id obj) { + return GetMapIvarWithField(obj, field); + }); + } + result.encodingSelector = @selector(getArray); + break; + } else if (sel == field->setSel_) { + // Local for syntax so the block can directly capture it and not the + // full lookup. + const GPBFileSyntax syntax = descriptor.file.syntax; + result.impToAdd = imp_implementationWithBlock(^(id obj, id value) { + return GPBSetObjectIvarWithFieldInternal(obj, field, value, syntax); + }); + result.encodingSelector = @selector(setArray:); + break; + } else if (sel == field->hasOrCountSel_) { + result.impToAdd = imp_implementationWithBlock(^(id obj) { + // Type doesn't matter, all *Array and *Dictionary types support + // -count. + NSArray *arrayOrMap = + GPBGetObjectIvarWithFieldNoAutocreate(obj, field); + return [arrayOrMap count]; + }); + result.encodingSelector = @selector(getArrayCount); + break; + } + } + } + if (result.impToAdd) { + const char *encoding = + GPBMessageEncodingForSelector(result.encodingSelector, YES); + Class msgClass = descriptor.messageClass; + BOOL methodAdded = class_addMethod(msgClass, sel, result.impToAdd, encoding); + // class_addMethod() is documented as also failing if the method was already + // added; so we check if the method is already there and return success so + // the method dispatch will still happen. Why would it already be added? + // Two threads could cause the same method to be bound at the same time, + // but only one will actually bind it; the other still needs to return true + // so things will dispatch. + if (!methodAdded) { + methodAdded = GPBClassHasSel(msgClass, sel); + } + return methodAdded; + } + return [super resolveInstanceMethod:sel]; +} + ++ (BOOL)resolveClassMethod:(SEL)sel { + // Extensions scoped to a Message and looked up via class methods. + if (GPBResolveExtensionClassMethod([self descriptor].messageClass, sel)) { + return YES; + } + return [super resolveClassMethod:sel]; +} + +#pragma mark - NSCoding Support + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [self init]; + if (self) { + NSData *data = + [aDecoder decodeObjectOfClass:[NSData class] forKey:kGPBDataCoderKey]; + if (data.length) { + [self mergeFromData:data extensionRegistry:nil]; + } + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + NSData *data = [self data]; + if (data.length) { + [aCoder encodeObject:data forKey:kGPBDataCoderKey]; + } +} + +#pragma mark - KVC Support + ++ (BOOL)accessInstanceVariablesDirectly { + // Make sure KVC doesn't use instance variables. + return NO; +} + +@end + +#pragma mark - Messages from GPBUtilities.h but defined here for access to helpers. + +// Only exists for public api, no core code should use this. +id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + if (field.fieldType != GPBFieldTypeRepeated) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@ is not a repeated field.", + [self class], field.name]; + } +#endif + GPBDescriptor *descriptor = [[self class] descriptor]; + GPBFileSyntax syntax = descriptor.file.syntax; + return GetOrCreateArrayIvarWithField(self, field, syntax); +} + +// Only exists for public api, no core code should use this. +id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + if (field.fieldType != GPBFieldTypeMap) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@ is not a map<> field.", + [self class], field.name]; + } +#endif + GPBDescriptor *descriptor = [[self class] descriptor]; + GPBFileSyntax syntax = descriptor.file.syntax; + return GetOrCreateMapIvarWithField(self, field, syntax); +} + +id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { + NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here"); + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + return *typePtr; + } + // Not set... + + // Non messages (string/data), get their default. + if (!GPBFieldDataTypeIsMessage(field)) { + return field.defaultValue.valueMessage; + } + + GPBPrepareReadOnlySemaphore(self); + dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); + GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + if (!result) { + // For non repeated messages, create the object, set it and return it. + // This object will not initially be visible via GPBGetHasIvar, so + // we save its creator so it can become visible if it's mutated later. + result = GPBCreateMessageWithAutocreator(field.msgClass, self, field); + GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result); + } + dispatch_semaphore_signal(self->readOnlySemaphore_); + return result; +} + +#pragma clang diagnostic pop diff --git a/My Mind/Pods/Protobuf/objectivec/GPBMessage_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBMessage_PackagePrivate.h new file mode 100644 index 0000000..ca10983 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBMessage_PackagePrivate.h @@ -0,0 +1,124 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +// This header is private to the ProtobolBuffers library and must NOT be +// included by any sources outside this library. The contents of this file are +// subject to change at any time without notice. + +#import "GPBMessage.h" + +// TODO: Remove this import. Older generated code use the OSAtomic* apis, +// so anyone that hasn't regenerated says building by having this. After +// enough time has passed, this likely can be removed as folks should have +// regenerated. +#import + +#import "GPBBootstrap.h" + +typedef struct GPBMessage_Storage { + uint32_t _has_storage_[0]; +} GPBMessage_Storage; + +typedef struct GPBMessage_Storage *GPBMessage_StoragePtr; + +@interface GPBMessage () { + @package + // NOTE: Because of the +allocWithZone code using NSAllocateObject(), + // this structure should ideally always be kept pointer aligned where the + // real storage starts is also pointer aligned. The compiler/runtime already + // do this, but it may not be documented. + + // A pointer to the actual fields of the subclasses. The actual structure + // pointed to by this pointer will depend on the subclass. + // All of the actual structures will start the same as + // GPBMessage_Storage with _has_storage__ as the first field. + // Kept public because static functions need to access it. + GPBMessage_StoragePtr messageStorage_; +} + +// Gets an extension value without autocreating the result if not found. (i.e. +// returns nil if the extension is not set) +- (id)getExistingExtension:(GPBExtensionDescriptor *)extension; + +// Parses a message of this type from the input and merges it with this +// message. +// +// Warning: This does not verify that all required fields are present in +// the input message. +// Note: The caller should call +// -[CodedInputStream checkLastTagWas:] after calling this to +// verify that the last tag seen was the appropriate end-group tag, +// or zero for EOF. +// NOTE: This will throw if there is an error while parsing. +- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; + +// Parses the next delimited message of this type from the input and merges it +// with this message. +- (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input + extensionRegistry: + (GPBExtensionRegistry *)extensionRegistry; + +- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; + +@end + +CF_EXTERN_C_BEGIN + + +// Call this before using the readOnlySemaphore_. This ensures it is created only once. +void GPBPrepareReadOnlySemaphore(GPBMessage *self); + +// Returns a new instance that was automatically created by |autocreator| for +// its field |field|. +GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, + GPBMessage *autocreator, + GPBFieldDescriptor *field) + __attribute__((ns_returns_retained)); + +// Returns whether |message| autocreated this message. This is NO if the message +// was not autocreated by |message| or if it has been mutated since +// autocreation. +BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent); + +// Call this when you mutate a message. It will cause the message to become +// visible to its autocreator. +void GPBBecomeVisibleToAutocreator(GPBMessage *self); + +// Call this when an array/dictionary is mutated so the parent message that +// autocreated it can react. +void GPBAutocreatedArrayModified(GPBMessage *self, id array); +void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary); + +// Clear the autocreator, if any. Asserts if the autocreator still has an +// autocreated reference to this message. +void GPBClearMessageAutocreator(GPBMessage *self); + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers.h b/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers.h new file mode 100644 index 0000000..68d8854 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers.h @@ -0,0 +1,76 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBBootstrap.h" + +#import "GPBArray.h" +#import "GPBCodedInputStream.h" +#import "GPBCodedOutputStream.h" +#import "GPBDescriptor.h" +#import "GPBDictionary.h" +#import "GPBExtensionRegistry.h" +#import "GPBMessage.h" +#import "GPBRootObject.h" +#import "GPBUnknownField.h" +#import "GPBUnknownFieldSet.h" +#import "GPBUtilities.h" +#import "GPBWellKnownTypes.h" +#import "GPBWireFormat.h" + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +// Well-known proto types +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import + #import + #import + #import + #import + #import + #import + #import +#else + #import "google/protobuf/Any.pbobjc.h" + #import "google/protobuf/Api.pbobjc.h" + #import "google/protobuf/Duration.pbobjc.h" + #import "google/protobuf/Empty.pbobjc.h" + #import "google/protobuf/FieldMask.pbobjc.h" + #import "google/protobuf/SourceContext.pbobjc.h" + #import "google/protobuf/Struct.pbobjc.h" + #import "google/protobuf/Timestamp.pbobjc.h" + #import "google/protobuf/Type.pbobjc.h" + #import "google/protobuf/Wrappers.pbobjc.h" +#endif diff --git a/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h b/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h new file mode 100644 index 0000000..04dde62 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h @@ -0,0 +1,40 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +// This header is meant to only be used by the generated source, it should not +// be included in code using protocol buffers. + +#import "GPBBootstrap.h" + +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBExtensionInternals.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBRootObject_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" diff --git a/My Mind/Pods/Protobuf/objectivec/GPBRootObject.h b/My Mind/Pods/Protobuf/objectivec/GPBRootObject.h new file mode 100644 index 0000000..d2e2aeb --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBRootObject.h @@ -0,0 +1,52 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +@class GPBExtensionRegistry; + +NS_ASSUME_NONNULL_BEGIN + +/** + * Every generated proto file defines a local "Root" class that exposes a + * GPBExtensionRegistry for all the extensions defined by that file and + * the files it depends on. + **/ +@interface GPBRootObject : NSObject + +/** + * @return An extension registry for the given file and all the files it depends + * on. + **/ ++ (GPBExtensionRegistry *)extensionRegistry; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBRootObject.m b/My Mind/Pods/Protobuf/objectivec/GPBRootObject.m new file mode 100644 index 0000000..bad2f9a --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBRootObject.m @@ -0,0 +1,245 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBRootObject_PackagePrivate.h" + +#import + +#import + +#import "GPBDescriptor.h" +#import "GPBExtensionRegistry.h" +#import "GPBUtilities_PackagePrivate.h" + +@interface GPBExtensionDescriptor (GPBRootObject) +// Get singletonName as a c string. +- (const char *)singletonNameC; +@end + +// We need some object to conform to the MessageSignatureProtocol to make sure +// the selectors in it are recorded in our Objective C runtime information. +// GPBMessage is arguably the more "obvious" choice, but given that all messages +// inherit from GPBMessage, conflicts seem likely, so we are using GPBRootObject +// instead. +@interface GPBRootObject () +@end + +@implementation GPBRootObject + +// Taken from http://www.burtleburtle.net/bob/hash/doobs.html +// Public Domain +static uint32_t jenkins_one_at_a_time_hash(const char *key) { + uint32_t hash = 0; + for (uint32_t i = 0; key[i] != '\0'; ++i) { + hash += key[i]; + hash += (hash << 10); + hash ^= (hash >> 6); + } + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + return hash; +} + +// Key methods for our custom CFDictionary. +// Note that the dictionary lasts for the lifetime of our app, so no need +// to worry about deallocation. All of the items are added to it at +// startup, and so the keys don't need to be retained/released. +// Keys are NULL terminated char *. +static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, + const void *value) { +#pragma unused(allocator) + return value; +} + +static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, + const void *value) { +#pragma unused(allocator) +#pragma unused(value) +} + +static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) { + const char *key = (const char *)value; + return CFStringCreateWithCString(kCFAllocatorDefault, key, + kCFStringEncodingUTF8); +} + +static Boolean GPBRootExtensionKeyEqual(const void *value1, + const void *value2) { + const char *key1 = (const char *)value1; + const char *key2 = (const char *)value2; + return strcmp(key1, key2) == 0; +} + +static CFHashCode GPBRootExtensionKeyHash(const void *value) { + const char *key = (const char *)value; + return jenkins_one_at_a_time_hash(key); +} + +// NOTE: OSSpinLock may seem like a good fit here but Apple engineers have +// pointed out that they are vulnerable to live locking on iOS in cases of +// priority inversion: +// http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/ +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html +static dispatch_semaphore_t gExtensionSingletonDictionarySemaphore; +static CFMutableDictionaryRef gExtensionSingletonDictionary = NULL; +static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL; + ++ (void)initialize { + // Ensure the global is started up. + if (!gExtensionSingletonDictionary) { + gExtensionSingletonDictionarySemaphore = dispatch_semaphore_create(1); + CFDictionaryKeyCallBacks keyCallBacks = { + // See description above for reason for using custom dictionary. + 0, + GPBRootExtensionKeyRetain, + GPBRootExtensionKeyRelease, + GPBRootExtensionCopyKeyDescription, + GPBRootExtensionKeyEqual, + GPBRootExtensionKeyHash, + }; + gExtensionSingletonDictionary = + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks, + &kCFTypeDictionaryValueCallBacks); + gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init]; + } + + if ([self superclass] == [GPBRootObject class]) { + // This is here to start up all the per file "Root" subclasses. + // This must be done in initialize to enforce thread safety of start up of + // the protocol buffer library. + [self extensionRegistry]; + } +} + ++ (GPBExtensionRegistry *)extensionRegistry { + // Is overridden in all the subclasses that provide extensions to provide the + // per class one. + return gDefaultExtensionRegistry; +} + ++ (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field { + const char *key = [field singletonNameC]; + dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, + DISPATCH_TIME_FOREVER); + CFDictionarySetValue(gExtensionSingletonDictionary, key, field); + dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); +} + +static id ExtensionForName(id self, SEL _cmd) { + // Really fast way of doing "classname_selName". + // This came up as a hotspot (creation of NSString *) when accessing a + // lot of extensions. + const char *selName = sel_getName(_cmd); + if (selName[0] == '_') { + return nil; // Apple internal selector. + } + size_t selNameLen = 0; + while (1) { + char c = selName[selNameLen]; + if (c == '\0') { // String end. + break; + } + if (c == ':') { + return nil; // Selector took an arg, not one of the runtime methods. + } + ++selNameLen; + } + + const char *className = class_getName(self); + size_t classNameLen = strlen(className); + char key[classNameLen + selNameLen + 2]; + memcpy(key, className, classNameLen); + key[classNameLen] = '_'; + memcpy(&key[classNameLen + 1], selName, selNameLen); + key[classNameLen + 1 + selNameLen] = '\0'; + + // NOTE: Even though this method is called from another C function, + // gExtensionSingletonDictionarySemaphore and gExtensionSingletonDictionary + // will always be initialized. This is because this call flow is just to + // lookup the Extension, meaning the code is calling an Extension class + // message on a Message or Root class. This guarantees that the class was + // initialized and Message classes ensure their Root was also initialized. + NSAssert(gExtensionSingletonDictionary, @"Startup order broken!"); + + dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, + DISPATCH_TIME_FOREVER); + id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key); + // We can't remove the key from the dictionary here (as an optimization), + // two threads could have gone into +resolveClassMethod: for the same method, + // and ended up here; there's no way to ensure both return YES without letting + // both try to wire in the method. + dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); + return extension; +} + +BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) { + // Another option would be to register the extensions with the class at + // globallyRegisterExtension: + // Timing the two solutions, this solution turned out to be much faster + // and reduced startup time, and runtime memory. + // The advantage to globallyRegisterExtension is that it would reduce the + // size of the protos somewhat because the singletonNameC wouldn't need + // to include the class name. For a class with a lot of extensions it + // can add up. You could also significantly reduce the code complexity of this + // file. + id extension = ExtensionForName(self, sel); + if (extension != nil) { + const char *encoding = + GPBMessageEncodingForSelector(@selector(getClassValue), NO); + Class metaClass = objc_getMetaClass(class_getName(self)); + IMP imp = imp_implementationWithBlock(^(id obj) { +#pragma unused(obj) + return extension; + }); + BOOL methodAdded = class_addMethod(metaClass, sel, imp, encoding); + // class_addMethod() is documented as also failing if the method was already + // added; so we check if the method is already there and return success so + // the method dispatch will still happen. Why would it already be added? + // Two threads could cause the same method to be bound at the same time, + // but only one will actually bind it; the other still needs to return true + // so things will dispatch. + if (!methodAdded) { + methodAdded = GPBClassHasSel(metaClass, sel); + } + return methodAdded; + } + return NO; +} + + ++ (BOOL)resolveClassMethod:(SEL)sel { + if (GPBResolveExtensionClassMethod(self, sel)) { + return YES; + } + return [super resolveClassMethod:sel]; +} + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBRootObject_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBRootObject_PackagePrivate.h new file mode 100644 index 0000000..3c8f09c --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBRootObject_PackagePrivate.h @@ -0,0 +1,46 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBRootObject.h" + +@class GPBExtensionDescriptor; + +@interface GPBRootObject () + +// Globally register. ++ (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field; + +@end + +// Returns YES if the selector was resolved and added to the class, +// NO otherwise. +BOOL GPBResolveExtensionClassMethod(Class self, SEL sel); diff --git a/My Mind/Pods/Protobuf/objectivec/GPBRuntimeTypes.h b/My Mind/Pods/Protobuf/objectivec/GPBRuntimeTypes.h new file mode 100644 index 0000000..4d55206 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBRuntimeTypes.h @@ -0,0 +1,144 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBBootstrap.h" + +@class GPBEnumDescriptor; +@class GPBMessage; +@class GPBInt32Array; + +/** + * Verifies that a given value can be represented by an enum type. + * */ +typedef BOOL (*GPBEnumValidationFunc)(int32_t); + +/** + * Fetches an EnumDescriptor. + * */ +typedef GPBEnumDescriptor *(*GPBEnumDescriptorFunc)(void); + +/** + * Magic value used at runtime to indicate an enum value that wasn't know at + * compile time. + * */ +enum { + kGPBUnrecognizedEnumeratorValue = (int32_t)0xFBADBEEF, +}; + +/** + * A union for storing all possible Protobuf values. Note that owner is + * responsible for memory management of object types. + * */ +typedef union { + BOOL valueBool; + int32_t valueInt32; + int64_t valueInt64; + uint32_t valueUInt32; + uint64_t valueUInt64; + float valueFloat; + double valueDouble; + GPB_UNSAFE_UNRETAINED NSData *valueData; + GPB_UNSAFE_UNRETAINED NSString *valueString; + GPB_UNSAFE_UNRETAINED GPBMessage *valueMessage; + int32_t valueEnum; +} GPBGenericValue; + +/** + * Enum listing the possible data types that a field can contain. + * + * @note Do not change the order of this enum (or add things to it) without + * thinking about it very carefully. There are several things that depend + * on the order. + * */ +typedef NS_ENUM(uint8_t, GPBDataType) { + /** Field contains boolean value(s). */ + GPBDataTypeBool = 0, + /** Field contains unsigned 4 byte value(s). */ + GPBDataTypeFixed32, + /** Field contains signed 4 byte value(s). */ + GPBDataTypeSFixed32, + /** Field contains float value(s). */ + GPBDataTypeFloat, + /** Field contains unsigned 8 byte value(s). */ + GPBDataTypeFixed64, + /** Field contains signed 8 byte value(s). */ + GPBDataTypeSFixed64, + /** Field contains double value(s). */ + GPBDataTypeDouble, + /** + * Field contains variable length value(s). Inefficient for encoding negative + * numbers – if your field is likely to have negative values, use + * GPBDataTypeSInt32 instead. + **/ + GPBDataTypeInt32, + /** + * Field contains variable length value(s). Inefficient for encoding negative + * numbers – if your field is likely to have negative values, use + * GPBDataTypeSInt64 instead. + **/ + GPBDataTypeInt64, + /** Field contains signed variable length integer value(s). */ + GPBDataTypeSInt32, + /** Field contains signed variable length integer value(s). */ + GPBDataTypeSInt64, + /** Field contains unsigned variable length integer value(s). */ + GPBDataTypeUInt32, + /** Field contains unsigned variable length integer value(s). */ + GPBDataTypeUInt64, + /** Field contains an arbitrary sequence of bytes. */ + GPBDataTypeBytes, + /** Field contains UTF-8 encoded or 7-bit ASCII text. */ + GPBDataTypeString, + /** Field contains message type(s). */ + GPBDataTypeMessage, + /** Field contains message type(s). */ + GPBDataTypeGroup, + /** Field contains enum value(s). */ + GPBDataTypeEnum, +}; + +enum { + /** + * A count of the number of types in GPBDataType. Separated out from the + * GPBDataType enum to avoid warnings regarding not handling GPBDataType_Count + * in switch statements. + **/ + GPBDataType_Count = GPBDataTypeEnum + 1 +}; + +/** An extension range. */ +typedef struct GPBExtensionRange { + /** Inclusive. */ + uint32_t start; + /** Exclusive. */ + uint32_t end; +} GPBExtensionRange; diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.h b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.h new file mode 100644 index 0000000..5b96023 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.h @@ -0,0 +1,99 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +@class GPBCodedOutputStream; +@class GPBUInt32Array; +@class GPBUInt64Array; +@class GPBUnknownFieldSet; + +NS_ASSUME_NONNULL_BEGIN +/** + * Store an unknown field. These are used in conjunction with + * GPBUnknownFieldSet. + **/ +@interface GPBUnknownField : NSObject + +/** Initialize a field with the given number. */ +- (instancetype)initWithNumber:(int32_t)number; + +/** The field number the data is stored under. */ +@property(nonatomic, readonly, assign) int32_t number; + +/** An array of varint values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt64Array *varintList; + +/** An array of fixed32 values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt32Array *fixed32List; + +/** An array of fixed64 values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt64Array *fixed64List; + +/** An array of data values for this field. */ +@property(nonatomic, readonly, strong) NSArray *lengthDelimitedList; + +/** An array of groups of values for this field. */ +@property(nonatomic, readonly, strong) NSArray *groupList; + +/** + * Add a value to the varintList. + * + * @param value The value to add. + **/ +- (void)addVarint:(uint64_t)value; +/** + * Add a value to the fixed32List. + * + * @param value The value to add. + **/ +- (void)addFixed32:(uint32_t)value; +/** + * Add a value to the fixed64List. + * + * @param value The value to add. + **/ +- (void)addFixed64:(uint64_t)value; +/** + * Add a value to the lengthDelimitedList. + * + * @param value The value to add. + **/ +- (void)addLengthDelimited:(NSData *)value; +/** + * Add a value to the groupList. + * + * @param value The value to add. + **/ +- (void)addGroup:(GPBUnknownFieldSet *)value; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.m b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.m new file mode 100644 index 0000000..9d5c97f --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField.m @@ -0,0 +1,336 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBUnknownField_PackagePrivate.h" + +#import "GPBArray.h" +#import "GPBCodedOutputStream_PackagePrivate.h" + +@implementation GPBUnknownField { + @protected + int32_t number_; + GPBUInt64Array *mutableVarintList_; + GPBUInt32Array *mutableFixed32List_; + GPBUInt64Array *mutableFixed64List_; + NSMutableArray *mutableLengthDelimitedList_; + NSMutableArray *mutableGroupList_; +} + +@synthesize number = number_; +@synthesize varintList = mutableVarintList_; +@synthesize fixed32List = mutableFixed32List_; +@synthesize fixed64List = mutableFixed64List_; +@synthesize lengthDelimitedList = mutableLengthDelimitedList_; +@synthesize groupList = mutableGroupList_; + +- (instancetype)initWithNumber:(int32_t)number { + if ((self = [super init])) { + number_ = number; + } + return self; +} + +- (void)dealloc { + [mutableVarintList_ release]; + [mutableFixed32List_ release]; + [mutableFixed64List_ release]; + [mutableLengthDelimitedList_ release]; + [mutableGroupList_ release]; + + [super dealloc]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (id)copyWithZone:(NSZone *)zone { + GPBUnknownField *result = + [[GPBUnknownField allocWithZone:zone] initWithNumber:number_]; + result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone]; + result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone]; + result->mutableLengthDelimitedList_ = + [mutableLengthDelimitedList_ mutableCopyWithZone:zone]; + result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone]; + if (mutableGroupList_.count) { + result->mutableGroupList_ = [[NSMutableArray allocWithZone:zone] + initWithCapacity:mutableGroupList_.count]; + for (GPBUnknownFieldSet *group in mutableGroupList_) { + GPBUnknownFieldSet *copied = [group copyWithZone:zone]; + [result->mutableGroupList_ addObject:copied]; + [copied release]; + } + } + return result; +} + +- (BOOL)isEqual:(id)object { + if (self == object) return YES; + if (![object isKindOfClass:[GPBUnknownField class]]) return NO; + GPBUnknownField *field = (GPBUnknownField *)object; + if (number_ != field->number_) return NO; + BOOL equalVarint = + (mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) || + [mutableVarintList_ isEqual:field->mutableVarintList_]; + if (!equalVarint) return NO; + BOOL equalFixed32 = (mutableFixed32List_.count == 0 && + field->mutableFixed32List_.count == 0) || + [mutableFixed32List_ isEqual:field->mutableFixed32List_]; + if (!equalFixed32) return NO; + BOOL equalFixed64 = (mutableFixed64List_.count == 0 && + field->mutableFixed64List_.count == 0) || + [mutableFixed64List_ isEqual:field->mutableFixed64List_]; + if (!equalFixed64) return NO; + BOOL equalLDList = + (mutableLengthDelimitedList_.count == 0 && + field->mutableLengthDelimitedList_.count == 0) || + [mutableLengthDelimitedList_ isEqual:field->mutableLengthDelimitedList_]; + if (!equalLDList) return NO; + BOOL equalGroupList = + (mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) || + [mutableGroupList_ isEqual:field->mutableGroupList_]; + if (!equalGroupList) return NO; + return YES; +} + +- (NSUInteger)hash { + // Just mix the hashes of the possible sub arrays. + const int prime = 31; + NSUInteger result = prime + [mutableVarintList_ hash]; + result = prime * result + [mutableFixed32List_ hash]; + result = prime * result + [mutableFixed64List_ hash]; + result = prime * result + [mutableLengthDelimitedList_ hash]; + result = prime * result + [mutableGroupList_ hash]; + return result; +} + +- (void)writeToOutput:(GPBCodedOutputStream *)output { + NSUInteger count = mutableVarintList_.count; + if (count > 0) { + [output writeUInt64Array:number_ values:mutableVarintList_ tag:0]; + } + count = mutableFixed32List_.count; + if (count > 0) { + [output writeFixed32Array:number_ values:mutableFixed32List_ tag:0]; + } + count = mutableFixed64List_.count; + if (count > 0) { + [output writeFixed64Array:number_ values:mutableFixed64List_ tag:0]; + } + count = mutableLengthDelimitedList_.count; + if (count > 0) { + [output writeBytesArray:number_ values:mutableLengthDelimitedList_]; + } + count = mutableGroupList_.count; + if (count > 0) { + [output writeUnknownGroupArray:number_ values:mutableGroupList_]; + } +} + +- (size_t)serializedSize { + __block size_t result = 0; + int32_t number = number_; + [mutableVarintList_ + enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + result += GPBComputeUInt64Size(number, value); + }]; + + [mutableFixed32List_ + enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + result += GPBComputeFixed32Size(number, value); + }]; + + [mutableFixed64List_ + enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + result += GPBComputeFixed64Size(number, value); + }]; + + for (NSData *data in mutableLengthDelimitedList_) { + result += GPBComputeBytesSize(number, data); + } + + for (GPBUnknownFieldSet *set in mutableGroupList_) { + result += GPBComputeUnknownGroupSize(number, set); + } + + return result; +} + +- (void)writeAsMessageSetExtensionToOutput:(GPBCodedOutputStream *)output { + for (NSData *data in mutableLengthDelimitedList_) { + [output writeRawMessageSetExtension:number_ value:data]; + } +} + +- (size_t)serializedSizeAsMessageSetExtension { + size_t result = 0; + for (NSData *data in mutableLengthDelimitedList_) { + result += GPBComputeRawMessageSetExtensionSize(number_, data); + } + return result; +} + +- (NSString *)description { + NSMutableString *description = + [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", + [self class], self, number_]; + [mutableVarintList_ + enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [description appendFormat:@"\t%llu\n", value]; + }]; + + [mutableFixed32List_ + enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [description appendFormat:@"\t%u\n", value]; + }]; + + [mutableFixed64List_ + enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { +#pragma unused(idx, stop) + [description appendFormat:@"\t%llu\n", value]; + }]; + + for (NSData *data in mutableLengthDelimitedList_) { + [description appendFormat:@"\t%@\n", data]; + } + + for (GPBUnknownFieldSet *set in mutableGroupList_) { + [description appendFormat:@"\t%@\n", set]; + } + [description appendString:@"}"]; + return description; +} + +- (void)mergeFromField:(GPBUnknownField *)other { + GPBUInt64Array *otherVarintList = other.varintList; + if (otherVarintList.count > 0) { + if (mutableVarintList_ == nil) { + mutableVarintList_ = [otherVarintList copy]; + } else { + [mutableVarintList_ addValuesFromArray:otherVarintList]; + } + } + + GPBUInt32Array *otherFixed32List = other.fixed32List; + if (otherFixed32List.count > 0) { + if (mutableFixed32List_ == nil) { + mutableFixed32List_ = [otherFixed32List copy]; + } else { + [mutableFixed32List_ addValuesFromArray:otherFixed32List]; + } + } + + GPBUInt64Array *otherFixed64List = other.fixed64List; + if (otherFixed64List.count > 0) { + if (mutableFixed64List_ == nil) { + mutableFixed64List_ = [otherFixed64List copy]; + } else { + [mutableFixed64List_ addValuesFromArray:otherFixed64List]; + } + } + + NSArray *otherLengthDelimitedList = other.lengthDelimitedList; + if (otherLengthDelimitedList.count > 0) { + if (mutableLengthDelimitedList_ == nil) { + mutableLengthDelimitedList_ = [otherLengthDelimitedList mutableCopy]; + } else { + [mutableLengthDelimitedList_ + addObjectsFromArray:otherLengthDelimitedList]; + } + } + + NSArray *otherGroupList = other.groupList; + if (otherGroupList.count > 0) { + if (mutableGroupList_ == nil) { + mutableGroupList_ = + [[NSMutableArray alloc] initWithCapacity:otherGroupList.count]; + } + // Make our own mutable copies. + for (GPBUnknownFieldSet *group in otherGroupList) { + GPBUnknownFieldSet *copied = [group copy]; + [mutableGroupList_ addObject:copied]; + [copied release]; + } + } +} + +- (void)addVarint:(uint64_t)value { + if (mutableVarintList_ == nil) { + mutableVarintList_ = [[GPBUInt64Array alloc] initWithValues:&value count:1]; + } else { + [mutableVarintList_ addValue:value]; + } +} + +- (void)addFixed32:(uint32_t)value { + if (mutableFixed32List_ == nil) { + mutableFixed32List_ = + [[GPBUInt32Array alloc] initWithValues:&value count:1]; + } else { + [mutableFixed32List_ addValue:value]; + } +} + +- (void)addFixed64:(uint64_t)value { + if (mutableFixed64List_ == nil) { + mutableFixed64List_ = + [[GPBUInt64Array alloc] initWithValues:&value count:1]; + } else { + [mutableFixed64List_ addValue:value]; + } +} + +- (void)addLengthDelimited:(NSData *)value { + if (mutableLengthDelimitedList_ == nil) { + mutableLengthDelimitedList_ = + [[NSMutableArray alloc] initWithObjects:&value count:1]; + } else { + [mutableLengthDelimitedList_ addObject:value]; + } +} + +- (void)addGroup:(GPBUnknownFieldSet *)value { + if (mutableGroupList_ == nil) { + mutableGroupList_ = [[NSMutableArray alloc] initWithObjects:&value count:1]; + } else { + [mutableGroupList_ addObject:value]; + } +} + +#pragma clang diagnostic pop + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.h b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.h new file mode 100644 index 0000000..1b5f24f --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.h @@ -0,0 +1,82 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +@class GPBUnknownField; + +NS_ASSUME_NONNULL_BEGIN + +/** + * A collection of unknown fields. Fields parsed from the binary representation + * of a message that are unknown end up in an instance of this set. This only + * applies for files declared with the "proto2" syntax. Files declared with the + * "proto3" syntax discard the unknown values. + **/ +@interface GPBUnknownFieldSet : NSObject + +/** + * Tests to see if the given field number has a value. + * + * @param number The field number to check. + * + * @return YES if there is an unknown field for the given field number. + **/ +- (BOOL)hasField:(int32_t)number; + +/** + * Fetches the GPBUnknownField for the given field number. + * + * @param number The field number to look up. + * + * @return The GPBUnknownField or nil if none found. + **/ +- (nullable GPBUnknownField *)getField:(int32_t)number; + +/** + * @return The number of fields in this set. + **/ +- (NSUInteger)countOfFields; + +/** + * Adds the given field to the set. + * + * @param field The field to add to the set. + **/ +- (void)addField:(GPBUnknownField *)field; + +/** + * @return An array of the GPBUnknownFields sorted by the field numbers. + **/ +- (NSArray *)sortedFields; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.m b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.m new file mode 100644 index 0000000..a7335f0 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet.m @@ -0,0 +1,395 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBUnknownFieldSet_PackagePrivate.h" + +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream.h" +#import "GPBUnknownField_PackagePrivate.h" +#import "GPBUtilities.h" +#import "GPBWireFormat.h" + +#pragma mark Helpers + +static void checkNumber(int32_t number) { + if (number == 0) { + [NSException raise:NSInvalidArgumentException + format:@"Zero is not a valid field number."]; + } +} + +@implementation GPBUnknownFieldSet { + @package + CFMutableDictionaryRef fields_; +} + +static void CopyWorker(const void *key, const void *value, void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBUnknownFieldSet *result = context; + + GPBUnknownField *copied = [field copy]; + [result addField:copied]; + [copied release]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (id)copyWithZone:(NSZone *)zone { + GPBUnknownFieldSet *result = [[GPBUnknownFieldSet allocWithZone:zone] init]; + if (fields_) { + CFDictionaryApplyFunction(fields_, CopyWorker, result); + } + return result; +} + +- (void)dealloc { + if (fields_) { + CFRelease(fields_); + } + [super dealloc]; +} + +- (BOOL)isEqual:(id)object { + BOOL equal = NO; + if ([object isKindOfClass:[GPBUnknownFieldSet class]]) { + GPBUnknownFieldSet *set = (GPBUnknownFieldSet *)object; + if ((fields_ == NULL) && (set->fields_ == NULL)) { + equal = YES; + } else if ((fields_ != NULL) && (set->fields_ != NULL)) { + equal = CFEqual(fields_, set->fields_); + } + } + return equal; +} + +- (NSUInteger)hash { + // Return the hash of the fields dictionary (or just some value). + if (fields_) { + return CFHash(fields_); + } + return (NSUInteger)[GPBUnknownFieldSet class]; +} + +#pragma mark - Public Methods + +- (BOOL)hasField:(int32_t)number { + ssize_t key = number; + return fields_ ? (CFDictionaryGetValue(fields_, (void *)key) != nil) : NO; +} + +- (GPBUnknownField *)getField:(int32_t)number { + ssize_t key = number; + GPBUnknownField *result = + fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil; + return result; +} + +- (NSUInteger)countOfFields { + return fields_ ? CFDictionaryGetCount(fields_) : 0; +} + +- (NSArray *)sortedFields { + if (!fields_) return [NSArray array]; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + GPBUnknownField *values[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, + (const void **)values); + struct GPBFieldPair { + ssize_t key; + GPBUnknownField *value; + } pairs[count]; + for (size_t i = 0; i < count; ++i) { + pairs[i].key = keys[i]; + pairs[i].value = values[i]; + }; + qsort_b(pairs, count, sizeof(struct GPBFieldPair), + ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); + for (size_t i = 0; i < count; ++i) { + values[i] = pairs[i].value; + }; + return [NSArray arrayWithObjects:values count:count]; +} + +#pragma mark - Internal Methods + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output { + if (!fields_) return; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + GPBUnknownField *values[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, + (const void **)values); + if (count > 1) { + struct GPBFieldPair { + ssize_t key; + GPBUnknownField *value; + } pairs[count]; + + for (size_t i = 0; i < count; ++i) { + pairs[i].key = keys[i]; + pairs[i].value = values[i]; + }; + qsort_b(pairs, count, sizeof(struct GPBFieldPair), + ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); + for (size_t i = 0; i < count; ++i) { + GPBUnknownField *value = pairs[i].value; + [value writeToOutput:output]; + } + } else { + [values[0] writeToOutput:output]; + } +} + +- (NSString *)description { + NSMutableString *description = [NSMutableString + stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; + NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" "); + [description appendString:textFormat]; + [description appendString:@"}"]; + return description; +} + +static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + size_t *result = context; + *result += [field serializedSize]; +} + +- (size_t)serializedSize { + size_t result = 0; + if (fields_) { + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, + &result); + } + return result; +} + +static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBCodedOutputStream *output = context; + [field writeAsMessageSetExtensionToOutput:output]; +} + +- (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output { + if (fields_) { + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, + output); + } +} + +static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + size_t *result = context; + *result += [field serializedSizeAsMessageSetExtension]; +} + +- (size_t)serializedSizeAsMessageSet { + size_t result = 0; + if (fields_) { + CFDictionaryApplyFunction( + fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result); + } + return result; +} + +- (NSData *)data { + NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize]; + GPBCodedOutputStream *output = + [[GPBCodedOutputStream alloc] initWithData:data]; + [self writeToCodedOutputStream:output]; + [output release]; + return data; +} + ++ (BOOL)isFieldTag:(int32_t)tag { + return GPBWireFormatGetTagWireType(tag) != GPBWireFormatEndGroup; +} + +- (void)addField:(GPBUnknownField *)field { + int32_t number = [field number]; + checkNumber(number); + if (!fields_) { + // Use a custom dictionary here because the keys are numbers and conversion + // back and forth from NSNumber isn't worth the cost. + fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, + &kCFTypeDictionaryValueCallBacks); + } + ssize_t key = number; + CFDictionarySetValue(fields_, (const void *)key, field); +} + +- (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create { + ssize_t key = number; + GPBUnknownField *existing = + fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil; + if (!existing && create) { + existing = [[GPBUnknownField alloc] initWithNumber:number]; + // This retains existing. + [self addField:existing]; + [existing release]; + } + return existing; +} + +static void GPBUnknownFieldSetMergeUnknownFields(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBUnknownFieldSet *self = context; + + int32_t number = [field number]; + checkNumber(number); + GPBUnknownField *oldField = [self mutableFieldForNumber:number create:NO]; + if (oldField) { + [oldField mergeFromField:field]; + } else { + // Merge only comes from GPBMessage's mergeFrom:, so it means we are on + // mutable message and are an mutable instance, so make sure we need + // mutable fields. + GPBUnknownField *fieldCopy = [field copy]; + [self addField:fieldCopy]; + [fieldCopy release]; + } +} + +- (void)mergeUnknownFields:(GPBUnknownFieldSet *)other { + if (other && other->fields_) { + CFDictionaryApplyFunction(other->fields_, + GPBUnknownFieldSetMergeUnknownFields, self); + } +} + +- (void)mergeFromData:(NSData *)data { + GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; + [self mergeFromCodedInputStream:input]; + [input checkLastTagWas:0]; + [input release]; +} + +- (void)mergeVarintField:(int32_t)number value:(int32_t)value { + checkNumber(number); + [[self mutableFieldForNumber:number create:YES] addVarint:value]; +} + +- (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input { + NSAssert(GPBWireFormatIsValidTag(tag), @"Got passed an invalid tag"); + int32_t number = GPBWireFormatGetTagFieldNumber(tag); + GPBCodedInputStreamState *state = &input->state_; + switch (GPBWireFormatGetTagWireType(tag)) { + case GPBWireFormatVarint: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addVarint:GPBCodedInputStreamReadInt64(state)]; + return YES; + } + case GPBWireFormatFixed64: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addFixed64:GPBCodedInputStreamReadFixed64(state)]; + return YES; + } + case GPBWireFormatLengthDelimited: { + NSData *data = GPBCodedInputStreamReadRetainedBytes(state); + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addLengthDelimited:data]; + [data release]; + return YES; + } + case GPBWireFormatStartGroup: { + GPBUnknownFieldSet *unknownFieldSet = [[GPBUnknownFieldSet alloc] init]; + [input readUnknownGroup:number message:unknownFieldSet]; + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addGroup:unknownFieldSet]; + [unknownFieldSet release]; + return YES; + } + case GPBWireFormatEndGroup: + return NO; + case GPBWireFormatFixed32: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addFixed32:GPBCodedInputStreamReadFixed32(state)]; + return YES; + } + } +} + +- (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData { + [[self mutableFieldForNumber:number create:YES] + addLengthDelimited:messageData]; +} + +- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { + GPBUnknownField *field = [self mutableFieldForNumber:fieldNum create:YES]; + [field addLengthDelimited:data]; +} + +- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input { + while (YES) { + int32_t tag = GPBCodedInputStreamReadTag(&input->state_); + if (tag == 0 || ![self mergeFieldFrom:tag input:input]) { + break; + } + } +} + +- (void)getTags:(int32_t *)tags { + if (!fields_) return; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, NULL); + for (size_t i = 0; i < count; ++i) { + tags[i] = (int32_t)keys[i]; + } +} + +#pragma clang diagnostic pop + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet_PackagePrivate.h new file mode 100644 index 0000000..e27127a --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownFieldSet_PackagePrivate.h @@ -0,0 +1,61 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBUnknownFieldSet.h" + +@class GPBCodedOutputStream; +@class GPBCodedInputStream; + +@interface GPBUnknownFieldSet () + ++ (BOOL)isFieldTag:(int32_t)tag; + +- (NSData *)data; + +- (size_t)serializedSize; +- (size_t)serializedSizeAsMessageSet; + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output; +- (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output; + +- (void)mergeUnknownFields:(GPBUnknownFieldSet *)other; + +- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input; +- (void)mergeFromData:(NSData *)data; + +- (void)mergeVarintField:(int32_t)number value:(int32_t)value; +- (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input; +- (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData; + +- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUnknownField_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField_PackagePrivate.h new file mode 100644 index 0000000..2b4c789 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUnknownField_PackagePrivate.h @@ -0,0 +1,47 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBUnknownField.h" + +@class GPBCodedOutputStream; + +@interface GPBUnknownField () + +- (void)writeToOutput:(GPBCodedOutputStream *)output; +- (size_t)serializedSize; + +- (void)writeAsMessageSetExtensionToOutput:(GPBCodedOutputStream *)output; +- (size_t)serializedSizeAsMessageSetExtension; + +- (void)mergeFromField:(GPBUnknownField *)other; + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUtilities.h b/My Mind/Pods/Protobuf/objectivec/GPBUtilities.h new file mode 100644 index 0000000..5464dfb --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUtilities.h @@ -0,0 +1,539 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBArray.h" +#import "GPBMessage.h" +#import "GPBRuntimeTypes.h" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +/** + * Generates a string that should be a valid "TextFormat" for the C++ version + * of Protocol Buffers. + * + * @param message The message to generate from. + * @param lineIndent A string to use as the prefix for all lines generated. Can + * be nil if no extra indent is needed. + * + * @return An NSString with the TextFormat of the message. + **/ +NSString *GPBTextFormatForMessage(GPBMessage *message, + NSString * __nullable lineIndent); + +/** + * Generates a string that should be a valid "TextFormat" for the C++ version + * of Protocol Buffers. + * + * @param unknownSet The unknown field set to generate from. + * @param lineIndent A string to use as the prefix for all lines generated. Can + * be nil if no extra indent is needed. + * + * @return An NSString with the TextFormat of the unknown field set. + **/ +NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet * __nullable unknownSet, + NSString * __nullable lineIndent); + +/** + * Checks if the given field number is set on a message. + * + * @param self The message to check. + * @param fieldNumber The field number to check. + * + * @return YES if the field number is set on the given message. + **/ +BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber); + +/** + * Checks if the given field is set on a message. + * + * @param self The message to check. + * @param field The field to check. + * + * @return YES if the field is set on the given message. + **/ +BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Clears the given field for the given message. + * + * @param self The message for which to clear the field. + * @param field The field to clear. + **/ +void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field); + +//%PDDM-EXPAND GPB_ACCESSORS() +// This block of code is generated, do not edit it directly. + + +// +// Get/Set a given field from/to a message. +// + +// Single Fields + +/** + * Gets the value of a bytes field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +NSData *GPBGetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a bytes field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field, NSData *value); + +/** + * Gets the value of a string field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +NSString *GPBGetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a string field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field, NSString *value); + +/** + * Gets the value of a message field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +GPBMessage *GPBGetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a message field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value); + +/** + * Gets the value of a group field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +GPBMessage *GPBGetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a group field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value); + +/** + * Gets the value of a bool field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a bool field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value); + +/** + * Gets the value of an int32 field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +int32_t GPBGetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of an int32 field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); + +/** + * Gets the value of an uint32 field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +uint32_t GPBGetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of an uint32 field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value); + +/** + * Gets the value of an int64 field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +int64_t GPBGetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of an int64 field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field, int64_t value); + +/** + * Gets the value of an uint64 field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +uint64_t GPBGetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of an uint64 field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value); + +/** + * Gets the value of a float field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +float GPBGetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a float field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field, float value); + +/** + * Gets the value of a double field. + * + * @param self The message from which to get the field. + * @param field The field to get. + **/ +double GPBGetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a double field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The to set in the field. + **/ +void GPBSetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field, double value); + +/** + * Gets the given enum field of a message. For proto3, if the value isn't a + * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned. + * GPBGetMessageRawEnumField will bypass the check and return whatever value + * was set. + * + * @param self The message from which to get the field. + * @param field The field to get. + * + * @return The enum value for the given field. + **/ +int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Set the given enum field of a message. You can only set values that are + * members of the enum. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The enum value to set in the field. + **/ +void GPBSetMessageEnumField(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value); + +/** + * Get the given enum field of a message. No check is done to ensure the value + * was defined in the enum. + * + * @param self The message from which to get the field. + * @param field The field to get. + * + * @return The raw enum value for the given field. + **/ +int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Set the given enum field of a message. You can set the value to anything, + * even a value that is not a member of the enum. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param value The raw enum value to set in the field. + **/ +void GPBSetMessageRawEnumField(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value); + +// Repeated Fields + +/** + * Gets the value of a repeated field. + * + * @param self The message from which to get the field. + * @param field The repeated field to get. + * + * @return A GPB*Array or an NSMutableArray based on the field's type. + **/ +id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a repeated field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param array A GPB*Array or NSMutableArray based on the field's type. + **/ +void GPBSetMessageRepeatedField(GPBMessage *self, + GPBFieldDescriptor *field, + id array); + +// Map Fields + +/** + * Gets the value of a map<> field. + * + * @param self The message from which to get the field. + * @param field The repeated field to get. + * + * @return A GPB*Dictionary or NSMutableDictionary based on the field's type. + **/ +id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field); + +/** + * Sets the value of a map<> field. + * + * @param self The message into which to set the field. + * @param field The field to set. + * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the + * field's type. + **/ +void GPBSetMessageMapField(GPBMessage *self, + GPBFieldDescriptor *field, + id dictionary); + +//%PDDM-EXPAND-END GPB_ACCESSORS() + +/** + * Returns an empty NSData to assign to byte fields when you wish to assign them + * to empty. Prevents allocating a lot of little [NSData data] objects. + **/ +NSData *GPBEmptyNSData(void) __attribute__((pure)); + +/** + * Drops the `unknownFields` from the given message and from all sub message. + **/ +void GPBMessageDropUnknownFieldsRecursively(GPBMessage *message); + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + + +//%PDDM-DEFINE GPB_ACCESSORS() +//% +//%// +//%// Get/Set a given field from/to a message. +//%// +//% +//%// Single Fields +//% +//%GPB_ACCESSOR_SINGLE_FULL(Bytes, NSData, , *) +//%GPB_ACCESSOR_SINGLE_FULL(String, NSString, , *) +//%GPB_ACCESSOR_SINGLE_FULL(Message, GPBMessage, , *) +//%GPB_ACCESSOR_SINGLE_FULL(Group, GPBMessage, , *) +//%GPB_ACCESSOR_SINGLE(Bool, BOOL, ) +//%GPB_ACCESSOR_SINGLE(Int32, int32_t, n) +//%GPB_ACCESSOR_SINGLE(UInt32, uint32_t, n) +//%GPB_ACCESSOR_SINGLE(Int64, int64_t, n) +//%GPB_ACCESSOR_SINGLE(UInt64, uint64_t, n) +//%GPB_ACCESSOR_SINGLE(Float, float, ) +//%GPB_ACCESSOR_SINGLE(Double, double, ) +//%/** +//% * Gets the given enum field of a message. For proto3, if the value isn't a +//% * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned. +//% * GPBGetMessageRawEnumField will bypass the check and return whatever value +//% * was set. +//% * +//% * @param self The message from which to get the field. +//% * @param field The field to get. +//% * +//% * @return The enum value for the given field. +//% **/ +//%int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field); +//% +//%/** +//% * Set the given enum field of a message. You can only set values that are +//% * members of the enum. +//% * +//% * @param self The message into which to set the field. +//% * @param field The field to set. +//% * @param value The enum value to set in the field. +//% **/ +//%void GPBSetMessageEnumField(GPBMessage *self, +//% GPBFieldDescriptor *field, +//% int32_t value); +//% +//%/** +//% * Get the given enum field of a message. No check is done to ensure the value +//% * was defined in the enum. +//% * +//% * @param self The message from which to get the field. +//% * @param field The field to get. +//% * +//% * @return The raw enum value for the given field. +//% **/ +//%int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field); +//% +//%/** +//% * Set the given enum field of a message. You can set the value to anything, +//% * even a value that is not a member of the enum. +//% * +//% * @param self The message into which to set the field. +//% * @param field The field to set. +//% * @param value The raw enum value to set in the field. +//% **/ +//%void GPBSetMessageRawEnumField(GPBMessage *self, +//% GPBFieldDescriptor *field, +//% int32_t value); +//% +//%// Repeated Fields +//% +//%/** +//% * Gets the value of a repeated field. +//% * +//% * @param self The message from which to get the field. +//% * @param field The repeated field to get. +//% * +//% * @return A GPB*Array or an NSMutableArray based on the field's type. +//% **/ +//%id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field); +//% +//%/** +//% * Sets the value of a repeated field. +//% * +//% * @param self The message into which to set the field. +//% * @param field The field to set. +//% * @param array A GPB*Array or NSMutableArray based on the field's type. +//% **/ +//%void GPBSetMessageRepeatedField(GPBMessage *self, +//% GPBFieldDescriptor *field, +//% id array); +//% +//%// Map Fields +//% +//%/** +//% * Gets the value of a map<> field. +//% * +//% * @param self The message from which to get the field. +//% * @param field The repeated field to get. +//% * +//% * @return A GPB*Dictionary or NSMutableDictionary based on the field's type. +//% **/ +//%id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field); +//% +//%/** +//% * Sets the value of a map<> field. +//% * +//% * @param self The message into which to set the field. +//% * @param field The field to set. +//% * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the +//% * field's type. +//% **/ +//%void GPBSetMessageMapField(GPBMessage *self, +//% GPBFieldDescriptor *field, +//% id dictionary); +//% + +//%PDDM-DEFINE GPB_ACCESSOR_SINGLE(NAME, TYPE, AN) +//%GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, ) +//%PDDM-DEFINE GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, TisP) +//%/** +//% * Gets the value of a##AN NAME$L field. +//% * +//% * @param self The message from which to get the field. +//% * @param field The field to get. +//% **/ +//%TYPE TisP##GPBGetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field); +//% +//%/** +//% * Sets the value of a##AN NAME$L field. +//% * +//% * @param self The message into which to set the field. +//% * @param field The field to set. +//% * @param value The to set in the field. +//% **/ +//%void GPBSetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field, TYPE TisP##value); +//% diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUtilities.m b/My Mind/Pods/Protobuf/objectivec/GPBUtilities.m new file mode 100644 index 0000000..e2a12ca --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUtilities.m @@ -0,0 +1,2166 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBUtilities_PackagePrivate.h" + +#import + +#import "GPBArray_PackagePrivate.h" +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBDictionary_PackagePrivate.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBUnknownField.h" +#import "GPBUnknownFieldSet.h" + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +static void AppendTextFormatForMessage(GPBMessage *message, + NSMutableString *toStr, + NSString *lineIndent); + +// Are two datatypes the same basic type representation (ex Int32 and SInt32). +// Marked unused because currently only called from asserts/debug. +static BOOL DataTypesEquivalent(GPBDataType type1, + GPBDataType type2) __attribute__ ((unused)); + +// Basic type representation for a type (ex: for SInt32 it is Int32). +// Marked unused because currently only called from asserts/debug. +static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused)); + +// String name for a data type. +// Marked unused because currently only called from asserts/debug. +static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused)); + +NSData *GPBEmptyNSData(void) { + static dispatch_once_t onceToken; + static NSData *defaultNSData = nil; + dispatch_once(&onceToken, ^{ + defaultNSData = [[NSData alloc] init]; + }); + return defaultNSData; +} + +void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) { + if (!initialMessage) { + return; + } + + // Use an array as a list to process to avoid recursion. + NSMutableArray *todo = [NSMutableArray arrayWithObject:initialMessage]; + + while (todo.count) { + GPBMessage *msg = todo.lastObject; + [todo removeLastObject]; + + // Clear unknowns. + msg.unknownFields = nil; + + // Handle the message fields. + GPBDescriptor *descriptor = [[msg class] descriptor]; + for (GPBFieldDescriptor *field in descriptor->fields_) { + if (!GPBFieldDataTypeIsMessage(field)) { + continue; + } + switch (field.fieldType) { + case GPBFieldTypeSingle: + if (GPBGetHasIvarField(msg, field)) { + GPBMessage *fieldMessage = GPBGetObjectIvarWithFieldNoAutocreate(msg, field); + [todo addObject:fieldMessage]; + } + break; + + case GPBFieldTypeRepeated: { + NSArray *fieldMessages = GPBGetObjectIvarWithFieldNoAutocreate(msg, field); + if (fieldMessages.count) { + [todo addObjectsFromArray:fieldMessages]; + } + break; + } + + case GPBFieldTypeMap: { + id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field); + switch (field.mapKeyDataType) { + case GPBDataTypeBool: + [(GPBBoolObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + BOOL key, id _Nonnull object, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:object]; + }]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + [(GPBUInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + uint32_t key, id _Nonnull object, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:object]; + }]; + break; + case GPBDataTypeInt32: + case GPBDataTypeSFixed32: + case GPBDataTypeSInt32: + [(GPBInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + int32_t key, id _Nonnull object, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:object]; + }]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + [(GPBUInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + uint64_t key, id _Nonnull object, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:object]; + }]; + break; + case GPBDataTypeInt64: + case GPBDataTypeSFixed64: + case GPBDataTypeSInt64: + [(GPBInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + int64_t key, id _Nonnull object, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:object]; + }]; + break; + case GPBDataTypeString: + [(NSDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( + NSString * _Nonnull key, GPBMessage * _Nonnull obj, BOOL * _Nonnull stop) { + #pragma unused(key, stop) + [todo addObject:obj]; + }]; + break; + case GPBDataTypeFloat: + case GPBDataTypeDouble: + case GPBDataTypeEnum: + case GPBDataTypeBytes: + case GPBDataTypeGroup: + case GPBDataTypeMessage: + NSCAssert(NO, @"Aren't valid key types."); + } + break; + } // switch(field.mapKeyDataType) + } // switch(field.fieldType) + } // for(fields) + + // Handle any extensions holding messages. + for (GPBExtensionDescriptor *extension in [msg extensionsCurrentlySet]) { + if (!GPBDataTypeIsMessage(extension.dataType)) { + continue; + } + if (extension.isRepeated) { + NSArray *extMessages = [msg getExtension:extension]; + [todo addObjectsFromArray:extMessages]; + } else { + GPBMessage *extMessage = [msg getExtension:extension]; + [todo addObject:extMessage]; + } + } // for(extensionsCurrentlySet) + + } // while(todo.count) +} + + +// -- About Version Checks -- +// There's actually 3 places these checks all come into play: +// 1. When the generated source is compile into .o files, the header check +// happens. This is checking the protoc used matches the library being used +// when making the .o. +// 2. Every place a generated proto header is included in a developer's code, +// the header check comes into play again. But this time it is checking that +// the current library headers being used still support/match the ones for +// the generated code. +// 3. At runtime the final check here (GPBCheckRuntimeVersionsInternal), is +// called from the generated code passing in values captured when the +// generated code's .o was made. This checks that at runtime the generated +// code and runtime library match. + +void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) { + // NOTE: This is passing the value captured in the compiled code to check + // against the values captured when the runtime support was compiled. This + // ensures the library code isn't in a different framework/library that + // was generated with a non matching version. + if (GOOGLE_PROTOBUF_OBJC_VERSION < objcRuntimeVersion) { + // Library is too old for headers. + [NSException raise:NSInternalInconsistencyException + format:@"Linked to ProtocolBuffer runtime version %d," + @" but code compiled needing atleast %d!", + GOOGLE_PROTOBUF_OBJC_VERSION, objcRuntimeVersion]; + } + if (objcRuntimeVersion < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) { + // Headers are too old for library. + [NSException raise:NSInternalInconsistencyException + format:@"Proto generation source compiled against runtime" + @" version %d, but this version of the runtime only" + @" supports back to %d!", + objcRuntimeVersion, + GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION]; + } +} + +// This api is no longer used for version checks. 30001 is the last version +// using this old versioning model. When that support is removed, this function +// can be removed (along with the declaration in GPBUtilities_PackagePrivate.h). +void GPBCheckRuntimeVersionInternal(int32_t version) { + GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION == 30001, + time_to_remove_this_old_version_shim); + if (version != GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) { + [NSException raise:NSInternalInconsistencyException + format:@"Linked to ProtocolBuffer runtime version %d," + @" but code compiled with version %d!", + GOOGLE_PROTOBUF_OBJC_GEN_VERSION, version]; + } +} + +BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber) { + GPBDescriptor *descriptor = [self descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:fieldNumber]; + return GPBMessageHasFieldSet(self, field); +} + +BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field) { + if (self == nil || field == nil) return NO; + + // Repeated/Map don't use the bit, they check the count. + if (GPBFieldIsMapOrArray(field)) { + // Array/map type doesn't matter, since GPB*Array/NSArray and + // GPB*Dictionary/NSDictionary all support -count; + NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field); + return (arrayOrMap.count > 0); + } else { + return GPBGetHasIvarField(self, field); + } +} + +void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) { + // If not set, nothing to do. + if (!GPBGetHasIvarField(self, field)) { + return; + } + + if (GPBFieldStoresObject(field)) { + // Object types are handled slightly differently, they need to be released. + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + [*typePtr release]; + *typePtr = nil; + } else { + // POD types just need to clear the has bit as the Get* method will + // fetch the default when needed. + } + GPBSetHasIvarField(self, field, NO); +} + +BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) { + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); + if (idx < 0) { + NSCAssert(fieldNumber != 0, @"Invalid field number."); + BOOL hasIvar = (self->messageStorage_->_has_storage_[-idx] == fieldNumber); + return hasIvar; + } else { + NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); + uint32_t byteIndex = idx / 32; + uint32_t bitMask = (1U << (idx % 32)); + BOOL hasIvar = + (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO; + return hasIvar; + } +} + +uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) { + NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", + [self class], idx); + uint32_t result = self->messageStorage_->_has_storage_[-idx]; + return result; +} + +void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, + BOOL value) { + if (idx < 0) { + NSCAssert(fieldNumber != 0, @"Invalid field number."); + uint32_t *has_storage = self->messageStorage_->_has_storage_; + has_storage[-idx] = (value ? fieldNumber : 0); + } else { + NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); + uint32_t *has_storage = self->messageStorage_->_has_storage_; + uint32_t byte = idx / 32; + uint32_t bitMask = (1U << (idx % 32)); + if (value) { + has_storage[byte] |= bitMask; + } else { + has_storage[byte] &= ~bitMask; + } + } +} + +void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, + int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) { + uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex); + if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) { + // Do nothing/nothing set in the oneof. + return; + } + + // Like GPBClearMessageField(), free the memory if an objecttype is set, + // pod types don't need to do anything. + GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet]; + NSCAssert(fieldSet, + @"%@: oneof set to something (%u) not in the oneof?", + [self class], fieldNumberSet); + if (fieldSet && GPBFieldStoresObject(fieldSet)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[fieldSet->description_->offset]; + [*typePtr release]; + *typePtr = nil; + } + + // Set to nothing stored in the oneof. + // (field number doesn't matter since setting to nothing). + GPBSetHasIvar(self, oneofHasIndex, 1, NO); +} + +#pragma mark - IVar accessors + +//%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE) +//%TYPE GPBGetMessage##NAME##Field(GPBMessage *self, +//% TYPE$S NAME$S GPBFieldDescriptor *field) { +//%#if defined(DEBUG) && DEBUG +//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), +//% GPBDataType##NAME), +//% @"Attempting to get value of TYPE from field %@ " +//% @"of %@ which is of type %@.", +//% [self class], field.name, +//% TypeToString(GPBGetFieldDataType(field))); +//%#endif +//% if (GPBGetHasIvarField(self, field)) { +//% uint8_t *storage = (uint8_t *)self->messageStorage_; +//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset]; +//% return *typePtr; +//% } else { +//% return field.defaultValue.value##NAME; +//% } +//%} +//% +//%// Only exists for public api, no core code should use this. +//%void GPBSetMessage##NAME##Field(GPBMessage *self, +//% NAME$S GPBFieldDescriptor *field, +//% NAME$S TYPE value) { +//% if (self == nil || field == nil) return; +//% GPBFileSyntax syntax = [self descriptor].file.syntax; +//% GPBSet##NAME##IvarWithFieldInternal(self, field, value, syntax); +//%} +//% +//%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self, +//% NAME$S GPBFieldDescriptor *field, +//% NAME$S TYPE value, +//% NAME$S GPBFileSyntax syntax) { +//%#if defined(DEBUG) && DEBUG +//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), +//% GPBDataType##NAME), +//% @"Attempting to set field %@ of %@ which is of type %@ with " +//% @"value of type TYPE.", +//% [self class], field.name, +//% TypeToString(GPBGetFieldDataType(field))); +//%#endif +//% GPBOneofDescriptor *oneof = field->containingOneof_; +//% if (oneof) { +//% GPBMessageFieldDescription *fieldDesc = field->description_; +//% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); +//% } +//%#if defined(DEBUG) && DEBUG +//% NSCAssert(self->messageStorage_ != NULL, +//% @"%@: All messages should have storage (from init)", +//% [self class]); +//%#endif +//%#if defined(__clang_analyzer__) +//% if (self->messageStorage_ == NULL) return; +//%#endif +//% uint8_t *storage = (uint8_t *)self->messageStorage_; +//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset]; +//% *typePtr = value; +//% // proto2: any value counts as having been set; proto3, it +//% // has to be a non zero value or be in a oneof. +//% BOOL hasValue = ((syntax == GPBFileSyntaxProto2) +//% || (value != (TYPE)0) +//% || (field->containingOneof_ != NULL)); +//% GPBSetHasIvarField(self, field, hasValue); +//% GPBBecomeVisibleToAutocreator(self); +//%} +//% +//%PDDM-DEFINE IVAR_ALIAS_DEFN_OBJECT(NAME, TYPE) +//%// Only exists for public api, no core code should use this. +//%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self, +//% TYPE$S NAME$S GPBFieldDescriptor *field) { +//%#if defined(DEBUG) && DEBUG +//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), +//% GPBDataType##NAME), +//% @"Attempting to get value of TYPE from field %@ " +//% @"of %@ which is of type %@.", +//% [self class], field.name, +//% TypeToString(GPBGetFieldDataType(field))); +//%#endif +//% return (TYPE *)GPBGetObjectIvarWithField(self, field); +//%} +//% +//%// Only exists for public api, no core code should use this. +//%void GPBSetMessage##NAME##Field(GPBMessage *self, +//% NAME$S GPBFieldDescriptor *field, +//% NAME$S TYPE *value) { +//%#if defined(DEBUG) && DEBUG +//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), +//% GPBDataType##NAME), +//% @"Attempting to set field %@ of %@ which is of type %@ with " +//% @"value of type TYPE.", +//% [self class], field.name, +//% TypeToString(GPBGetFieldDataType(field))); +//%#endif +//% GPBSetObjectIvarWithField(self, field, (id)value); +//%} +//% + +// Object types are handled slightly differently, they need to be released +// and retained. + +void GPBSetAutocreatedRetainedObjectIvarWithField( + GPBMessage *self, GPBFieldDescriptor *field, + id __attribute__((ns_consumed)) value) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + NSCAssert(*typePtr == NULL, @"Can't set autocreated object more than once."); + *typePtr = value; +} + +void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field) { + if (GPBGetHasIvarField(self, field)) { + return; + } + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + GPBMessage *oldValue = *typePtr; + *typePtr = NULL; + GPBClearMessageAutocreator(oldValue); + [oldValue release]; +} + +// This exists only for briging some aliased types, nothing else should use it. +static void GPBSetObjectIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field, id value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain], + syntax); +} + +void GPBSetObjectIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, id value, + GPBFileSyntax syntax) { + GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain], + syntax); +} + +void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + id value, GPBFileSyntax syntax) { + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + GPBDataType fieldType = GPBGetFieldDataType(field); + BOOL isMapOrArray = GPBFieldIsMapOrArray(field); + BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType); +#if defined(DEBUG) && DEBUG + if (value == nil && !isMapOrArray && !fieldIsMessage && + field.hasDefaultValue) { + // Setting a message to nil is an obvious way to "clear" the value + // as there is no way to set a non-empty default value for messages. + // + // For Strings and Bytes that have default values set it is not clear what + // should be done when their value is set to nil. Is the intention just to + // clear the set value and reset to default, or is the intention to set the + // value to the empty string/data? Arguments can be made for both cases. + // 'nil' has been abused as a replacement for an empty string/data in ObjC. + // We decided to be consistent with all "object" types and clear the has + // field, and fall back on the default value. The warning below will only + // appear in debug, but the could should be changed so the intention is + // clear. + NSString *hasSel = NSStringFromSelector(field->hasOrCountSel_); + NSString *propName = field.name; + NSString *className = self.descriptor.name; + NSLog(@"warning: '%@.%@ = nil;' is not clearly defined for fields with " + @"default values. Please use '%@.%@ = %@' if you want to set it to " + @"empty, or call '%@.%@ = NO' to reset it to it's default value of " + @"'%@'. Defaulting to resetting default value.", + className, propName, className, propName, + (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", + className, hasSel, field.defaultValue.valueString); + // Note: valueString, depending on the type, it could easily be + // valueData/valueMessage. + } +#endif // DEBUG + if (!isMapOrArray) { + // Non repeated/map can be in an oneof, clear any existing value from the + // oneof. + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } + // Clear "has" if they are being set to nil. + BOOL setHasValue = (value != nil); + // Under proto3, Bytes & String fields get cleared by resetting them to + // their default (empty) values, so if they are set to something of length + // zero, they are being cleared. + if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage && + ([value length] == 0)) { + // Except, if the field was in a oneof, then it still gets recorded as + // having been set so the state of the oneof can be serialized back out. + if (!oneof) { + setHasValue = NO; + } + if (setHasValue) { + NSCAssert(value != nil, @"Should never be setting has for nil"); + } else { + // The value passed in was retained, it must be released since we + // aren't saving anything in the field. + [value release]; + value = nil; + } + } + GPBSetHasIvarField(self, field, setHasValue); + } + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + + id oldValue = *typePtr; + + *typePtr = value; + + if (oldValue) { + if (isMapOrArray) { + if (field.fieldType == GPBFieldTypeRepeated) { + // If the old array was autocreated by us, then clear it. + if (GPBDataTypeIsObject(fieldType)) { + if ([oldValue isKindOfClass:[GPBAutocreatedArray class]]) { + GPBAutocreatedArray *autoArray = oldValue; + if (autoArray->_autocreator == self) { + autoArray->_autocreator = nil; + } + } + } else { + // Type doesn't matter, it is a GPB*Array. + GPBInt32Array *gpbArray = oldValue; + if (gpbArray->_autocreator == self) { + gpbArray->_autocreator = nil; + } + } + } else { // GPBFieldTypeMap + // If the old map was autocreated by us, then clear it. + if ((field.mapKeyDataType == GPBDataTypeString) && + GPBDataTypeIsObject(fieldType)) { + if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) { + GPBAutocreatedDictionary *autoDict = oldValue; + if (autoDict->_autocreator == self) { + autoDict->_autocreator = nil; + } + } + } else { + // Type doesn't matter, it is a GPB*Dictionary. + GPBInt32Int32Dictionary *gpbDict = oldValue; + if (gpbDict->_autocreator == self) { + gpbDict->_autocreator = nil; + } + } + } + } else if (fieldIsMessage) { + // If the old message value was autocreated by us, then clear it. + GPBMessage *oldMessageValue = oldValue; + if (GPBWasMessageAutocreatedBy(oldMessageValue, self)) { + GPBClearMessageAutocreator(oldMessageValue); + } + } + [oldValue release]; + } + + GPBBecomeVisibleToAutocreator(self); +} + +id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, + GPBFieldDescriptor *field) { + if (self->messageStorage_ == nil) { + return nil; + } + uint8_t *storage = (uint8_t *)self->messageStorage_; + id *typePtr = (id *)&storage[field->description_->offset]; + return *typePtr; +} + +// Only exists for public api, no core code should use this. +int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) { + GPBFileSyntax syntax = [self descriptor].file.syntax; + return GPBGetEnumIvarWithFieldInternal(self, field, syntax); +} + +int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, + @"Attempting to get value of type Enum from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + int32_t result = GPBGetMessageInt32Field(self, field); + // If this is presevering unknown enums, make sure the value is valid before + // returning it. + if (GPBHasPreservingUnknownEnumSemantics(syntax) && + ![field isValidEnumValue:result]) { + result = kGPBUnrecognizedEnumeratorValue; + } + return result; +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, + int32_t value) { + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetEnumIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, int32_t value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type Enum.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + // Don't allow in unknown values. Proto3 can use the Raw method. + if (![field isValidEnumValue:value]) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@: Attempt to set an unknown enum value (%d)", + [self class], field.name, value]; + } + GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); +} + +// Only exists for public api, no core code should use this. +int32_t GPBGetMessageRawEnumField(GPBMessage *self, + GPBFieldDescriptor *field) { + int32_t result = GPBGetMessageInt32Field(self, field); + return result; +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, + int32_t value) { + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); +} + +BOOL GPBGetMessageBoolField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), + @"Attempting to get value of type bool from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + // Bools are stored in the has bits to avoid needing explicit space in the + // storage structure. + // (the field number passed to the HasIvar helper doesn't really matter + // since the offset is never negative) + GPBMessageFieldDescription *fieldDesc = field->description_; + return GPBGetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number); + } else { + return field.defaultValue.valueBool; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageBoolField(GPBMessage *self, + GPBFieldDescriptor *field, + BOOL value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetBoolIvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetBoolIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + BOOL value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type bool.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } + + // Bools are stored in the has bits to avoid needing explicit space in the + // storage structure. + // (the field number passed to the HasIvar helper doesn't really matter since + // the offset is never negative) + GPBSetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number, value); + + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (BOOL)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t) +// This block of code is generated, do not edit it directly. + +int32_t GPBGetMessageInt32Field(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeInt32), + @"Attempting to get value of int32_t from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + int32_t *typePtr = (int32_t *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueInt32; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageInt32Field(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeInt32), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type int32_t.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + int32_t *typePtr = (int32_t *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (int32_t)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t) +// This block of code is generated, do not edit it directly. + +uint32_t GPBGetMessageUInt32Field(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeUInt32), + @"Attempting to get value of uint32_t from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueUInt32; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageUInt32Field(GPBMessage *self, + GPBFieldDescriptor *field, + uint32_t value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetUInt32IvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + uint32_t value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeUInt32), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type uint32_t.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (uint32_t)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t) +// This block of code is generated, do not edit it directly. + +int64_t GPBGetMessageInt64Field(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeInt64), + @"Attempting to get value of int64_t from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + int64_t *typePtr = (int64_t *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueInt64; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageInt64Field(GPBMessage *self, + GPBFieldDescriptor *field, + int64_t value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetInt64IvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetInt64IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + int64_t value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeInt64), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type int64_t.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + int64_t *typePtr = (int64_t *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (int64_t)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t) +// This block of code is generated, do not edit it directly. + +uint64_t GPBGetMessageUInt64Field(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeUInt64), + @"Attempting to get value of uint64_t from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueUInt64; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageUInt64Field(GPBMessage *self, + GPBFieldDescriptor *field, + uint64_t value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetUInt64IvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + uint64_t value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeUInt64), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type uint64_t.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (uint64_t)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float) +// This block of code is generated, do not edit it directly. + +float GPBGetMessageFloatField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeFloat), + @"Attempting to get value of float from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + float *typePtr = (float *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueFloat; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageFloatField(GPBMessage *self, + GPBFieldDescriptor *field, + float value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetFloatIvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetFloatIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + float value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeFloat), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type float.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + float *typePtr = (float *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (float)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double) +// This block of code is generated, do not edit it directly. + +double GPBGetMessageDoubleField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeDouble), + @"Attempting to get value of double from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + if (GPBGetHasIvarField(self, field)) { + uint8_t *storage = (uint8_t *)self->messageStorage_; + double *typePtr = (double *)&storage[field->description_->offset]; + return *typePtr; + } else { + return field.defaultValue.valueDouble; + } +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageDoubleField(GPBMessage *self, + GPBFieldDescriptor *field, + double value) { + if (self == nil || field == nil) return; + GPBFileSyntax syntax = [self descriptor].file.syntax; + GPBSetDoubleIvarWithFieldInternal(self, field, value, syntax); +} + +void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + double value, + GPBFileSyntax syntax) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeDouble), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type double.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBOneofDescriptor *oneof = field->containingOneof_; + if (oneof) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); + } +#if defined(DEBUG) && DEBUG + NSCAssert(self->messageStorage_ != NULL, + @"%@: All messages should have storage (from init)", + [self class]); +#endif +#if defined(__clang_analyzer__) + if (self->messageStorage_ == NULL) return; +#endif + uint8_t *storage = (uint8_t *)self->messageStorage_; + double *typePtr = (double *)&storage[field->description_->offset]; + *typePtr = value; + // proto2: any value counts as having been set; proto3, it + // has to be a non zero value or be in a oneof. + BOOL hasValue = ((syntax == GPBFileSyntaxProto2) + || (value != (double)0) + || (field->containingOneof_ != NULL)); + GPBSetHasIvarField(self, field, hasValue); + GPBBecomeVisibleToAutocreator(self); +} + +//%PDDM-EXPAND-END (6 expansions) + +// Aliases are function calls that are virtually the same. + +//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(String, NSString) +// This block of code is generated, do not edit it directly. + +// Only exists for public api, no core code should use this. +NSString *GPBGetMessageStringField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeString), + @"Attempting to get value of NSString from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + return (NSString *)GPBGetObjectIvarWithField(self, field); +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageStringField(GPBMessage *self, + GPBFieldDescriptor *field, + NSString *value) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeString), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type NSString.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBSetObjectIvarWithField(self, field, (id)value); +} + +//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Bytes, NSData) +// This block of code is generated, do not edit it directly. + +// Only exists for public api, no core code should use this. +NSData *GPBGetMessageBytesField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeBytes), + @"Attempting to get value of NSData from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + return (NSData *)GPBGetObjectIvarWithField(self, field); +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageBytesField(GPBMessage *self, + GPBFieldDescriptor *field, + NSData *value) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeBytes), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type NSData.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBSetObjectIvarWithField(self, field, (id)value); +} + +//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage) +// This block of code is generated, do not edit it directly. + +// Only exists for public api, no core code should use this. +GPBMessage *GPBGetMessageMessageField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeMessage), + @"Attempting to get value of GPBMessage from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + return (GPBMessage *)GPBGetObjectIvarWithField(self, field); +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageMessageField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBMessage *value) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeMessage), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type GPBMessage.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBSetObjectIvarWithField(self, field, (id)value); +} + +//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage) +// This block of code is generated, do not edit it directly. + +// Only exists for public api, no core code should use this. +GPBMessage *GPBGetMessageGroupField(GPBMessage *self, + GPBFieldDescriptor *field) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeGroup), + @"Attempting to get value of GPBMessage from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + return (GPBMessage *)GPBGetObjectIvarWithField(self, field); +} + +// Only exists for public api, no core code should use this. +void GPBSetMessageGroupField(GPBMessage *self, + GPBFieldDescriptor *field, + GPBMessage *value) { +#if defined(DEBUG) && DEBUG + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), + GPBDataTypeGroup), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type GPBMessage.", + [self class], field.name, + TypeToString(GPBGetFieldDataType(field))); +#endif + GPBSetObjectIvarWithField(self, field, (id)value); +} + +//%PDDM-EXPAND-END (4 expansions) + +// GPBGetMessageRepeatedField is defined in GPBMessage.m + +// Only exists for public api, no core code should use this. +void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array) { +#if defined(DEBUG) && DEBUG + if (field.fieldType != GPBFieldTypeRepeated) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@ is not a repeated field.", + [self class], field.name]; + } + Class expectedClass = Nil; + switch (GPBGetFieldDataType(field)) { + case GPBDataTypeBool: + expectedClass = [GPBBoolArray class]; + break; + case GPBDataTypeSFixed32: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + expectedClass = [GPBInt32Array class]; + break; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + expectedClass = [GPBUInt32Array class]; + break; + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + expectedClass = [GPBInt64Array class]; + break; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + expectedClass = [GPBUInt64Array class]; + break; + case GPBDataTypeFloat: + expectedClass = [GPBFloatArray class]; + break; + case GPBDataTypeDouble: + expectedClass = [GPBDoubleArray class]; + break; + case GPBDataTypeBytes: + case GPBDataTypeString: + case GPBDataTypeMessage: + case GPBDataTypeGroup: + expectedClass = [NSMutableArray class]; + break; + case GPBDataTypeEnum: + expectedClass = [GPBEnumArray class]; + break; + } + if (array && ![array isKindOfClass:expectedClass]) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@: Expected %@ object, got %@.", + [self class], field.name, expectedClass, [array class]]; + } +#endif + GPBSetObjectIvarWithField(self, field, array); +} + +static GPBDataType BaseDataType(GPBDataType type) { + switch (type) { + case GPBDataTypeSFixed32: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + case GPBDataTypeEnum: + return GPBDataTypeInt32; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + return GPBDataTypeUInt32; + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + return GPBDataTypeInt64; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + return GPBDataTypeUInt64; + case GPBDataTypeMessage: + case GPBDataTypeGroup: + return GPBDataTypeMessage; + case GPBDataTypeBool: + case GPBDataTypeFloat: + case GPBDataTypeDouble: + case GPBDataTypeBytes: + case GPBDataTypeString: + return type; + } +} + +static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) { + return BaseDataType(type1) == BaseDataType(type2); +} + +static NSString *TypeToString(GPBDataType dataType) { + switch (dataType) { + case GPBDataTypeBool: + return @"Bool"; + case GPBDataTypeSFixed32: + case GPBDataTypeInt32: + case GPBDataTypeSInt32: + return @"Int32"; + case GPBDataTypeFixed32: + case GPBDataTypeUInt32: + return @"UInt32"; + case GPBDataTypeSFixed64: + case GPBDataTypeInt64: + case GPBDataTypeSInt64: + return @"Int64"; + case GPBDataTypeFixed64: + case GPBDataTypeUInt64: + return @"UInt64"; + case GPBDataTypeFloat: + return @"Float"; + case GPBDataTypeDouble: + return @"Double"; + case GPBDataTypeBytes: + case GPBDataTypeString: + case GPBDataTypeMessage: + case GPBDataTypeGroup: + return @"Object"; + case GPBDataTypeEnum: + return @"Enum"; + } +} + +// GPBGetMessageMapField is defined in GPBMessage.m + +// Only exists for public api, no core code should use this. +void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, + id dictionary) { +#if defined(DEBUG) && DEBUG + if (field.fieldType != GPBFieldTypeMap) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@ is not a map<> field.", + [self class], field.name]; + } + if (dictionary) { + GPBDataType keyDataType = field.mapKeyDataType; + GPBDataType valueDataType = GPBGetFieldDataType(field); + NSString *keyStr = TypeToString(keyDataType); + NSString *valueStr = TypeToString(valueDataType); + if (keyDataType == GPBDataTypeString) { + keyStr = @"String"; + } + Class expectedClass = Nil; + if ((keyDataType == GPBDataTypeString) && + GPBDataTypeIsObject(valueDataType)) { + expectedClass = [NSMutableDictionary class]; + } else { + NSString *className = + [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr]; + expectedClass = NSClassFromString(className); + NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass); + } + if (![dictionary isKindOfClass:expectedClass]) { + [NSException raise:NSInvalidArgumentException + format:@"%@.%@: Expected %@ object, got %@.", + [self class], field.name, expectedClass, + [dictionary class]]; + } + } +#endif + GPBSetObjectIvarWithField(self, field, dictionary); +} + +#pragma mark - Misc Dynamic Runtime Utils + +const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) { + Protocol *protocol = + objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol)); + NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol"); + struct objc_method_description description = + protocol_getMethodDescription(protocol, selector, NO, instanceSel); + NSCAssert(description.name != Nil && description.types != nil, + @"Missing method for selector %@", NSStringFromSelector(selector)); + return description.types; +} + +#pragma mark - Text Format Support + +static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) { + [destStr appendString:@"\""]; + NSUInteger len = [toPrint length]; + for (NSUInteger i = 0; i < len; ++i) { + unichar aChar = [toPrint characterAtIndex:i]; + switch (aChar) { + case '\n': [destStr appendString:@"\\n"]; break; + case '\r': [destStr appendString:@"\\r"]; break; + case '\t': [destStr appendString:@"\\t"]; break; + case '\"': [destStr appendString:@"\\\""]; break; + case '\'': [destStr appendString:@"\\\'"]; break; + case '\\': [destStr appendString:@"\\\\"]; break; + default: + // This differs slightly from the C++ code in that the C++ doesn't + // generate UTF8; it looks at the string in UTF8, but escapes every + // byte > 0x7E. + if (aChar < 0x20) { + [destStr appendFormat:@"\\%d%d%d", + (aChar / 64), ((aChar % 64) / 8), (aChar % 8)]; + } else { + [destStr appendFormat:@"%C", aChar]; + } + break; + } + } + [destStr appendString:@"\""]; +} + +static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) { + const char *src = (const char *)[buffer bytes]; + size_t srcLen = [buffer length]; + [destStr appendString:@"\""]; + for (const char *srcEnd = src + srcLen; src < srcEnd; src++) { + switch (*src) { + case '\n': [destStr appendString:@"\\n"]; break; + case '\r': [destStr appendString:@"\\r"]; break; + case '\t': [destStr appendString:@"\\t"]; break; + case '\"': [destStr appendString:@"\\\""]; break; + case '\'': [destStr appendString:@"\\\'"]; break; + case '\\': [destStr appendString:@"\\\\"]; break; + default: + if (isprint(*src)) { + [destStr appendFormat:@"%c", *src]; + } else { + // NOTE: doing hex means you have to worry about the letter after + // the hex being another hex char and forcing that to be escaped, so + // use octal to keep it simple. + [destStr appendFormat:@"\\%03o", (uint8_t)(*src)]; + } + break; + } + } + [destStr appendString:@"\""]; +} + +static void AppendTextFormatForMapMessageField( + id map, GPBFieldDescriptor *field, NSMutableString *toStr, + NSString *lineIndent, NSString *fieldName, NSString *lineEnding) { + GPBDataType keyDataType = field.mapKeyDataType; + GPBDataType valueDataType = GPBGetFieldDataType(field); + BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType); + + NSString *msgStartFirst = + [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding]; + NSString *msgStart = + [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName]; + NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent]; + + NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent]; + NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent, + (isMessageValue ? "" : ":")]; + + __block BOOL isFirst = YES; + + if ((keyDataType == GPBDataTypeString) && + GPBDataTypeIsObject(valueDataType)) { + // map is an NSDictionary. + NSDictionary *dict = map; + [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { + #pragma unused(stop) + [toStr appendString:(isFirst ? msgStartFirst : msgStart)]; + isFirst = NO; + + [toStr appendString:keyLine]; + AppendStringEscaped(key, toStr); + [toStr appendString:@"\n"]; + + [toStr appendString:valueLine]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wswitch-enum" + switch (valueDataType) { + case GPBDataTypeString: + AppendStringEscaped(value, toStr); + break; + + case GPBDataTypeBytes: + AppendBufferAsString(value, toStr); + break; + + case GPBDataTypeMessage: + [toStr appendString:@"{\n"]; + NSString *subIndent = [lineIndent stringByAppendingString:@" "]; + AppendTextFormatForMessage(value, toStr, subIndent); + [toStr appendFormat:@"%@ }", lineIndent]; + break; + + default: + NSCAssert(NO, @"Can't happen"); + break; + } +#pragma clang diagnostic pop + [toStr appendString:@"\n"]; + + [toStr appendString:msgEnd]; + }]; + } else { + // map is one of the GPB*Dictionary classes, type doesn't matter. + GPBInt32Int32Dictionary *dict = map; + [dict enumerateForTextFormat:^(id keyObj, id valueObj) { + [toStr appendString:(isFirst ? msgStartFirst : msgStart)]; + isFirst = NO; + + // Key always is a NSString. + if (keyDataType == GPBDataTypeString) { + [toStr appendString:keyLine]; + AppendStringEscaped(keyObj, toStr); + [toStr appendString:@"\n"]; + } else { + [toStr appendFormat:@"%@%@\n", keyLine, keyObj]; + } + + [toStr appendString:valueLine]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wswitch-enum" + switch (valueDataType) { + case GPBDataTypeString: + AppendStringEscaped(valueObj, toStr); + break; + + case GPBDataTypeBytes: + AppendBufferAsString(valueObj, toStr); + break; + + case GPBDataTypeMessage: + [toStr appendString:@"{\n"]; + NSString *subIndent = [lineIndent stringByAppendingString:@" "]; + AppendTextFormatForMessage(valueObj, toStr, subIndent); + [toStr appendFormat:@"%@ }", lineIndent]; + break; + + case GPBDataTypeEnum: { + int32_t enumValue = [valueObj intValue]; + NSString *valueStr = nil; + GPBEnumDescriptor *descriptor = field.enumDescriptor; + if (descriptor) { + valueStr = [descriptor textFormatNameForValue:enumValue]; + } + if (valueStr) { + [toStr appendString:valueStr]; + } else { + [toStr appendFormat:@"%d", enumValue]; + } + break; + } + + default: + NSCAssert(valueDataType != GPBDataTypeGroup, @"Can't happen"); + // Everything else is a NSString. + [toStr appendString:valueObj]; + break; + } +#pragma clang diagnostic pop + [toStr appendString:@"\n"]; + + [toStr appendString:msgEnd]; + }]; + } +} + +static void AppendTextFormatForMessageField(GPBMessage *message, + GPBFieldDescriptor *field, + NSMutableString *toStr, + NSString *lineIndent) { + id arrayOrMap; + NSUInteger count; + GPBFieldType fieldType = field.fieldType; + switch (fieldType) { + case GPBFieldTypeSingle: + arrayOrMap = nil; + count = (GPBGetHasIvarField(message, field) ? 1 : 0); + break; + + case GPBFieldTypeRepeated: + // Will be NSArray or GPB*Array, type doesn't matter, they both + // implement count. + arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field); + count = [(NSArray *)arrayOrMap count]; + break; + + case GPBFieldTypeMap: { + // Will be GPB*Dictionary or NSMutableDictionary, type doesn't matter, + // they both implement count. + arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field); + count = [(NSDictionary *)arrayOrMap count]; + break; + } + } + + if (count == 0) { + // Nothing to print, out of here. + return; + } + + NSString *lineEnding = @""; + + // If the name can't be reversed or support for extra info was turned off, + // this can return nil. + NSString *fieldName = [field textFormatName]; + if ([fieldName length] == 0) { + fieldName = [NSString stringWithFormat:@"%u", GPBFieldNumber(field)]; + // If there is only one entry, put the objc name as a comment, other wise + // add it before the repeated values. + if (count > 1) { + [toStr appendFormat:@"%@# %@\n", lineIndent, field.name]; + } else { + lineEnding = [NSString stringWithFormat:@" # %@", field.name]; + } + } + + if (fieldType == GPBFieldTypeMap) { + AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, + fieldName, lineEnding); + return; + } + + id array = arrayOrMap; + const BOOL isRepeated = (array != nil); + + GPBDataType fieldDataType = GPBGetFieldDataType(field); + BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType); + for (NSUInteger j = 0; j < count; ++j) { + // Start the line. + [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, + (isMessageField ? "" : ":")]; + + // The value. + switch (fieldDataType) { +#define FIELD_CASE(GPBDATATYPE, CTYPE, REAL_TYPE, ...) \ + case GPBDataType##GPBDATATYPE: { \ + CTYPE v = (isRepeated ? [(GPB##REAL_TYPE##Array *)array valueAtIndex:j] \ + : GPBGetMessage##REAL_TYPE##Field(message, field)); \ + [toStr appendFormat:__VA_ARGS__, v]; \ + break; \ + } + + FIELD_CASE(Int32, int32_t, Int32, @"%d") + FIELD_CASE(SInt32, int32_t, Int32, @"%d") + FIELD_CASE(SFixed32, int32_t, Int32, @"%d") + FIELD_CASE(UInt32, uint32_t, UInt32, @"%u") + FIELD_CASE(Fixed32, uint32_t, UInt32, @"%u") + FIELD_CASE(Int64, int64_t, Int64, @"%lld") + FIELD_CASE(SInt64, int64_t, Int64, @"%lld") + FIELD_CASE(SFixed64, int64_t, Int64, @"%lld") + FIELD_CASE(UInt64, uint64_t, UInt64, @"%llu") + FIELD_CASE(Fixed64, uint64_t, UInt64, @"%llu") + FIELD_CASE(Float, float, Float, @"%.*g", FLT_DIG) + FIELD_CASE(Double, double, Double, @"%.*lg", DBL_DIG) + +#undef FIELD_CASE + + case GPBDataTypeEnum: { + int32_t v = (isRepeated ? [(GPBEnumArray *)array rawValueAtIndex:j] + : GPBGetMessageInt32Field(message, field)); + NSString *valueStr = nil; + GPBEnumDescriptor *descriptor = field.enumDescriptor; + if (descriptor) { + valueStr = [descriptor textFormatNameForValue:v]; + } + if (valueStr) { + [toStr appendString:valueStr]; + } else { + [toStr appendFormat:@"%d", v]; + } + break; + } + + case GPBDataTypeBool: { + BOOL v = (isRepeated ? [(GPBBoolArray *)array valueAtIndex:j] + : GPBGetMessageBoolField(message, field)); + [toStr appendString:(v ? @"true" : @"false")]; + break; + } + + case GPBDataTypeString: { + NSString *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] + : GPBGetMessageStringField(message, field)); + AppendStringEscaped(v, toStr); + break; + } + + case GPBDataTypeBytes: { + NSData *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] + : GPBGetMessageBytesField(message, field)); + AppendBufferAsString(v, toStr); + break; + } + + case GPBDataTypeGroup: + case GPBDataTypeMessage: { + GPBMessage *v = + (isRepeated ? [(NSArray *)array objectAtIndex:j] + : GPBGetObjectIvarWithField(message, field)); + [toStr appendFormat:@"{%@\n", lineEnding]; + NSString *subIndent = [lineIndent stringByAppendingString:@" "]; + AppendTextFormatForMessage(v, toStr, subIndent); + [toStr appendFormat:@"%@}", lineIndent]; + lineEnding = @""; + break; + } + + } // switch(fieldDataType) + + // End the line. + [toStr appendFormat:@"%@\n", lineEnding]; + + } // for(count) +} + +static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, + NSArray *activeExtensions, + GPBExtensionRange range, + NSMutableString *toStr, + NSString *lineIndent) { + uint32_t start = range.start; + uint32_t end = range.end; + for (GPBExtensionDescriptor *extension in activeExtensions) { + uint32_t fieldNumber = extension.fieldNumber; + if (fieldNumber < start) { + // Not there yet. + continue; + } + if (fieldNumber > end) { + // Done. + break; + } + + id rawExtValue = [message getExtension:extension]; + BOOL isRepeated = extension.isRepeated; + + NSUInteger numValues = 1; + NSString *lineEnding = @""; + if (isRepeated) { + numValues = [(NSArray *)rawExtValue count]; + } + + NSString *singletonName = extension.singletonName; + if (numValues == 1) { + lineEnding = [NSString stringWithFormat:@" # [%@]", singletonName]; + } else { + [toStr appendFormat:@"%@# [%@]\n", lineIndent, singletonName]; + } + + GPBDataType extDataType = extension.dataType; + for (NSUInteger j = 0; j < numValues; ++j) { + id curValue = (isRepeated ? [rawExtValue objectAtIndex:j] : rawExtValue); + + // Start the line. + [toStr appendFormat:@"%@%u%s ", lineIndent, fieldNumber, + (GPBDataTypeIsMessage(extDataType) ? "" : ":")]; + + // The value. + switch (extDataType) { +#define FIELD_CASE(GPBDATATYPE, CTYPE, NUMSELECTOR, ...) \ + case GPBDataType##GPBDATATYPE: { \ + CTYPE v = [(NSNumber *)curValue NUMSELECTOR]; \ + [toStr appendFormat:__VA_ARGS__, v]; \ + break; \ + } + + FIELD_CASE(Int32, int32_t, intValue, @"%d") + FIELD_CASE(SInt32, int32_t, intValue, @"%d") + FIELD_CASE(SFixed32, int32_t, unsignedIntValue, @"%d") + FIELD_CASE(UInt32, uint32_t, unsignedIntValue, @"%u") + FIELD_CASE(Fixed32, uint32_t, unsignedIntValue, @"%u") + FIELD_CASE(Int64, int64_t, longLongValue, @"%lld") + FIELD_CASE(SInt64, int64_t, longLongValue, @"%lld") + FIELD_CASE(SFixed64, int64_t, longLongValue, @"%lld") + FIELD_CASE(UInt64, uint64_t, unsignedLongLongValue, @"%llu") + FIELD_CASE(Fixed64, uint64_t, unsignedLongLongValue, @"%llu") + FIELD_CASE(Float, float, floatValue, @"%.*g", FLT_DIG) + FIELD_CASE(Double, double, doubleValue, @"%.*lg", DBL_DIG) + // TODO: Add a comment with the enum name from enum descriptors + // (might not be real value, so leave it as a comment, ObjC compiler + // name mangles differently). Doesn't look like we actually generate + // an enum descriptor reference like we do for normal fields, so this + // will take a compiler change. + FIELD_CASE(Enum, int32_t, intValue, @"%d") + +#undef FIELD_CASE + + case GPBDataTypeBool: + [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" + : @"false")]; + break; + + case GPBDataTypeString: + AppendStringEscaped(curValue, toStr); + break; + + case GPBDataTypeBytes: + AppendBufferAsString((NSData *)curValue, toStr); + break; + + case GPBDataTypeGroup: + case GPBDataTypeMessage: { + [toStr appendFormat:@"{%@\n", lineEnding]; + NSString *subIndent = [lineIndent stringByAppendingString:@" "]; + AppendTextFormatForMessage(curValue, toStr, subIndent); + [toStr appendFormat:@"%@}", lineIndent]; + lineEnding = @""; + break; + } + + } // switch(extDataType) + + } // for(numValues) + + // End the line. + [toStr appendFormat:@"%@\n", lineEnding]; + + } // for..in(activeExtensions) +} + +static void AppendTextFormatForMessage(GPBMessage *message, + NSMutableString *toStr, + NSString *lineIndent) { + GPBDescriptor *descriptor = [message descriptor]; + NSArray *fieldsArray = descriptor->fields_; + NSUInteger fieldCount = fieldsArray.count; + const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; + NSUInteger extensionRangesCount = descriptor.extensionRangesCount; + NSArray *activeExtensions = [[message extensionsCurrentlySet] + sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; + for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { + if (i == fieldCount) { + AppendTextFormatForMessageExtensionRange( + message, activeExtensions, extensionRanges[j++], toStr, lineIndent); + } else if (j == extensionRangesCount || + GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { + AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, + lineIndent); + } else { + AppendTextFormatForMessageExtensionRange( + message, activeExtensions, extensionRanges[j++], toStr, lineIndent); + } + } + + NSString *unknownFieldsStr = + GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent); + if ([unknownFieldsStr length] > 0) { + [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent]; + [toStr appendString:unknownFieldsStr]; + } +} + +NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) { + if (message == nil) return @""; + if (lineIndent == nil) lineIndent = @""; + + NSMutableString *buildString = [NSMutableString string]; + AppendTextFormatForMessage(message, buildString, lineIndent); + return buildString; +} + +NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, + NSString *lineIndent) { + if (unknownSet == nil) return @""; + if (lineIndent == nil) lineIndent = @""; + + NSMutableString *result = [NSMutableString string]; + for (GPBUnknownField *field in [unknownSet sortedFields]) { + int32_t fieldNumber = [field number]; + +#define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \ + [field.PROPNAME \ + enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \ + _Pragma("unused(idx, stop)"); \ + [result \ + appendFormat:@"%@%d: " #FORMAT "\n", lineIndent, fieldNumber, value]; \ + }]; + + PRINT_LOOP(varintList, uint64_t, %llu); + PRINT_LOOP(fixed32List, uint32_t, 0x%X); + PRINT_LOOP(fixed64List, uint64_t, 0x%llX); + +#undef PRINT_LOOP + + // NOTE: C++ version of TextFormat tries to parse this as a message + // and print that if it succeeds. + for (NSData *data in field.lengthDelimitedList) { + [result appendFormat:@"%@%d: ", lineIndent, fieldNumber]; + AppendBufferAsString(data, result); + [result appendString:@"\n"]; + } + + for (GPBUnknownFieldSet *subUnknownSet in field.groupList) { + [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber]; + NSString *subIndent = [lineIndent stringByAppendingString:@" "]; + NSString *subUnknwonSetStr = + GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent); + [result appendString:subUnknwonSetStr]; + [result appendFormat:@"%@}\n", lineIndent]; + } + } + return result; +} + +// Helpers to decode a varint. Not using GPBCodedInputStream version because +// that needs a state object, and we don't want to create an input stream out +// of the data. +GPB_INLINE int8_t ReadRawByteFromData(const uint8_t **data) { + int8_t result = *((int8_t *)(*data)); + ++(*data); + return result; +} + +static int32_t ReadRawVarint32FromData(const uint8_t **data) { + int8_t tmp = ReadRawByteFromData(data); + if (tmp >= 0) { + return tmp; + } + int32_t result = tmp & 0x7f; + if ((tmp = ReadRawByteFromData(data)) >= 0) { + result |= tmp << 7; + } else { + result |= (tmp & 0x7f) << 7; + if ((tmp = ReadRawByteFromData(data)) >= 0) { + result |= tmp << 14; + } else { + result |= (tmp & 0x7f) << 14; + if ((tmp = ReadRawByteFromData(data)) >= 0) { + result |= tmp << 21; + } else { + result |= (tmp & 0x7f) << 21; + result |= (tmp = ReadRawByteFromData(data)) << 28; + if (tmp < 0) { + // Discard upper 32 bits. + for (int i = 0; i < 5; i++) { + if (ReadRawByteFromData(data) >= 0) { + return result; + } + } + [NSException raise:NSParseErrorException + format:@"Unable to read varint32"]; + } + } + } + } + return result; +} + +NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, + NSString *inputStr) { + // decodData form: + // varint32: num entries + // for each entry: + // varint32: key + // bytes*: decode data + // + // decode data one of two forms: + // 1: a \0 followed by the string followed by an \0 + // 2: bytecodes to transform an input into the right thing, ending with \0 + // + // the bytes codes are of the form: + // 0xabbccccc + // 0x0 (all zeros), end. + // a - if set, add an underscore + // bb - 00 ccccc bytes as is + // bb - 10 ccccc upper first, as is on rest, ccccc byte total + // bb - 01 ccccc lower first, as is on rest, ccccc byte total + // bb - 11 ccccc all upper, ccccc byte total + + if (!decodeData || !inputStr) { + return nil; + } + + // Find key + const uint8_t *scan = decodeData; + int32_t numEntries = ReadRawVarint32FromData(&scan); + BOOL foundKey = NO; + while (!foundKey && (numEntries > 0)) { + --numEntries; + int32_t dataKey = ReadRawVarint32FromData(&scan); + if (dataKey == key) { + foundKey = YES; + } else { + // If it is a inlined string, it will start with \0; if it is bytecode it + // will start with a code. So advance one (skipping the inline string + // marker), and then loop until reaching the end marker (\0). + ++scan; + while (*scan != 0) ++scan; + // Now move past the end marker. + ++scan; + } + } + + if (!foundKey) { + return nil; + } + + // Decode + + if (*scan == 0) { + // Inline string. Move over the marker, and NSString can take it as + // UTF8. + ++scan; + NSString *result = [NSString stringWithUTF8String:(const char *)scan]; + return result; + } + + NSMutableString *result = + [NSMutableString stringWithCapacity:[inputStr length]]; + + const uint8_t kAddUnderscore = 0b10000000; + const uint8_t kOpMask = 0b01100000; + // const uint8_t kOpAsIs = 0b00000000; + const uint8_t kOpFirstUpper = 0b01000000; + const uint8_t kOpFirstLower = 0b00100000; + const uint8_t kOpAllUpper = 0b01100000; + const uint8_t kSegmentLenMask = 0b00011111; + + NSInteger i = 0; + for (; *scan != 0; ++scan) { + if (*scan & kAddUnderscore) { + [result appendString:@"_"]; + } + int segmentLen = *scan & kSegmentLenMask; + uint8_t decodeOp = *scan & kOpMask; + + // Do op specific handling of the first character. + if (decodeOp == kOpFirstUpper) { + unichar c = [inputStr characterAtIndex:i]; + [result appendFormat:@"%c", toupper((char)c)]; + ++i; + --segmentLen; + } else if (decodeOp == kOpFirstLower) { + unichar c = [inputStr characterAtIndex:i]; + [result appendFormat:@"%c", tolower((char)c)]; + ++i; + --segmentLen; + } + // else op == kOpAsIs || op == kOpAllUpper + + // Now pull over the rest of the length for this segment. + for (int x = 0; x < segmentLen; ++x) { + unichar c = [inputStr characterAtIndex:(i + x)]; + if (decodeOp == kOpAllUpper) { + [result appendFormat:@"%c", toupper((char)c)]; + } else { + [result appendFormat:@"%C", c]; + } + } + i += segmentLen; + } + + return result; +} + +#pragma clang diagnostic pop + +BOOL GPBClassHasSel(Class aClass, SEL sel) { + // NOTE: We have to use class_copyMethodList, all other runtime method + // lookups actually also resolve the method implementation and this + // is called from within those methods. + + BOOL result = NO; + unsigned int methodCount = 0; + Method *methodList = class_copyMethodList(aClass, &methodCount); + for (unsigned int i = 0; i < methodCount; ++i) { + SEL methodSelector = method_getName(methodList[i]); + if (methodSelector == sel) { + result = YES; + break; + } + } + free(methodList); + return result; +} diff --git a/My Mind/Pods/Protobuf/objectivec/GPBUtilities_PackagePrivate.h b/My Mind/Pods/Protobuf/objectivec/GPBUtilities_PackagePrivate.h new file mode 100644 index 0000000..ed424ce --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBUtilities_PackagePrivate.h @@ -0,0 +1,351 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +#import "GPBUtilities.h" + +#import "GPBDescriptor_PackagePrivate.h" + +// Macros for stringifying library symbols. These are used in the generated +// PB descriptor classes wherever a library symbol name is represented as a +// string. See README.google for more information. +#define GPBStringify(S) #S +#define GPBStringifySymbol(S) GPBStringify(S) + +#define GPBNSStringify(S) @#S +#define GPBNSStringifySymbol(S) GPBNSStringify(S) + +// Constant to internally mark when there is no has bit. +#define GPBNoHasBit INT32_MAX + +CF_EXTERN_C_BEGIN + +// These two are used to inject a runtime check for version mismatch into the +// generated sources to make sure they are linked with a supporting runtime. +void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion); +GPB_INLINE void GPB_DEBUG_CHECK_RUNTIME_VERSIONS() { + // NOTE: By being inline here, this captures the value from the library's + // headers at the time the generated code was compiled. +#if defined(DEBUG) && DEBUG + GPBCheckRuntimeVersionSupport(GOOGLE_PROTOBUF_OBJC_VERSION); +#endif +} + +// Legacy version of the checks, remove when GOOGLE_PROTOBUF_OBJC_GEN_VERSION +// goes away (see more info in GPBBootstrap.h). +void GPBCheckRuntimeVersionInternal(int32_t version); +GPB_INLINE void GPBDebugCheckRuntimeVersion() { +#if defined(DEBUG) && DEBUG + GPBCheckRuntimeVersionInternal(GOOGLE_PROTOBUF_OBJC_GEN_VERSION); +#endif +} + +// Conversion functions for de/serializing floating point types. + +GPB_INLINE int64_t GPBConvertDoubleToInt64(double v) { + union { double f; int64_t i; } u; + u.f = v; + return u.i; +} + +GPB_INLINE int32_t GPBConvertFloatToInt32(float v) { + union { float f; int32_t i; } u; + u.f = v; + return u.i; +} + +GPB_INLINE double GPBConvertInt64ToDouble(int64_t v) { + union { double f; int64_t i; } u; + u.i = v; + return u.f; +} + +GPB_INLINE float GPBConvertInt32ToFloat(int32_t v) { + union { float f; int32_t i; } u; + u.i = v; + return u.f; +} + +GPB_INLINE int32_t GPBLogicalRightShift32(int32_t value, int32_t spaces) { + return (int32_t)((uint32_t)(value) >> spaces); +} + +GPB_INLINE int64_t GPBLogicalRightShift64(int64_t value, int32_t spaces) { + return (int64_t)((uint64_t)(value) >> spaces); +} + +// Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers +// into values that can be efficiently encoded with varint. (Otherwise, +// negative values must be sign-extended to 64 bits to be varint encoded, +// thus always taking 10 bytes on the wire.) +GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) { + return (int32_t)(GPBLogicalRightShift32((int32_t)n, 1) ^ -((int32_t)(n) & 1)); +} + +// Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers +// into values that can be efficiently encoded with varint. (Otherwise, +// negative values must be sign-extended to 64 bits to be varint encoded, +// thus always taking 10 bytes on the wire.) +GPB_INLINE int64_t GPBDecodeZigZag64(uint64_t n) { + return (int64_t)(GPBLogicalRightShift64((int64_t)n, 1) ^ -((int64_t)(n) & 1)); +} + +// Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers +// into values that can be efficiently encoded with varint. (Otherwise, +// negative values must be sign-extended to 64 bits to be varint encoded, +// thus always taking 10 bytes on the wire.) +GPB_INLINE uint32_t GPBEncodeZigZag32(int32_t n) { + // Note: the right-shift must be arithmetic + return ((uint32_t)n << 1) ^ (uint32_t)(n >> 31); +} + +// Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers +// into values that can be efficiently encoded with varint. (Otherwise, +// negative values must be sign-extended to 64 bits to be varint encoded, +// thus always taking 10 bytes on the wire.) +GPB_INLINE uint64_t GPBEncodeZigZag64(int64_t n) { + // Note: the right-shift must be arithmetic + return ((uint64_t)n << 1) ^ (uint64_t)(n >> 63); +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wswitch-enum" +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +GPB_INLINE BOOL GPBDataTypeIsObject(GPBDataType type) { + switch (type) { + case GPBDataTypeBytes: + case GPBDataTypeString: + case GPBDataTypeMessage: + case GPBDataTypeGroup: + return YES; + default: + return NO; + } +} + +GPB_INLINE BOOL GPBDataTypeIsMessage(GPBDataType type) { + switch (type) { + case GPBDataTypeMessage: + case GPBDataTypeGroup: + return YES; + default: + return NO; + } +} + +GPB_INLINE BOOL GPBFieldDataTypeIsMessage(GPBFieldDescriptor *field) { + return GPBDataTypeIsMessage(field->description_->dataType); +} + +GPB_INLINE BOOL GPBFieldDataTypeIsObject(GPBFieldDescriptor *field) { + return GPBDataTypeIsObject(field->description_->dataType); +} + +GPB_INLINE BOOL GPBExtensionIsMessage(GPBExtensionDescriptor *ext) { + return GPBDataTypeIsMessage(ext->description_->dataType); +} + +// The field is an array/map or it has an object value. +GPB_INLINE BOOL GPBFieldStoresObject(GPBFieldDescriptor *field) { + GPBMessageFieldDescription *desc = field->description_; + if ((desc->flags & (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0) { + return YES; + } + return GPBDataTypeIsObject(desc->dataType); +} + +BOOL GPBGetHasIvar(GPBMessage *self, int32_t index, uint32_t fieldNumber); +void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, + BOOL value); +uint32_t GPBGetHasOneof(GPBMessage *self, int32_t index); + +GPB_INLINE BOOL +GPBGetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field) { + GPBMessageFieldDescription *fieldDesc = field->description_; + return GPBGetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number); +} +GPB_INLINE void GPBSetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field, + BOOL value) { + GPBMessageFieldDescription *fieldDesc = field->description_; + GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, value); +} + +void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, + int32_t oneofHasIndex, uint32_t fieldNumberNotToClear); + +#pragma clang diagnostic pop + +//%PDDM-DEFINE GPB_IVAR_SET_DECL(NAME, TYPE) +//%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self, +//% NAME$S GPBFieldDescriptor *field, +//% NAME$S TYPE value, +//% NAME$S GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Bool, BOOL) +// This block of code is generated, do not edit it directly. + +void GPBSetBoolIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + BOOL value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Int32, int32_t) +// This block of code is generated, do not edit it directly. + +void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt32, uint32_t) +// This block of code is generated, do not edit it directly. + +void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + uint32_t value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Int64, int64_t) +// This block of code is generated, do not edit it directly. + +void GPBSetInt64IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + int64_t value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt64, uint64_t) +// This block of code is generated, do not edit it directly. + +void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + uint64_t value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Float, float) +// This block of code is generated, do not edit it directly. + +void GPBSetFloatIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + float value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Double, double) +// This block of code is generated, do not edit it directly. + +void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + double value, + GPBFileSyntax syntax); +//%PDDM-EXPAND GPB_IVAR_SET_DECL(Enum, int32_t) +// This block of code is generated, do not edit it directly. + +void GPBSetEnumIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + int32_t value, + GPBFileSyntax syntax); +//%PDDM-EXPAND-END (8 expansions) + +int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + GPBFileSyntax syntax); + +id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); + +void GPBSetObjectIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, id value, + GPBFileSyntax syntax); +void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self, + GPBFieldDescriptor *field, + id __attribute__((ns_consumed)) + value, + GPBFileSyntax syntax); + +// GPBGetObjectIvarWithField will automatically create the field (message) if +// it doesn't exist. GPBGetObjectIvarWithFieldNoAutocreate will return nil. +id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, + GPBFieldDescriptor *field); + +void GPBSetAutocreatedRetainedObjectIvarWithField( + GPBMessage *self, GPBFieldDescriptor *field, + id __attribute__((ns_consumed)) value); + +// Clears and releases the autocreated message ivar, if it's autocreated. If +// it's not set as autocreated, this method does nothing. +void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, + GPBFieldDescriptor *field); + +// Returns an Objective C encoding for |selector|. |instanceSel| should be +// YES if it's an instance selector (as opposed to a class selector). +// |selector| must be a selector from MessageSignatureProtocol. +const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel); + +// Helper for text format name encoding. +// decodeData is the data describing the sepecial decodes. +// key and inputString are the input that needs decoding. +NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, + NSString *inputString); + +// A series of selectors that are used solely to get @encoding values +// for them by the dynamic protobuf runtime code. See +// GPBMessageEncodingForSelector for details. GPBRootObject conforms to +// the protocol so that it is encoded in the Objective C runtime. +@protocol GPBMessageSignatureProtocol +@optional + +#define GPB_MESSAGE_SIGNATURE_ENTRY(TYPE, NAME) \ + -(TYPE)get##NAME; \ + -(void)set##NAME : (TYPE)value; \ + -(TYPE)get##NAME##AtIndex : (NSUInteger)index; + +GPB_MESSAGE_SIGNATURE_ENTRY(BOOL, Bool) +GPB_MESSAGE_SIGNATURE_ENTRY(uint32_t, Fixed32) +GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, SFixed32) +GPB_MESSAGE_SIGNATURE_ENTRY(float, Float) +GPB_MESSAGE_SIGNATURE_ENTRY(uint64_t, Fixed64) +GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, SFixed64) +GPB_MESSAGE_SIGNATURE_ENTRY(double, Double) +GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, Int32) +GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, Int64) +GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, SInt32) +GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, SInt64) +GPB_MESSAGE_SIGNATURE_ENTRY(uint32_t, UInt32) +GPB_MESSAGE_SIGNATURE_ENTRY(uint64_t, UInt64) +GPB_MESSAGE_SIGNATURE_ENTRY(NSData *, Bytes) +GPB_MESSAGE_SIGNATURE_ENTRY(NSString *, String) +GPB_MESSAGE_SIGNATURE_ENTRY(GPBMessage *, Message) +GPB_MESSAGE_SIGNATURE_ENTRY(GPBMessage *, Group) +GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, Enum) + +#undef GPB_MESSAGE_SIGNATURE_ENTRY + +- (id)getArray; +- (NSUInteger)getArrayCount; +- (void)setArray:(NSArray *)array; ++ (id)getClassValue; +@end + +BOOL GPBClassHasSel(Class aClass, SEL sel); + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.h b/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.h new file mode 100644 index 0000000..04df417 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.h @@ -0,0 +1,245 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "google/protobuf/Any.pbobjc.h" + #import "google/protobuf/Duration.pbobjc.h" + #import "google/protobuf/Timestamp.pbobjc.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Errors + +/** NSError domain used for errors. */ +extern NSString *const GPBWellKnownTypesErrorDomain; + +/** Error code for NSError with GPBWellKnownTypesErrorDomain. */ +typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { + /** The type_url could not be computed for the requested GPBMessage class. */ + GPBWellKnownTypesErrorCodeFailedToComputeTypeURL = -100, + /** type_url in a Any doesn’t match that of the requested GPBMessage class. */ + GPBWellKnownTypesErrorCodeTypeURLMismatch = -101, +}; + +#pragma mark - GPBTimestamp + +/** + * Category for GPBTimestamp to work with standard Foundation time/date types. + **/ +@interface GPBTimestamp (GBPWellKnownTypes) + +/** The NSDate representation of this GPBTimestamp. */ +@property(nonatomic, readwrite, strong) NSDate *date; + +/** + * The NSTimeInterval representation of this GPBTimestamp. + * + * @note: Not all second/nanos combinations can be represented in a + * NSTimeInterval, so getting this could be a lossy transform. + **/ +@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970; + +/** + * Initializes a GPBTimestamp with the given NSDate. + * + * @param date The date to configure the GPBTimestamp with. + * + * @return A newly initialized GPBTimestamp. + **/ +- (instancetype)initWithDate:(NSDate *)date; + +/** + * Initializes a GPBTimestamp with the given NSTimeInterval. + * + * @param timeIntervalSince1970 Time interval to configure the GPBTimestamp with. + * + * @return A newly initialized GPBTimestamp. + **/ +- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970; + +@end + +#pragma mark - GPBDuration + +/** + * Category for GPBDuration to work with standard Foundation time type. + **/ +@interface GPBDuration (GBPWellKnownTypes) + +/** + * The NSTimeInterval representation of this GPBDuration. + * + * @note: Not all second/nanos combinations can be represented in a + * NSTimeInterval, so getting this could be a lossy transform. + **/ +@property(nonatomic, readwrite) NSTimeInterval timeInterval; + +/** + * Initializes a GPBDuration with the given NSTimeInterval. + * + * @param timeInterval Time interval to configure the GPBDuration with. + * + * @return A newly initialized GPBDuration. + **/ +- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval; + +// These next two methods are deprecated because GBPDuration has no need of a +// "base" time. The older methods were about symmetry with GBPTimestamp, but +// the unix epoch usage is too confusing. + +/** Deprecated, use timeInterval instead. */ +@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970 + __attribute__((deprecated("Use timeInterval"))); +/** Deprecated, use initWithTimeInterval: instead. */ +- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 + __attribute__((deprecated("Use initWithTimeInterval:"))); + +@end + +#pragma mark - GPBAny + +/** + * Category for GPBAny to help work with the message within the object. + **/ +@interface GPBAny (GBPWellKnownTypes) + +/** + * Convenience method to create a GPBAny containing the serialized message. + * This uses type.googleapis.com/ as the type_url's prefix. + * + * @param message The message to be packed into the GPBAny. + * @param errorPtr Pointer to an error that will be populated if something goes + * wrong. + * + * @return A newly configured GPBAny with the given message, or nil on failure. + */ ++ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message + error:(NSError **)errorPtr; + +/** + * Convenience method to create a GPBAny containing the serialized message. + * + * @param message The message to be packed into the GPBAny. + * @param typeURLPrefix The URL prefix to apply for type_url. + * @param errorPtr Pointer to an error that will be populated if something + * goes wrong. + * + * @return A newly configured GPBAny with the given message, or nil on failure. + */ ++ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message + typeURLPrefix:(nonnull NSString *)typeURLPrefix + error:(NSError **)errorPtr; + +/** + * Initializes a GPBAny to contain the serialized message. This uses + * type.googleapis.com/ as the type_url's prefix. + * + * @param message The message to be packed into the GPBAny. + * @param errorPtr Pointer to an error that will be populated if something goes + * wrong. + * + * @return A newly configured GPBAny with the given message, or nil on failure. + */ +- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message + error:(NSError **)errorPtr; + +/** + * Initializes a GPBAny to contain the serialized message. + * + * @param message The message to be packed into the GPBAny. + * @param typeURLPrefix The URL prefix to apply for type_url. + * @param errorPtr Pointer to an error that will be populated if something + * goes wrong. + * + * @return A newly configured GPBAny with the given message, or nil on failure. + */ +- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message + typeURLPrefix:(nonnull NSString *)typeURLPrefix + error:(NSError **)errorPtr; + +/** + * Packs the serialized message into this GPBAny. This uses + * type.googleapis.com/ as the type_url's prefix. + * + * @param message The message to be packed into the GPBAny. + * @param errorPtr Pointer to an error that will be populated if something goes + * wrong. + * + * @return Whether the packing was successful or not. + */ +- (BOOL)packWithMessage:(nonnull GPBMessage *)message + error:(NSError **)errorPtr; + +/** + * Packs the serialized message into this GPBAny. + * + * @param message The message to be packed into the GPBAny. + * @param typeURLPrefix The URL prefix to apply for type_url. + * @param errorPtr Pointer to an error that will be populated if something + * goes wrong. + * + * @return Whether the packing was successful or not. + */ +- (BOOL)packWithMessage:(nonnull GPBMessage *)message + typeURLPrefix:(nonnull NSString *)typeURLPrefix + error:(NSError **)errorPtr; + +/** + * Unpacks the serialized message as if it was an instance of the given class. + * + * @note When checking type_url, the base URL is not checked, only the fully + * qualified name. + * + * @param messageClass The class to use to deserialize the contained message. + * @param errorPtr Pointer to an error that will be populated if something + * goes wrong. + * + * @return An instance of the given class populated with the contained data, or + * nil on failure. + */ +- (nullable GPBMessage *)unpackMessageClass:(Class)messageClass + error:(NSError **)errorPtr; + +@end + +NS_ASSUME_NONNULL_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.m b/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.m new file mode 100644 index 0000000..2808afe --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBWellKnownTypes.m @@ -0,0 +1,272 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +// Importing sources here to force the linker to include our category methods in +// the static library. If these were compiled separately, the category methods +// below would be stripped by the linker. + +#import "GPBWellKnownTypes.h" + +#import "GPBUtilities_PackagePrivate.h" + +NSString *const GPBWellKnownTypesErrorDomain = + GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain); + +static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/"; + +static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds, + int32_t nanos) { + return seconds + (NSTimeInterval)nanos / 1e9; +} + +static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time, + int64_t *outSeconds, + BOOL nanosMustBePositive) { + NSTimeInterval seconds; + NSTimeInterval nanos = modf(time, &seconds); + + if (nanosMustBePositive && (nanos < 0)) { + // Per Timestamp.proto, nanos is non-negative and "Negative second values with + // fractions must still have non-negative nanos values that count forward in + // time. Must be from 0 to 999,999,999 inclusive." + --seconds; + nanos = 1.0 + nanos; + } + + nanos *= 1e9; + *outSeconds = (int64_t)seconds; + return (int32_t)nanos; +} + +static NSString *BuildTypeURL(NSString *typeURLPrefix, NSString *fullName) { + if (typeURLPrefix.length == 0) { + return fullName; + } + + if ([typeURLPrefix hasSuffix:@"/"]) { + return [typeURLPrefix stringByAppendingString:fullName]; + } + + return [NSString stringWithFormat:@"%@/%@", typeURLPrefix, fullName]; +} + +static NSString *ParseTypeFromURL(NSString *typeURLString) { + NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch]; + if ((range.location == NSNotFound) || + (NSMaxRange(range) == typeURLString.length)) { + return nil; + } + NSString *result = [typeURLString substringFromIndex:range.location + 1]; + return result; +} + +#pragma mark - GPBTimestamp + +@implementation GPBTimestamp (GBPWellKnownTypes) + +- (instancetype)initWithDate:(NSDate *)date { + return [self initWithTimeIntervalSince1970:date.timeIntervalSince1970]; +} + +- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { + if ((self = [super init])) { + int64_t seconds; + int32_t nanos = SecondsAndNanosFromTimeInterval( + timeIntervalSince1970, &seconds, YES); + self.seconds = seconds; + self.nanos = nanos; + } + return self; +} + +- (NSDate *)date { + return [NSDate dateWithTimeIntervalSince1970:self.timeIntervalSince1970]; +} + +- (void)setDate:(NSDate *)date { + self.timeIntervalSince1970 = date.timeIntervalSince1970; +} + +- (NSTimeInterval)timeIntervalSince1970 { + return TimeIntervalFromSecondsAndNanos(self.seconds, self.nanos); +} + +- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { + int64_t seconds; + int32_t nanos = + SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES); + self.seconds = seconds; + self.nanos = nanos; +} + +@end + +#pragma mark - GPBDuration + +@implementation GPBDuration (GBPWellKnownTypes) + +- (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval { + if ((self = [super init])) { + int64_t seconds; + int32_t nanos = SecondsAndNanosFromTimeInterval( + timeInterval, &seconds, NO); + self.seconds = seconds; + self.nanos = nanos; + } + return self; +} + +- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { + return [self initWithTimeInterval:timeIntervalSince1970]; +} + +- (NSTimeInterval)timeInterval { + return TimeIntervalFromSecondsAndNanos(self.seconds, self.nanos); +} + +- (void)setTimeInterval:(NSTimeInterval)timeInterval { + int64_t seconds; + int32_t nanos = + SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO); + self.seconds = seconds; + self.nanos = nanos; +} + +- (NSTimeInterval)timeIntervalSince1970 { + return self.timeInterval; +} + +- (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { + self.timeInterval = timeIntervalSince1970; +} + +@end + +#pragma mark - GPBAny + +@implementation GPBAny (GBPWellKnownTypes) + ++ (instancetype)anyWithMessage:(GPBMessage *)message + error:(NSError **)errorPtr { + return [self anyWithMessage:message + typeURLPrefix:kTypePrefixGoogleApisCom + error:errorPtr]; +} + ++ (instancetype)anyWithMessage:(GPBMessage *)message + typeURLPrefix:(NSString *)typeURLPrefix + error:(NSError **)errorPtr { + return [[[self alloc] initWithMessage:message + typeURLPrefix:typeURLPrefix + error:errorPtr] autorelease]; +} + +- (instancetype)initWithMessage:(GPBMessage *)message + error:(NSError **)errorPtr { + return [self initWithMessage:message + typeURLPrefix:kTypePrefixGoogleApisCom + error:errorPtr]; +} + +- (instancetype)initWithMessage:(GPBMessage *)message + typeURLPrefix:(NSString *)typeURLPrefix + error:(NSError **)errorPtr { + self = [self init]; + if (self) { + if (![self packWithMessage:message + typeURLPrefix:typeURLPrefix + error:errorPtr]) { + [self release]; + self = nil; + } + } + return self; +} + +- (BOOL)packWithMessage:(GPBMessage *)message + error:(NSError **)errorPtr { + return [self packWithMessage:message + typeURLPrefix:kTypePrefixGoogleApisCom + error:errorPtr]; +} + +- (BOOL)packWithMessage:(GPBMessage *)message + typeURLPrefix:(NSString *)typeURLPrefix + error:(NSError **)errorPtr { + NSString *fullName = [message descriptor].fullName; + if (fullName.length == 0) { + if (errorPtr) { + *errorPtr = + [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL + userInfo:nil]; + } + return NO; + } + if (errorPtr) { + *errorPtr = nil; + } + self.typeURL = BuildTypeURL(typeURLPrefix, fullName); + self.value = message.data; + return YES; +} + +- (GPBMessage *)unpackMessageClass:(Class)messageClass + error:(NSError **)errorPtr { + NSString *fullName = [messageClass descriptor].fullName; + if (fullName.length == 0) { + if (errorPtr) { + *errorPtr = + [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL + userInfo:nil]; + } + return nil; + } + + NSString *expectedFullName = ParseTypeFromURL(self.typeURL); + if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) { + if (errorPtr) { + *errorPtr = + [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeTypeURLMismatch + userInfo:nil]; + } + return nil; + } + + // Any is proto3, which means no extensions, so this assumes anything put + // within an any also won't need extensions. A second helper could be added + // if needed. + return [messageClass parseFromData:self.value + error:errorPtr]; +} + +@end diff --git a/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.h b/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.h new file mode 100644 index 0000000..c5941a3 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.h @@ -0,0 +1,73 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBRuntimeTypes.h" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +typedef enum { + GPBWireFormatVarint = 0, + GPBWireFormatFixed64 = 1, + GPBWireFormatLengthDelimited = 2, + GPBWireFormatStartGroup = 3, + GPBWireFormatEndGroup = 4, + GPBWireFormatFixed32 = 5, +} GPBWireFormat; + +enum { + GPBWireFormatMessageSetItem = 1, + GPBWireFormatMessageSetTypeId = 2, + GPBWireFormatMessageSetMessage = 3 +}; + +uint32_t GPBWireFormatMakeTag(uint32_t fieldNumber, GPBWireFormat wireType) + __attribute__((const)); +GPBWireFormat GPBWireFormatGetTagWireType(uint32_t tag) __attribute__((const)); +uint32_t GPBWireFormatGetTagFieldNumber(uint32_t tag) __attribute__((const)); +BOOL GPBWireFormatIsValidTag(uint32_t tag) __attribute__((const)); + +GPBWireFormat GPBWireFormatForType(GPBDataType dataType, BOOL isPacked) + __attribute__((const)); + +#define GPBWireFormatMessageSetItemTag \ + (GPBWireFormatMakeTag(GPBWireFormatMessageSetItem, GPBWireFormatStartGroup)) +#define GPBWireFormatMessageSetItemEndTag \ + (GPBWireFormatMakeTag(GPBWireFormatMessageSetItem, GPBWireFormatEndGroup)) +#define GPBWireFormatMessageSetTypeIdTag \ + (GPBWireFormatMakeTag(GPBWireFormatMessageSetTypeId, GPBWireFormatVarint)) +#define GPBWireFormatMessageSetMessageTag \ + (GPBWireFormatMakeTag(GPBWireFormatMessageSetMessage, \ + GPBWireFormatLengthDelimited)) + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END diff --git a/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.m b/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.m new file mode 100644 index 0000000..860a339 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/GPBWireFormat.m @@ -0,0 +1,85 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. 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 +// OWNER 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. + +#import "GPBWireFormat.h" + +#import "GPBUtilities_PackagePrivate.h" + +enum { + GPBWireFormatTagTypeBits = 3, + GPBWireFormatTagTypeMask = 7 /* = (1 << GPBWireFormatTagTypeBits) - 1 */, +}; + +uint32_t GPBWireFormatMakeTag(uint32_t fieldNumber, GPBWireFormat wireType) { + return (fieldNumber << GPBWireFormatTagTypeBits) | wireType; +} + +GPBWireFormat GPBWireFormatGetTagWireType(uint32_t tag) { + return (GPBWireFormat)(tag & GPBWireFormatTagTypeMask); +} + +uint32_t GPBWireFormatGetTagFieldNumber(uint32_t tag) { + return GPBLogicalRightShift32(tag, GPBWireFormatTagTypeBits); +} + +BOOL GPBWireFormatIsValidTag(uint32_t tag) { + uint32_t formatBits = (tag & GPBWireFormatTagTypeMask); + // The valid GPBWireFormat* values are 0-5, anything else is not a valid tag. + BOOL result = (formatBits <= 5); + return result; +} + +GPBWireFormat GPBWireFormatForType(GPBDataType type, BOOL isPacked) { + if (isPacked) { + return GPBWireFormatLengthDelimited; + } + + static const GPBWireFormat format[GPBDataType_Count] = { + GPBWireFormatVarint, // GPBDataTypeBool + GPBWireFormatFixed32, // GPBDataTypeFixed32 + GPBWireFormatFixed32, // GPBDataTypeSFixed32 + GPBWireFormatFixed32, // GPBDataTypeFloat + GPBWireFormatFixed64, // GPBDataTypeFixed64 + GPBWireFormatFixed64, // GPBDataTypeSFixed64 + GPBWireFormatFixed64, // GPBDataTypeDouble + GPBWireFormatVarint, // GPBDataTypeInt32 + GPBWireFormatVarint, // GPBDataTypeInt64 + GPBWireFormatVarint, // GPBDataTypeSInt32 + GPBWireFormatVarint, // GPBDataTypeSInt64 + GPBWireFormatVarint, // GPBDataTypeUInt32 + GPBWireFormatVarint, // GPBDataTypeUInt64 + GPBWireFormatLengthDelimited, // GPBDataTypeBytes + GPBWireFormatLengthDelimited, // GPBDataTypeString + GPBWireFormatLengthDelimited, // GPBDataTypeMessage + GPBWireFormatStartGroup, // GPBDataTypeGroup + GPBWireFormatVarint // GPBDataTypeEnum + }; + return format[type]; +} diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.h new file mode 100644 index 0000000..ad26189 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.h @@ -0,0 +1,182 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/any.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBAnyRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBAnyRoot : GPBRootObject +@end + +#pragma mark - GPBAny + +typedef GPB_ENUM(GPBAny_FieldNumber) { + GPBAny_FieldNumber_TypeURL = 1, + GPBAny_FieldNumber_Value = 2, +}; + +/** + * `Any` contains an arbitrary serialized protocol buffer message along with a + * URL that describes the type of the serialized message. + * + * Protobuf library provides support to pack/unpack Any values in the form + * of utility functions or additional generated methods of the Any type. + * + * Example 1: Pack and unpack a message in C++. + * + * Foo foo = ...; + * Any any; + * any.PackFrom(foo); + * ... + * if (any.UnpackTo(&foo)) { + * ... + * } + * + * Example 2: Pack and unpack a message in Java. + * + * Foo foo = ...; + * Any any = Any.pack(foo); + * ... + * if (any.is(Foo.class)) { + * foo = any.unpack(Foo.class); + * } + * + * Example 3: Pack and unpack a message in Python. + * + * foo = Foo(...) + * any = Any() + * any.Pack(foo) + * ... + * if any.Is(Foo.DESCRIPTOR): + * any.Unpack(foo) + * ... + * + * Example 4: Pack and unpack a message in Go + * + * foo := &pb.Foo{...} + * any, err := ptypes.MarshalAny(foo) + * ... + * foo := &pb.Foo{} + * if err := ptypes.UnmarshalAny(any, foo); err != nil { + * ... + * } + * + * The pack methods provided by protobuf library will by default use + * 'type.googleapis.com/full.type.name' as the type URL and the unpack + * methods only use the fully qualified type name after the last '/' + * in the type URL, for example "foo.bar.com/x/y.z" will yield type + * name "y.z". + * + * + * JSON + * ==== + * The JSON representation of an `Any` value uses the regular + * representation of the deserialized, embedded message, with an + * additional field `\@type` which contains the type URL. Example: + * + * package google.profile; + * message Person { + * string first_name = 1; + * string last_name = 2; + * } + * + * { + * "\@type": "type.googleapis.com/google.profile.Person", + * "firstName": , + * "lastName": + * } + * + * If the embedded message type is well-known and has a custom JSON + * representation, that representation will be embedded adding a field + * `value` which holds the custom JSON in addition to the `\@type` + * field. Example (for message [google.protobuf.Duration][]): + * + * { + * "\@type": "type.googleapis.com/google.protobuf.Duration", + * "value": "1.212s" + * } + **/ +@interface GPBAny : GPBMessage + +/** + * A URL/resource name that uniquely identifies the type of the serialized + * protocol buffer message. The last segment of the URL's path must represent + * the fully qualified name of the type (as in + * `path/google.protobuf.Duration`). The name should be in a canonical form + * (e.g., leading "." is not accepted). + * + * In practice, teams usually precompile into the binary all types that they + * expect it to use in the context of Any. However, for URLs which use the + * scheme `http`, `https`, or no scheme, one can optionally set up a type + * server that maps type URLs to message definitions as follows: + * + * * If no scheme is provided, `https` is assumed. + * * An HTTP GET on the URL must yield a [google.protobuf.Type][] + * value in binary format, or produce an error. + * * Applications are allowed to cache lookup results based on the + * URL, or have them precompiled into a binary to avoid any + * lookup. Therefore, binary compatibility needs to be preserved + * on changes to types. (Use versioned type names to manage + * breaking changes.) + * + * Note: this functionality is not currently available in the official + * protobuf release, and it is not used for type URLs beginning with + * type.googleapis.com. + * + * Schemes other than `http`, `https` (or the empty scheme) might be + * used with implementation specific semantics. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL; + +/** Must be a valid serialized protocol buffer of the above specified type. */ +@property(nonatomic, readwrite, copy, null_resettable) NSData *value; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.m new file mode 100644 index 0000000..d210643 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.m @@ -0,0 +1,112 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/any.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Any.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBAnyRoot + +@implementation GPBAnyRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBAnyRoot_FileDescriptor + +static GPBFileDescriptor *GPBAnyRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBAny + +@implementation GPBAny + +@dynamic typeURL; +@dynamic value; + +typedef struct GPBAny__storage_ { + uint32_t _has_storage_[1]; + NSString *typeURL; + NSData *value; +} GPBAny__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "typeURL", + .dataTypeSpecific.className = NULL, + .number = GPBAny_FieldNumber_TypeURL, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBAny__storage_, typeURL), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeString, + }, + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBAny_FieldNumber_Value, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBAny__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBytes, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBAny class] + rootClass:[GPBAnyRoot class] + file:GPBAnyRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBAny__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\001\001\004\241!!\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.h new file mode 100644 index 0000000..c93f3f1 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.h @@ -0,0 +1,311 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/api.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +@class GPBMethod; +@class GPBMixin; +@class GPBOption; +@class GPBSourceContext; +GPB_ENUM_FWD_DECLARE(GPBSyntax); + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBApiRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBApiRoot : GPBRootObject +@end + +#pragma mark - GPBApi + +typedef GPB_ENUM(GPBApi_FieldNumber) { + GPBApi_FieldNumber_Name = 1, + GPBApi_FieldNumber_MethodsArray = 2, + GPBApi_FieldNumber_OptionsArray = 3, + GPBApi_FieldNumber_Version = 4, + GPBApi_FieldNumber_SourceContext = 5, + GPBApi_FieldNumber_MixinsArray = 6, + GPBApi_FieldNumber_Syntax = 7, +}; + +/** + * Api is a light-weight descriptor for an API Interface. + * + * Interfaces are also described as "protocol buffer services" in some contexts, + * such as by the "service" keyword in a .proto file, but they are different + * from API Services, which represent a concrete implementation of an interface + * as opposed to simply a description of methods and bindings. They are also + * sometimes simply referred to as "APIs" in other contexts, such as the name of + * this message itself. See https://cloud.google.com/apis/design/glossary for + * detailed terminology. + **/ +@interface GPBApi : GPBMessage + +/** + * The fully qualified name of this interface, including package name + * followed by the interface's simple name. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** The methods of this interface, in unspecified order. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *methodsArray; +/** The number of items in @c methodsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger methodsArray_Count; + +/** Any metadata attached to the interface. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +/** + * A version string for this interface. If specified, must have the form + * `major-version.minor-version`, as in `1.10`. If the minor version is + * omitted, it defaults to zero. If the entire version field is empty, the + * major version is derived from the package name, as outlined below. If the + * field is not empty, the version in the package name will be verified to be + * consistent with what is provided here. + * + * The versioning schema uses [semantic + * versioning](http://semver.org) where the major version number + * indicates a breaking change and the minor version an additive, + * non-breaking change. Both version numbers are signals to users + * what to expect from different versions, and should be carefully + * chosen based on the product plan. + * + * The major version is also reflected in the package name of the + * interface, which must end in `v`, as in + * `google.feature.v1`. For major versions 0 and 1, the suffix can + * be omitted. Zero major versions must only be used for + * experimental, non-GA interfaces. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *version; + +/** + * Source context for the protocol buffer service represented by this + * message. + **/ +@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; +/** Test to see if @c sourceContext has been set. */ +@property(nonatomic, readwrite) BOOL hasSourceContext; + +/** Included interfaces. See [Mixin][]. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *mixinsArray; +/** The number of items in @c mixinsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger mixinsArray_Count; + +/** The source syntax of the service. */ +@property(nonatomic, readwrite) enum GPBSyntax syntax; + +@end + +/** + * Fetches the raw value of a @c GPBApi's @c syntax property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBApi_Syntax_RawValue(GPBApi *message); +/** + * Sets the raw value of an @c GPBApi's @c syntax property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value); + +#pragma mark - GPBMethod + +typedef GPB_ENUM(GPBMethod_FieldNumber) { + GPBMethod_FieldNumber_Name = 1, + GPBMethod_FieldNumber_RequestTypeURL = 2, + GPBMethod_FieldNumber_RequestStreaming = 3, + GPBMethod_FieldNumber_ResponseTypeURL = 4, + GPBMethod_FieldNumber_ResponseStreaming = 5, + GPBMethod_FieldNumber_OptionsArray = 6, + GPBMethod_FieldNumber_Syntax = 7, +}; + +/** + * Method represents a method of an API interface. + **/ +@interface GPBMethod : GPBMessage + +/** The simple name of this method. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** A URL of the input message type. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *requestTypeURL; + +/** If true, the request is streamed. */ +@property(nonatomic, readwrite) BOOL requestStreaming; + +/** The URL of the output message type. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *responseTypeURL; + +/** If true, the response is streamed. */ +@property(nonatomic, readwrite) BOOL responseStreaming; + +/** Any metadata attached to the method. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +/** The source syntax of this method. */ +@property(nonatomic, readwrite) enum GPBSyntax syntax; + +@end + +/** + * Fetches the raw value of a @c GPBMethod's @c syntax property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBMethod_Syntax_RawValue(GPBMethod *message); +/** + * Sets the raw value of an @c GPBMethod's @c syntax property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value); + +#pragma mark - GPBMixin + +typedef GPB_ENUM(GPBMixin_FieldNumber) { + GPBMixin_FieldNumber_Name = 1, + GPBMixin_FieldNumber_Root = 2, +}; + +/** + * Declares an API Interface to be included in this interface. The including + * interface must redeclare all the methods from the included interface, but + * documentation and options are inherited as follows: + * + * - If after comment and whitespace stripping, the documentation + * string of the redeclared method is empty, it will be inherited + * from the original method. + * + * - Each annotation belonging to the service config (http, + * visibility) which is not set in the redeclared method will be + * inherited. + * + * - If an http annotation is inherited, the path pattern will be + * modified as follows. Any version prefix will be replaced by the + * version of the including interface plus the [root][] path if + * specified. + * + * Example of a simple mixin: + * + * package google.acl.v1; + * service AccessControl { + * // Get the underlying ACL object. + * rpc GetAcl(GetAclRequest) returns (Acl) { + * option (google.api.http).get = "/v1/{resource=**}:getAcl"; + * } + * } + * + * package google.storage.v2; + * service Storage { + * rpc GetAcl(GetAclRequest) returns (Acl); + * + * // Get a data record. + * rpc GetData(GetDataRequest) returns (Data) { + * option (google.api.http).get = "/v2/{resource=**}"; + * } + * } + * + * Example of a mixin configuration: + * + * apis: + * - name: google.storage.v2.Storage + * mixins: + * - name: google.acl.v1.AccessControl + * + * The mixin construct implies that all methods in `AccessControl` are + * also declared with same name and request/response types in + * `Storage`. A documentation generator or annotation processor will + * see the effective `Storage.GetAcl` method after inherting + * documentation and annotations as follows: + * + * service Storage { + * // Get the underlying ACL object. + * rpc GetAcl(GetAclRequest) returns (Acl) { + * option (google.api.http).get = "/v2/{resource=**}:getAcl"; + * } + * ... + * } + * + * Note how the version in the path pattern changed from `v1` to `v2`. + * + * If the `root` field in the mixin is specified, it should be a + * relative path under which inherited HTTP paths are placed. Example: + * + * apis: + * - name: google.storage.v2.Storage + * mixins: + * - name: google.acl.v1.AccessControl + * root: acls + * + * This implies the following inherited HTTP annotation: + * + * service Storage { + * // Get the underlying ACL object. + * rpc GetAcl(GetAclRequest) returns (Acl) { + * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; + * } + * ... + * } + **/ +@interface GPBMixin : GPBMessage + +/** The fully qualified name of the interface which is included. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** + * If non-empty specifies a path under which inherited HTTP paths + * are rooted. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *root; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.m new file mode 100644 index 0000000..58b4715 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.m @@ -0,0 +1,356 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/api.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "google/protobuf/Api.pbobjc.h" + #import "google/protobuf/SourceContext.pbobjc.h" + #import "google/protobuf/Type.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBApiRoot + +@implementation GPBApiRoot + +// No extensions in the file and none of the imports (direct or indirect) +// defined extensions, so no need to generate +extensionRegistry. + +@end + +#pragma mark - GPBApiRoot_FileDescriptor + +static GPBFileDescriptor *GPBApiRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBApi + +@implementation GPBApi + +@dynamic name; +@dynamic methodsArray, methodsArray_Count; +@dynamic optionsArray, optionsArray_Count; +@dynamic version; +@dynamic hasSourceContext, sourceContext; +@dynamic mixinsArray, mixinsArray_Count; +@dynamic syntax; + +typedef struct GPBApi__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSMutableArray *methodsArray; + NSMutableArray *optionsArray; + NSString *version; + GPBSourceContext *sourceContext; + NSMutableArray *mixinsArray; +} GPBApi__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBApi_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBApi__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "methodsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBMethod), + .number = GPBApi_FieldNumber_MethodsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBApi__storage_, methodsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBApi_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBApi__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "version", + .dataTypeSpecific.className = NULL, + .number = GPBApi_FieldNumber_Version, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBApi__storage_, version), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "sourceContext", + .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), + .number = GPBApi_FieldNumber_SourceContext, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBApi__storage_, sourceContext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "mixinsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBMixin), + .number = GPBApi_FieldNumber_MixinsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBApi__storage_, mixinsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBApi_FieldNumber_Syntax, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GPBApi__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBApi class] + rootClass:[GPBApiRoot class] + file:GPBApiRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBApi__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBApi_Syntax_RawValue(GPBApi *message) { + GPBDescriptor *descriptor = [GPBApi descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value) { + GPBDescriptor *descriptor = [GPBApi descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +#pragma mark - GPBMethod + +@implementation GPBMethod + +@dynamic name; +@dynamic requestTypeURL; +@dynamic requestStreaming; +@dynamic responseTypeURL; +@dynamic responseStreaming; +@dynamic optionsArray, optionsArray_Count; +@dynamic syntax; + +typedef struct GPBMethod__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSString *requestTypeURL; + NSString *responseTypeURL; + NSMutableArray *optionsArray; +} GPBMethod__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBMethod_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBMethod__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "requestTypeURL", + .dataTypeSpecific.className = NULL, + .number = GPBMethod_FieldNumber_RequestTypeURL, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBMethod__storage_, requestTypeURL), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeString, + }, + { + .name = "requestStreaming", + .dataTypeSpecific.className = NULL, + .number = GPBMethod_FieldNumber_RequestStreaming, + .hasIndex = 2, + .offset = 3, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "responseTypeURL", + .dataTypeSpecific.className = NULL, + .number = GPBMethod_FieldNumber_ResponseTypeURL, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GPBMethod__storage_, responseTypeURL), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeString, + }, + { + .name = "responseStreaming", + .dataTypeSpecific.className = NULL, + .number = GPBMethod_FieldNumber_ResponseStreaming, + .hasIndex = 5, + .offset = 6, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBMethod_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBMethod__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBMethod_FieldNumber_Syntax, + .hasIndex = 7, + .offset = (uint32_t)offsetof(GPBMethod__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBMethod class] + rootClass:[GPBApiRoot class] + file:GPBApiRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBMethod__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\002\002\007\244\241!!\000\004\010\244\241!!\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBMethod_Syntax_RawValue(GPBMethod *message) { + GPBDescriptor *descriptor = [GPBMethod descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value) { + GPBDescriptor *descriptor = [GPBMethod descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +#pragma mark - GPBMixin + +@implementation GPBMixin + +@dynamic name; +@dynamic root; + +typedef struct GPBMixin__storage_ { + uint32_t _has_storage_[1]; + NSString *name; + NSString *root; +} GPBMixin__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBMixin_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBMixin__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "root", + .dataTypeSpecific.className = NULL, + .number = GPBMixin_FieldNumber_Root, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBMixin__storage_, root), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBMixin class] + rootClass:[GPBApiRoot class] + file:GPBApiRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBMixin__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.h new file mode 100644 index 0000000..3e36759 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.h @@ -0,0 +1,145 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/duration.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBDurationRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBDurationRoot : GPBRootObject +@end + +#pragma mark - GPBDuration + +typedef GPB_ENUM(GPBDuration_FieldNumber) { + GPBDuration_FieldNumber_Seconds = 1, + GPBDuration_FieldNumber_Nanos = 2, +}; + +/** + * A Duration represents a signed, fixed-length span of time represented + * as a count of seconds and fractions of seconds at nanosecond + * resolution. It is independent of any calendar and concepts like "day" + * or "month". It is related to Timestamp in that the difference between + * two Timestamp values is a Duration and it can be added or subtracted + * from a Timestamp. Range is approximately +-10,000 years. + * + * # Examples + * + * Example 1: Compute Duration from two Timestamps in pseudo code. + * + * Timestamp start = ...; + * Timestamp end = ...; + * Duration duration = ...; + * + * duration.seconds = end.seconds - start.seconds; + * duration.nanos = end.nanos - start.nanos; + * + * if (duration.seconds < 0 && duration.nanos > 0) { + * duration.seconds += 1; + * duration.nanos -= 1000000000; + * } else if (durations.seconds > 0 && duration.nanos < 0) { + * duration.seconds -= 1; + * duration.nanos += 1000000000; + * } + * + * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. + * + * Timestamp start = ...; + * Duration duration = ...; + * Timestamp end = ...; + * + * end.seconds = start.seconds + duration.seconds; + * end.nanos = start.nanos + duration.nanos; + * + * if (end.nanos < 0) { + * end.seconds -= 1; + * end.nanos += 1000000000; + * } else if (end.nanos >= 1000000000) { + * end.seconds += 1; + * end.nanos -= 1000000000; + * } + * + * Example 3: Compute Duration from datetime.timedelta in Python. + * + * td = datetime.timedelta(days=3, minutes=10) + * duration = Duration() + * duration.FromTimedelta(td) + * + * # JSON Mapping + * + * In JSON format, the Duration type is encoded as a string rather than an + * object, where the string ends in the suffix "s" (indicating seconds) and + * is preceded by the number of seconds, with nanoseconds expressed as + * fractional seconds. For example, 3 seconds with 0 nanoseconds should be + * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should + * be expressed in JSON format as "3.000000001s", and 3 seconds and 1 + * microsecond should be expressed in JSON format as "3.000001s". + **/ +@interface GPBDuration : GPBMessage + +/** + * Signed seconds of the span of time. Must be from -315,576,000,000 + * to +315,576,000,000 inclusive. Note: these bounds are computed from: + * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + **/ +@property(nonatomic, readwrite) int64_t seconds; + +/** + * Signed fractions of a second at nanosecond resolution of the span + * of time. Durations less than one second are represented with a 0 + * `seconds` field and a positive or negative `nanos` field. For durations + * of one second or more, a non-zero value for the `nanos` field must be + * of the same sign as the `seconds` field. Must be from -999,999,999 + * to +999,999,999 inclusive. + **/ +@property(nonatomic, readwrite) int32_t nanos; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.m new file mode 100644 index 0000000..bafb64a --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.m @@ -0,0 +1,107 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/duration.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Duration.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBDurationRoot + +@implementation GPBDurationRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBDurationRoot_FileDescriptor + +static GPBFileDescriptor *GPBDurationRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBDuration + +@implementation GPBDuration + +@dynamic seconds; +@dynamic nanos; + +typedef struct GPBDuration__storage_ { + uint32_t _has_storage_[1]; + int32_t nanos; + int64_t seconds; +} GPBDuration__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "seconds", + .dataTypeSpecific.className = NULL, + .number = GPBDuration_FieldNumber_Seconds, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBDuration__storage_, seconds), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "nanos", + .dataTypeSpecific.className = NULL, + .number = GPBDuration_FieldNumber_Nanos, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBDuration__storage_, nanos), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBDuration class] + rootClass:[GPBDurationRoot class] + file:GPBDurationRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBDuration__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.h new file mode 100644 index 0000000..fdc247a --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.h @@ -0,0 +1,74 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/empty.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBEmptyRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBEmptyRoot : GPBRootObject +@end + +#pragma mark - GPBEmpty + +/** + * A generic empty message that you can re-use to avoid defining duplicated + * empty messages in your APIs. A typical example is to use it as the request + * or the response type of an API method. For instance: + * + * service Foo { + * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + * } + * + * The JSON representation for `Empty` is empty JSON object `{}`. + **/ +@interface GPBEmpty : GPBMessage + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.m new file mode 100644 index 0000000..506b500 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.m @@ -0,0 +1,83 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/empty.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Empty.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBEmptyRoot + +@implementation GPBEmptyRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBEmptyRoot_FileDescriptor + +static GPBFileDescriptor *GPBEmptyRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBEmpty + +@implementation GPBEmpty + + +typedef struct GPBEmpty__storage_ { + uint32_t _has_storage_[1]; +} GPBEmpty__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEmpty class] + rootClass:[GPBEmptyRoot class] + file:GPBEmptyRoot_FileDescriptor() + fields:NULL + fieldCount:0 + storageSize:sizeof(GPBEmpty__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.h new file mode 100644 index 0000000..73296d5 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.h @@ -0,0 +1,281 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/field_mask.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBFieldMaskRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBFieldMaskRoot : GPBRootObject +@end + +#pragma mark - GPBFieldMask + +typedef GPB_ENUM(GPBFieldMask_FieldNumber) { + GPBFieldMask_FieldNumber_PathsArray = 1, +}; + +/** + * `FieldMask` represents a set of symbolic field paths, for example: + * + * paths: "f.a" + * paths: "f.b.d" + * + * Here `f` represents a field in some root message, `a` and `b` + * fields in the message found in `f`, and `d` a field found in the + * message in `f.b`. + * + * Field masks are used to specify a subset of fields that should be + * returned by a get operation or modified by an update operation. + * Field masks also have a custom JSON encoding (see below). + * + * # Field Masks in Projections + * + * When used in the context of a projection, a response message or + * sub-message is filtered by the API to only contain those fields as + * specified in the mask. For example, if the mask in the previous + * example is applied to a response message as follows: + * + * f { + * a : 22 + * b { + * d : 1 + * x : 2 + * } + * y : 13 + * } + * z: 8 + * + * The result will not contain specific values for fields x,y and z + * (their value will be set to the default, and omitted in proto text + * output): + * + * + * f { + * a : 22 + * b { + * d : 1 + * } + * } + * + * A repeated field is not allowed except at the last position of a + * paths string. + * + * If a FieldMask object is not present in a get operation, the + * operation applies to all fields (as if a FieldMask of all fields + * had been specified). + * + * Note that a field mask does not necessarily apply to the + * top-level response message. In case of a REST get operation, the + * field mask applies directly to the response, but in case of a REST + * list operation, the mask instead applies to each individual message + * in the returned resource list. In case of a REST custom method, + * other definitions may be used. Where the mask applies will be + * clearly documented together with its declaration in the API. In + * any case, the effect on the returned resource/resources is required + * behavior for APIs. + * + * # Field Masks in Update Operations + * + * A field mask in update operations specifies which fields of the + * targeted resource are going to be updated. The API is required + * to only change the values of the fields as specified in the mask + * and leave the others untouched. If a resource is passed in to + * describe the updated values, the API ignores the values of all + * fields not covered by the mask. + * + * If a repeated field is specified for an update operation, the existing + * repeated values in the target resource will be overwritten by the new values. + * Note that a repeated field is only allowed in the last position of a `paths` + * string. + * + * If a sub-message is specified in the last position of the field mask for an + * update operation, then the existing sub-message in the target resource is + * overwritten. Given the target message: + * + * f { + * b { + * d : 1 + * x : 2 + * } + * c : 1 + * } + * + * And an update message: + * + * f { + * b { + * d : 10 + * } + * } + * + * then if the field mask is: + * + * paths: "f.b" + * + * then the result will be: + * + * f { + * b { + * d : 10 + * } + * c : 1 + * } + * + * However, if the update mask was: + * + * paths: "f.b.d" + * + * then the result would be: + * + * f { + * b { + * d : 10 + * x : 2 + * } + * c : 1 + * } + * + * In order to reset a field's value to the default, the field must + * be in the mask and set to the default value in the provided resource. + * Hence, in order to reset all fields of a resource, provide a default + * instance of the resource and set all fields in the mask, or do + * not provide a mask as described below. + * + * If a field mask is not present on update, the operation applies to + * all fields (as if a field mask of all fields has been specified). + * Note that in the presence of schema evolution, this may mean that + * fields the client does not know and has therefore not filled into + * the request will be reset to their default. If this is unwanted + * behavior, a specific service may require a client to always specify + * a field mask, producing an error if not. + * + * As with get operations, the location of the resource which + * describes the updated values in the request message depends on the + * operation kind. In any case, the effect of the field mask is + * required to be honored by the API. + * + * ## Considerations for HTTP REST + * + * The HTTP kind of an update operation which uses a field mask must + * be set to PATCH instead of PUT in order to satisfy HTTP semantics + * (PUT must only be used for full updates). + * + * # JSON Encoding of Field Masks + * + * In JSON, a field mask is encoded as a single string where paths are + * separated by a comma. Fields name in each path are converted + * to/from lower-camel naming conventions. + * + * As an example, consider the following message declarations: + * + * message Profile { + * User user = 1; + * Photo photo = 2; + * } + * message User { + * string display_name = 1; + * string address = 2; + * } + * + * In proto a field mask for `Profile` may look as such: + * + * mask { + * paths: "user.display_name" + * paths: "photo" + * } + * + * In JSON, the same mask is represented as below: + * + * { + * mask: "user.displayName,photo" + * } + * + * # Field Masks and Oneof Fields + * + * Field masks treat fields in oneofs just as regular fields. Consider the + * following message: + * + * message SampleMessage { + * oneof test_oneof { + * string name = 4; + * SubMessage sub_message = 9; + * } + * } + * + * The field mask can be: + * + * mask { + * paths: "name" + * } + * + * Or: + * + * mask { + * paths: "sub_message" + * } + * + * Note that oneof type names ("test_oneof" in this case) cannot be used in + * paths. + * + * ## Field Mask Verification + * + * The implementation of any API method which has a FieldMask type field in the + * request should verify the included field paths, and return an + * `INVALID_ARGUMENT` error if any path is duplicated or unmappable. + **/ +@interface GPBFieldMask : GPBMessage + +/** The set of field mask paths. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *pathsArray; +/** The number of items in @c pathsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger pathsArray_Count; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.m new file mode 100644 index 0000000..b0915af --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.m @@ -0,0 +1,96 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/field_mask.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/FieldMask.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBFieldMaskRoot + +@implementation GPBFieldMaskRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBFieldMaskRoot_FileDescriptor + +static GPBFileDescriptor *GPBFieldMaskRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBFieldMask + +@implementation GPBFieldMask + +@dynamic pathsArray, pathsArray_Count; + +typedef struct GPBFieldMask__storage_ { + uint32_t _has_storage_[1]; + NSMutableArray *pathsArray; +} GPBFieldMask__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "pathsArray", + .dataTypeSpecific.className = NULL, + .number = GPBFieldMask_FieldNumber_PathsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBFieldMask__storage_, pathsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBFieldMask class] + rootClass:[GPBFieldMaskRoot class] + file:GPBFieldMaskRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBFieldMask__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.h new file mode 100644 index 0000000..e492395 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.h @@ -0,0 +1,77 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/source_context.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBSourceContextRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBSourceContextRoot : GPBRootObject +@end + +#pragma mark - GPBSourceContext + +typedef GPB_ENUM(GPBSourceContext_FieldNumber) { + GPBSourceContext_FieldNumber_FileName = 1, +}; + +/** + * `SourceContext` represents information about the source of a + * protobuf element, like the file in which it is defined. + **/ +@interface GPBSourceContext : GPBMessage + +/** + * The path-qualified name of the .proto file that contained the associated + * protobuf element. For example: `"google/protobuf/source_context.proto"`. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *fileName; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.m new file mode 100644 index 0000000..83bfa34 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.m @@ -0,0 +1,96 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/source_context.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/SourceContext.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBSourceContextRoot + +@implementation GPBSourceContextRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBSourceContextRoot_FileDescriptor + +static GPBFileDescriptor *GPBSourceContextRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBSourceContext + +@implementation GPBSourceContext + +@dynamic fileName; + +typedef struct GPBSourceContext__storage_ { + uint32_t _has_storage_[1]; + NSString *fileName; +} GPBSourceContext__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "fileName", + .dataTypeSpecific.className = NULL, + .number = GPBSourceContext_FieldNumber_FileName, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBSourceContext__storage_, fileName), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBSourceContext class] + rootClass:[GPBSourceContextRoot class] + file:GPBSourceContextRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBSourceContext__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.h new file mode 100644 index 0000000..fb20425 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.h @@ -0,0 +1,204 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/struct.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +@class GPBListValue; +@class GPBStruct; +@class GPBValue; + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Enum GPBNullValue + +/** + * `NullValue` is a singleton enumeration to represent the null value for the + * `Value` type union. + * + * The JSON representation for `NullValue` is JSON `null`. + **/ +typedef GPB_ENUM(GPBNullValue) { + /** + * Value used if any message's field encounters a value that is not defined + * by this enum. The message will also have C functions to get/set the rawValue + * of the field. + **/ + GPBNullValue_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, + /** Null value. */ + GPBNullValue_NullValue = 0, +}; + +GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GPBNullValue_IsValidValue(int32_t value); + +#pragma mark - GPBStructRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBStructRoot : GPBRootObject +@end + +#pragma mark - GPBStruct + +typedef GPB_ENUM(GPBStruct_FieldNumber) { + GPBStruct_FieldNumber_Fields = 1, +}; + +/** + * `Struct` represents a structured data value, consisting of fields + * which map to dynamically typed values. In some languages, `Struct` + * might be supported by a native representation. For example, in + * scripting languages like JS a struct is represented as an + * object. The details of that representation are described together + * with the proto support for the language. + * + * The JSON representation for `Struct` is JSON object. + **/ +@interface GPBStruct : GPBMessage + +/** Unordered map of dynamically typed values. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableDictionary *fields; +/** The number of items in @c fields without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger fields_Count; + +@end + +#pragma mark - GPBValue + +typedef GPB_ENUM(GPBValue_FieldNumber) { + GPBValue_FieldNumber_NullValue = 1, + GPBValue_FieldNumber_NumberValue = 2, + GPBValue_FieldNumber_StringValue = 3, + GPBValue_FieldNumber_BoolValue = 4, + GPBValue_FieldNumber_StructValue = 5, + GPBValue_FieldNumber_ListValue = 6, +}; + +typedef GPB_ENUM(GPBValue_Kind_OneOfCase) { + GPBValue_Kind_OneOfCase_GPBUnsetOneOfCase = 0, + GPBValue_Kind_OneOfCase_NullValue = 1, + GPBValue_Kind_OneOfCase_NumberValue = 2, + GPBValue_Kind_OneOfCase_StringValue = 3, + GPBValue_Kind_OneOfCase_BoolValue = 4, + GPBValue_Kind_OneOfCase_StructValue = 5, + GPBValue_Kind_OneOfCase_ListValue = 6, +}; + +/** + * `Value` represents a dynamically typed value which can be either + * null, a number, a string, a boolean, a recursive struct value, or a + * list of values. A producer of value is expected to set one of that + * variants, absence of any variant indicates an error. + * + * The JSON representation for `Value` is JSON value. + **/ +@interface GPBValue : GPBMessage + +/** The kind of value. */ +@property(nonatomic, readonly) GPBValue_Kind_OneOfCase kindOneOfCase; + +/** Represents a null value. */ +@property(nonatomic, readwrite) GPBNullValue nullValue; + +/** Represents a double value. */ +@property(nonatomic, readwrite) double numberValue; + +/** Represents a string value. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *stringValue; + +/** Represents a boolean value. */ +@property(nonatomic, readwrite) BOOL boolValue; + +/** Represents a structured value. */ +@property(nonatomic, readwrite, strong, null_resettable) GPBStruct *structValue; + +/** Represents a repeated `Value`. */ +@property(nonatomic, readwrite, strong, null_resettable) GPBListValue *listValue; + +@end + +/** + * Fetches the raw value of a @c GPBValue's @c nullValue property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBValue_NullValue_RawValue(GPBValue *message); +/** + * Sets the raw value of an @c GPBValue's @c nullValue property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value); + +/** + * Clears whatever value was set for the oneof 'kind'. + **/ +void GPBValue_ClearKindOneOfCase(GPBValue *message); + +#pragma mark - GPBListValue + +typedef GPB_ENUM(GPBListValue_FieldNumber) { + GPBListValue_FieldNumber_ValuesArray = 1, +}; + +/** + * `ListValue` is a wrapper around a repeated field of values. + * + * The JSON representation for `ListValue` is JSON array. + **/ +@interface GPBListValue : GPBMessage + +/** Repeated field of dynamically typed values. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *valuesArray; +/** The number of items in @c valuesArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger valuesArray_Count; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.m new file mode 100644 index 0000000..816fd6d --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.m @@ -0,0 +1,296 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/struct.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#import + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Struct.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +#pragma mark - GPBStructRoot + +@implementation GPBStructRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBStructRoot_FileDescriptor + +static GPBFileDescriptor *GPBStructRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - Enum GPBNullValue + +GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "NullValue\000"; + static const int32_t values[] = { + GPBNullValue_NullValue, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBNullValue) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBNullValue_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBNullValue_IsValidValue(int32_t value__) { + switch (value__) { + case GPBNullValue_NullValue: + return YES; + default: + return NO; + } +} + +#pragma mark - GPBStruct + +@implementation GPBStruct + +@dynamic fields, fields_Count; + +typedef struct GPBStruct__storage_ { + uint32_t _has_storage_[1]; + NSMutableDictionary *fields; +} GPBStruct__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "fields", + .dataTypeSpecific.className = GPBStringifySymbol(GPBValue), + .number = GPBStruct_FieldNumber_Fields, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBStruct__storage_, fields), + .flags = GPBFieldMapKeyString, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBStruct class] + rootClass:[GPBStructRoot class] + file:GPBStructRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBStruct__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBValue + +@implementation GPBValue + +@dynamic kindOneOfCase; +@dynamic nullValue; +@dynamic numberValue; +@dynamic stringValue; +@dynamic boolValue; +@dynamic structValue; +@dynamic listValue; + +typedef struct GPBValue__storage_ { + uint32_t _has_storage_[2]; + GPBNullValue nullValue; + NSString *stringValue; + GPBStruct *structValue; + GPBListValue *listValue; + double numberValue; +} GPBValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "nullValue", + .dataTypeSpecific.enumDescFunc = GPBNullValue_EnumDescriptor, + .number = GPBValue_FieldNumber_NullValue, + .hasIndex = -1, + .offset = (uint32_t)offsetof(GPBValue__storage_, nullValue), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "numberValue", + .dataTypeSpecific.className = NULL, + .number = GPBValue_FieldNumber_NumberValue, + .hasIndex = -1, + .offset = (uint32_t)offsetof(GPBValue__storage_, numberValue), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeDouble, + }, + { + .name = "stringValue", + .dataTypeSpecific.className = NULL, + .number = GPBValue_FieldNumber_StringValue, + .hasIndex = -1, + .offset = (uint32_t)offsetof(GPBValue__storage_, stringValue), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "boolValue", + .dataTypeSpecific.className = NULL, + .number = GPBValue_FieldNumber_BoolValue, + .hasIndex = -1, + .offset = 0, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "structValue", + .dataTypeSpecific.className = GPBStringifySymbol(GPBStruct), + .number = GPBValue_FieldNumber_StructValue, + .hasIndex = -1, + .offset = (uint32_t)offsetof(GPBValue__storage_, structValue), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "listValue", + .dataTypeSpecific.className = GPBStringifySymbol(GPBListValue), + .number = GPBValue_FieldNumber_ListValue, + .hasIndex = -1, + .offset = (uint32_t)offsetof(GPBValue__storage_, listValue), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBValue class] + rootClass:[GPBStructRoot class] + file:GPBStructRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + static const char *oneofs[] = { + "kind", + }; + [localDescriptor setupOneofs:oneofs + count:(uint32_t)(sizeof(oneofs) / sizeof(char*)) + firstHasIndex:-1]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBValue_NullValue_RawValue(GPBValue *message) { + GPBDescriptor *descriptor = [GPBValue descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value) { + GPBDescriptor *descriptor = [GPBValue descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +void GPBValue_ClearKindOneOfCase(GPBValue *message) { + GPBDescriptor *descriptor = [message descriptor]; + GPBOneofDescriptor *oneof = [descriptor.oneofs objectAtIndex:0]; + GPBMaybeClearOneof(message, oneof, -1, 0); +} +#pragma mark - GPBListValue + +@implementation GPBListValue + +@dynamic valuesArray, valuesArray_Count; + +typedef struct GPBListValue__storage_ { + uint32_t _has_storage_[1]; + NSMutableArray *valuesArray; +} GPBListValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "valuesArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBValue), + .number = GPBListValue_FieldNumber_ValuesArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBListValue__storage_, valuesArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBListValue class] + rootClass:[GPBStructRoot class] + file:GPBStructRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBListValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h new file mode 100644 index 0000000..2c4b8b2 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h @@ -0,0 +1,163 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/timestamp.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBTimestampRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBTimestampRoot : GPBRootObject +@end + +#pragma mark - GPBTimestamp + +typedef GPB_ENUM(GPBTimestamp_FieldNumber) { + GPBTimestamp_FieldNumber_Seconds = 1, + GPBTimestamp_FieldNumber_Nanos = 2, +}; + +/** + * A Timestamp represents a point in time independent of any time zone + * or calendar, represented as seconds and fractions of seconds at + * nanosecond resolution in UTC Epoch time. It is encoded using the + * Proleptic Gregorian Calendar which extends the Gregorian calendar + * backwards to year one. It is encoded assuming all minutes are 60 + * seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from + * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * By restricting to that range, we ensure that we can convert to + * and from RFC 3339 date strings. + * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). + * + * # Examples + * + * Example 1: Compute Timestamp from POSIX `time()`. + * + * Timestamp timestamp; + * timestamp.set_seconds(time(NULL)); + * timestamp.set_nanos(0); + * + * Example 2: Compute Timestamp from POSIX `gettimeofday()`. + * + * struct timeval tv; + * gettimeofday(&tv, NULL); + * + * Timestamp timestamp; + * timestamp.set_seconds(tv.tv_sec); + * timestamp.set_nanos(tv.tv_usec * 1000); + * + * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. + * + * FILETIME ft; + * GetSystemTimeAsFileTime(&ft); + * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + * + * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z + * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. + * Timestamp timestamp; + * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); + * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); + * + * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. + * + * long millis = System.currentTimeMillis(); + * + * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) + * .setNanos((int) ((millis % 1000) * 1000000)).build(); + * + * + * Example 5: Compute Timestamp from current time in Python. + * + * timestamp = Timestamp() + * timestamp.GetCurrentTime() + * + * # JSON Mapping + * + * In JSON format, the Timestamp type is encoded as a string in the + * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the + * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" + * where {year} is always expressed using four digits while {month}, {day}, + * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional + * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), + * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone + * is required. A proto3 JSON serializer should always use UTC (as indicated by + * "Z") when printing the Timestamp type and a proto3 JSON parser should be + * able to accept both UTC and other timezones (as indicated by an offset). + * + * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past + * 01:30 UTC on January 15, 2017. + * + * In JavaScript, one can convert a Date object to this format using the + * standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] + * method. In Python, a standard `datetime.datetime` object can be converted + * to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) + * with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one + * can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( + * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime-- + * ) to obtain a formatter capable of generating timestamps in this format. + **/ +@interface GPBTimestamp : GPBMessage + +/** + * Represents seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + **/ +@property(nonatomic, readwrite) int64_t seconds; + +/** + * Non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions must still have non-negative nanos values + * that count forward in time. Must be from 0 to 999,999,999 + * inclusive. + **/ +@property(nonatomic, readwrite) int32_t nanos; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.m new file mode 100644 index 0000000..4ab159f --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.m @@ -0,0 +1,107 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/timestamp.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Timestamp.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBTimestampRoot + +@implementation GPBTimestampRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBTimestampRoot_FileDescriptor + +static GPBFileDescriptor *GPBTimestampRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBTimestamp + +@implementation GPBTimestamp + +@dynamic seconds; +@dynamic nanos; + +typedef struct GPBTimestamp__storage_ { + uint32_t _has_storage_[1]; + int32_t nanos; + int64_t seconds; +} GPBTimestamp__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "seconds", + .dataTypeSpecific.className = NULL, + .number = GPBTimestamp_FieldNumber_Seconds, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBTimestamp__storage_, seconds), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + { + .name = "nanos", + .dataTypeSpecific.className = NULL, + .number = GPBTimestamp_FieldNumber_Nanos, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBTimestamp__storage_, nanos), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBTimestamp class] + rootClass:[GPBTimestampRoot class] + file:GPBTimestampRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBTimestamp__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.h new file mode 100644 index 0000000..e14d15d --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.h @@ -0,0 +1,444 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/type.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +@class GPBAny; +@class GPBEnumValue; +@class GPBField; +@class GPBOption; +@class GPBSourceContext; + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - Enum GPBSyntax + +/** The syntax in which a protocol buffer element is defined. */ +typedef GPB_ENUM(GPBSyntax) { + /** + * Value used if any message's field encounters a value that is not defined + * by this enum. The message will also have C functions to get/set the rawValue + * of the field. + **/ + GPBSyntax_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, + /** Syntax `proto2`. */ + GPBSyntax_SyntaxProto2 = 0, + + /** Syntax `proto3`. */ + GPBSyntax_SyntaxProto3 = 1, +}; + +GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GPBSyntax_IsValidValue(int32_t value); + +#pragma mark - Enum GPBField_Kind + +/** Basic field types. */ +typedef GPB_ENUM(GPBField_Kind) { + /** + * Value used if any message's field encounters a value that is not defined + * by this enum. The message will also have C functions to get/set the rawValue + * of the field. + **/ + GPBField_Kind_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, + /** Field type unknown. */ + GPBField_Kind_TypeUnknown = 0, + + /** Field type double. */ + GPBField_Kind_TypeDouble = 1, + + /** Field type float. */ + GPBField_Kind_TypeFloat = 2, + + /** Field type int64. */ + GPBField_Kind_TypeInt64 = 3, + + /** Field type uint64. */ + GPBField_Kind_TypeUint64 = 4, + + /** Field type int32. */ + GPBField_Kind_TypeInt32 = 5, + + /** Field type fixed64. */ + GPBField_Kind_TypeFixed64 = 6, + + /** Field type fixed32. */ + GPBField_Kind_TypeFixed32 = 7, + + /** Field type bool. */ + GPBField_Kind_TypeBool = 8, + + /** Field type string. */ + GPBField_Kind_TypeString = 9, + + /** Field type group. Proto2 syntax only, and deprecated. */ + GPBField_Kind_TypeGroup = 10, + + /** Field type message. */ + GPBField_Kind_TypeMessage = 11, + + /** Field type bytes. */ + GPBField_Kind_TypeBytes = 12, + + /** Field type uint32. */ + GPBField_Kind_TypeUint32 = 13, + + /** Field type enum. */ + GPBField_Kind_TypeEnum = 14, + + /** Field type sfixed32. */ + GPBField_Kind_TypeSfixed32 = 15, + + /** Field type sfixed64. */ + GPBField_Kind_TypeSfixed64 = 16, + + /** Field type sint32. */ + GPBField_Kind_TypeSint32 = 17, + + /** Field type sint64. */ + GPBField_Kind_TypeSint64 = 18, +}; + +GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GPBField_Kind_IsValidValue(int32_t value); + +#pragma mark - Enum GPBField_Cardinality + +/** Whether a field is optional, required, or repeated. */ +typedef GPB_ENUM(GPBField_Cardinality) { + /** + * Value used if any message's field encounters a value that is not defined + * by this enum. The message will also have C functions to get/set the rawValue + * of the field. + **/ + GPBField_Cardinality_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, + /** For fields with unknown cardinality. */ + GPBField_Cardinality_CardinalityUnknown = 0, + + /** For optional fields. */ + GPBField_Cardinality_CardinalityOptional = 1, + + /** For required fields. Proto2 syntax only. */ + GPBField_Cardinality_CardinalityRequired = 2, + + /** For repeated fields. */ + GPBField_Cardinality_CardinalityRepeated = 3, +}; + +GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void); + +/** + * Checks to see if the given value is defined by the enum or was not known at + * the time this source was generated. + **/ +BOOL GPBField_Cardinality_IsValidValue(int32_t value); + +#pragma mark - GPBTypeRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBTypeRoot : GPBRootObject +@end + +#pragma mark - GPBType + +typedef GPB_ENUM(GPBType_FieldNumber) { + GPBType_FieldNumber_Name = 1, + GPBType_FieldNumber_FieldsArray = 2, + GPBType_FieldNumber_OneofsArray = 3, + GPBType_FieldNumber_OptionsArray = 4, + GPBType_FieldNumber_SourceContext = 5, + GPBType_FieldNumber_Syntax = 6, +}; + +/** + * A protocol buffer message type. + **/ +@interface GPBType : GPBMessage + +/** The fully qualified message name. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** The list of fields. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *fieldsArray; +/** The number of items in @c fieldsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger fieldsArray_Count; + +/** The list of types appearing in `oneof` definitions in this type. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *oneofsArray; +/** The number of items in @c oneofsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger oneofsArray_Count; + +/** The protocol buffer options. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +/** The source context. */ +@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; +/** Test to see if @c sourceContext has been set. */ +@property(nonatomic, readwrite) BOOL hasSourceContext; + +/** The source syntax. */ +@property(nonatomic, readwrite) GPBSyntax syntax; + +@end + +/** + * Fetches the raw value of a @c GPBType's @c syntax property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBType_Syntax_RawValue(GPBType *message); +/** + * Sets the raw value of an @c GPBType's @c syntax property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value); + +#pragma mark - GPBField + +typedef GPB_ENUM(GPBField_FieldNumber) { + GPBField_FieldNumber_Kind = 1, + GPBField_FieldNumber_Cardinality = 2, + GPBField_FieldNumber_Number = 3, + GPBField_FieldNumber_Name = 4, + GPBField_FieldNumber_TypeURL = 6, + GPBField_FieldNumber_OneofIndex = 7, + GPBField_FieldNumber_Packed = 8, + GPBField_FieldNumber_OptionsArray = 9, + GPBField_FieldNumber_JsonName = 10, + GPBField_FieldNumber_DefaultValue = 11, +}; + +/** + * A single field of a message type. + **/ +@interface GPBField : GPBMessage + +/** The field type. */ +@property(nonatomic, readwrite) GPBField_Kind kind; + +/** The field cardinality. */ +@property(nonatomic, readwrite) GPBField_Cardinality cardinality; + +/** The field number. */ +@property(nonatomic, readwrite) int32_t number; + +/** The field name. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** + * The field type URL, without the scheme, for message or enumeration + * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL; + +/** + * The index of the field type in `Type.oneofs`, for message or enumeration + * types. The first type has index 1; zero means the type is not in the list. + **/ +@property(nonatomic, readwrite) int32_t oneofIndex; + +/** Whether to use alternative packed wire representation. */ +@property(nonatomic, readwrite) BOOL packed; + +/** The protocol buffer options. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +/** The field JSON name. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *jsonName; + +/** The string value of the default value of this field. Proto2 syntax only. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *defaultValue; + +@end + +/** + * Fetches the raw value of a @c GPBField's @c kind property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBField_Kind_RawValue(GPBField *message); +/** + * Sets the raw value of an @c GPBField's @c kind property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBField_Kind_RawValue(GPBField *message, int32_t value); + +/** + * Fetches the raw value of a @c GPBField's @c cardinality property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBField_Cardinality_RawValue(GPBField *message); +/** + * Sets the raw value of an @c GPBField's @c cardinality property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value); + +#pragma mark - GPBEnum + +typedef GPB_ENUM(GPBEnum_FieldNumber) { + GPBEnum_FieldNumber_Name = 1, + GPBEnum_FieldNumber_EnumvalueArray = 2, + GPBEnum_FieldNumber_OptionsArray = 3, + GPBEnum_FieldNumber_SourceContext = 4, + GPBEnum_FieldNumber_Syntax = 5, +}; + +/** + * Enum type definition. + **/ +@interface GPBEnum : GPBMessage + +/** Enum type name. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** Enum value definitions. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *enumvalueArray; +/** The number of items in @c enumvalueArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger enumvalueArray_Count; + +/** Protocol buffer options. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +/** The source context. */ +@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; +/** Test to see if @c sourceContext has been set. */ +@property(nonatomic, readwrite) BOOL hasSourceContext; + +/** The source syntax. */ +@property(nonatomic, readwrite) GPBSyntax syntax; + +@end + +/** + * Fetches the raw value of a @c GPBEnum's @c syntax property, even + * if the value was not defined by the enum at the time the code was generated. + **/ +int32_t GPBEnum_Syntax_RawValue(GPBEnum *message); +/** + * Sets the raw value of an @c GPBEnum's @c syntax property, allowing + * it to be set to a value that was not defined by the enum at the time the code + * was generated. + **/ +void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value); + +#pragma mark - GPBEnumValue + +typedef GPB_ENUM(GPBEnumValue_FieldNumber) { + GPBEnumValue_FieldNumber_Name = 1, + GPBEnumValue_FieldNumber_Number = 2, + GPBEnumValue_FieldNumber_OptionsArray = 3, +}; + +/** + * Enum value definition. + **/ +@interface GPBEnumValue : GPBMessage + +/** Enum value name. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** Enum value number. */ +@property(nonatomic, readwrite) int32_t number; + +/** Protocol buffer options. */ +@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; +/** The number of items in @c optionsArray without causing the array to be created. */ +@property(nonatomic, readonly) NSUInteger optionsArray_Count; + +@end + +#pragma mark - GPBOption + +typedef GPB_ENUM(GPBOption_FieldNumber) { + GPBOption_FieldNumber_Name = 1, + GPBOption_FieldNumber_Value = 2, +}; + +/** + * A protocol buffer option, which can be attached to a message, field, + * enumeration, etc. + **/ +@interface GPBOption : GPBMessage + +/** + * The option's name. For protobuf built-in options (options defined in + * descriptor.proto), this is the short name. For example, `"map_entry"`. + * For custom options, it should be the fully-qualified name. For example, + * `"google.api.http"`. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *name; + +/** + * The option's value packed in an Any message. If the value is a primitive, + * the corresponding wrapper type defined in google/protobuf/wrappers.proto + * should be used. If the value is an enum, it should be stored as an int32 + * value using the google.protobuf.Int32Value type. + **/ +@property(nonatomic, readwrite, strong, null_resettable) GPBAny *value; +/** Test to see if @c value has been set. */ +@property(nonatomic, readwrite) BOOL hasValue; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.m new file mode 100644 index 0000000..bb64d87 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.m @@ -0,0 +1,706 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/type.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#import + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "google/protobuf/Type.pbobjc.h" + #import "google/protobuf/Any.pbobjc.h" + #import "google/protobuf/SourceContext.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBTypeRoot + +@implementation GPBTypeRoot + +// No extensions in the file and none of the imports (direct or indirect) +// defined extensions, so no need to generate +extensionRegistry. + +@end + +#pragma mark - GPBTypeRoot_FileDescriptor + +static GPBFileDescriptor *GPBTypeRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - Enum GPBSyntax + +GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "SyntaxProto2\000SyntaxProto3\000"; + static const int32_t values[] = { + GPBSyntax_SyntaxProto2, + GPBSyntax_SyntaxProto3, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBSyntax) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBSyntax_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBSyntax_IsValidValue(int32_t value__) { + switch (value__) { + case GPBSyntax_SyntaxProto2: + case GPBSyntax_SyntaxProto3: + return YES; + default: + return NO; + } +} + +#pragma mark - GPBType + +@implementation GPBType + +@dynamic name; +@dynamic fieldsArray, fieldsArray_Count; +@dynamic oneofsArray, oneofsArray_Count; +@dynamic optionsArray, optionsArray_Count; +@dynamic hasSourceContext, sourceContext; +@dynamic syntax; + +typedef struct GPBType__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSMutableArray *fieldsArray; + NSMutableArray *oneofsArray; + NSMutableArray *optionsArray; + GPBSourceContext *sourceContext; +} GPBType__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBType_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBType__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "fieldsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBField), + .number = GPBType_FieldNumber_FieldsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, fieldsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "oneofsArray", + .dataTypeSpecific.className = NULL, + .number = GPBType_FieldNumber_OneofsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, oneofsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBType_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "sourceContext", + .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), + .number = GPBType_FieldNumber_SourceContext, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBType__storage_, sourceContext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBType_FieldNumber_Syntax, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBType__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBType class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBType__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBType_Syntax_RawValue(GPBType *message) { + GPBDescriptor *descriptor = [GPBType descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value) { + GPBDescriptor *descriptor = [GPBType descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +#pragma mark - GPBField + +@implementation GPBField + +@dynamic kind; +@dynamic cardinality; +@dynamic number; +@dynamic name; +@dynamic typeURL; +@dynamic oneofIndex; +@dynamic packed; +@dynamic optionsArray, optionsArray_Count; +@dynamic jsonName; +@dynamic defaultValue; + +typedef struct GPBField__storage_ { + uint32_t _has_storage_[1]; + GPBField_Kind kind; + GPBField_Cardinality cardinality; + int32_t number; + int32_t oneofIndex; + NSString *name; + NSString *typeURL; + NSMutableArray *optionsArray; + NSString *jsonName; + NSString *defaultValue; +} GPBField__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "kind", + .dataTypeSpecific.enumDescFunc = GPBField_Kind_EnumDescriptor, + .number = GPBField_FieldNumber_Kind, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBField__storage_, kind), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "cardinality", + .dataTypeSpecific.enumDescFunc = GPBField_Cardinality_EnumDescriptor, + .number = GPBField_FieldNumber_Cardinality, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBField__storage_, cardinality), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + { + .name = "number", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_Number, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBField__storage_, number), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_Name, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GPBField__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "typeURL", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_TypeURL, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GPBField__storage_, typeURL), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), + .dataType = GPBDataTypeString, + }, + { + .name = "oneofIndex", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_OneofIndex, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GPBField__storage_, oneofIndex), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "packed", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_Packed, + .hasIndex = 6, + .offset = 7, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBField_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBField__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "jsonName", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_JsonName, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GPBField__storage_, jsonName), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "defaultValue", + .dataTypeSpecific.className = NULL, + .number = GPBField_FieldNumber_DefaultValue, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GPBField__storage_, defaultValue), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBField class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBField__storage_) + flags:GPBDescriptorInitializationFlag_None]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\001\006\004\241!!\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBField_Kind_RawValue(GPBField *message) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBField_Kind_RawValue(GPBField *message, int32_t value) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +int32_t GPBField_Cardinality_RawValue(GPBField *message) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +#pragma mark - Enum GPBField_Kind + +GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "TypeUnknown\000TypeDouble\000TypeFloat\000TypeInt" + "64\000TypeUint64\000TypeInt32\000TypeFixed64\000Type" + "Fixed32\000TypeBool\000TypeString\000TypeGroup\000Ty" + "peMessage\000TypeBytes\000TypeUint32\000TypeEnum\000" + "TypeSfixed32\000TypeSfixed64\000TypeSint32\000Typ" + "eSint64\000"; + static const int32_t values[] = { + GPBField_Kind_TypeUnknown, + GPBField_Kind_TypeDouble, + GPBField_Kind_TypeFloat, + GPBField_Kind_TypeInt64, + GPBField_Kind_TypeUint64, + GPBField_Kind_TypeInt32, + GPBField_Kind_TypeFixed64, + GPBField_Kind_TypeFixed32, + GPBField_Kind_TypeBool, + GPBField_Kind_TypeString, + GPBField_Kind_TypeGroup, + GPBField_Kind_TypeMessage, + GPBField_Kind_TypeBytes, + GPBField_Kind_TypeUint32, + GPBField_Kind_TypeEnum, + GPBField_Kind_TypeSfixed32, + GPBField_Kind_TypeSfixed64, + GPBField_Kind_TypeSint32, + GPBField_Kind_TypeSint64, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Kind) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBField_Kind_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBField_Kind_IsValidValue(int32_t value__) { + switch (value__) { + case GPBField_Kind_TypeUnknown: + case GPBField_Kind_TypeDouble: + case GPBField_Kind_TypeFloat: + case GPBField_Kind_TypeInt64: + case GPBField_Kind_TypeUint64: + case GPBField_Kind_TypeInt32: + case GPBField_Kind_TypeFixed64: + case GPBField_Kind_TypeFixed32: + case GPBField_Kind_TypeBool: + case GPBField_Kind_TypeString: + case GPBField_Kind_TypeGroup: + case GPBField_Kind_TypeMessage: + case GPBField_Kind_TypeBytes: + case GPBField_Kind_TypeUint32: + case GPBField_Kind_TypeEnum: + case GPBField_Kind_TypeSfixed32: + case GPBField_Kind_TypeSfixed64: + case GPBField_Kind_TypeSint32: + case GPBField_Kind_TypeSint64: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GPBField_Cardinality + +GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "CardinalityUnknown\000CardinalityOptional\000C" + "ardinalityRequired\000CardinalityRepeated\000"; + static const int32_t values[] = { + GPBField_Cardinality_CardinalityUnknown, + GPBField_Cardinality_CardinalityOptional, + GPBField_Cardinality_CardinalityRequired, + GPBField_Cardinality_CardinalityRepeated, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Cardinality) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBField_Cardinality_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBField_Cardinality_IsValidValue(int32_t value__) { + switch (value__) { + case GPBField_Cardinality_CardinalityUnknown: + case GPBField_Cardinality_CardinalityOptional: + case GPBField_Cardinality_CardinalityRequired: + case GPBField_Cardinality_CardinalityRepeated: + return YES; + default: + return NO; + } +} + +#pragma mark - GPBEnum + +@implementation GPBEnum + +@dynamic name; +@dynamic enumvalueArray, enumvalueArray_Count; +@dynamic optionsArray, optionsArray_Count; +@dynamic hasSourceContext, sourceContext; +@dynamic syntax; + +typedef struct GPBEnum__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSMutableArray *enumvalueArray; + NSMutableArray *optionsArray; + GPBSourceContext *sourceContext; +} GPBEnum__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBEnum_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBEnum__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "enumvalueArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBEnumValue), + .number = GPBEnum_FieldNumber_EnumvalueArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnum__storage_, enumvalueArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBEnum_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnum__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "sourceContext", + .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), + .number = GPBEnum_FieldNumber_SourceContext, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBEnum__storage_, sourceContext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBEnum_FieldNumber_Syntax, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBEnum__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEnum class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBEnum__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBEnum_Syntax_RawValue(GPBEnum *message) { + GPBDescriptor *descriptor = [GPBEnum descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; + return GPBGetMessageInt32Field(message, field); +} + +void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value) { + GPBDescriptor *descriptor = [GPBEnum descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; + GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); +} + +#pragma mark - GPBEnumValue + +@implementation GPBEnumValue + +@dynamic name; +@dynamic number; +@dynamic optionsArray, optionsArray_Count; + +typedef struct GPBEnumValue__storage_ { + uint32_t _has_storage_[1]; + int32_t number; + NSString *name; + NSMutableArray *optionsArray; +} GPBEnumValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBEnumValue_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "number", + .dataTypeSpecific.className = NULL, + .number = GPBEnumValue_FieldNumber_Number, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, number), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + { + .name = "optionsArray", + .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), + .number = GPBEnumValue_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEnumValue class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBEnumValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBOption + +@implementation GPBOption + +@dynamic name; +@dynamic hasValue, value; + +typedef struct GPBOption__storage_ { + uint32_t _has_storage_[1]; + NSString *name; + GPBAny *value; +} GPBOption__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.className = NULL, + .number = GPBOption_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBOption__storage_, name), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + { + .name = "value", + .dataTypeSpecific.className = GPBStringifySymbol(GPBAny), + .number = GPBOption_FieldNumber_Value, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBOption__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBOption class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBOption__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.h b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.h new file mode 100644 index 0000000..0411e1e --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.h @@ -0,0 +1,219 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/wrappers.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBWrappersRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +@interface GPBWrappersRoot : GPBRootObject +@end + +#pragma mark - GPBDoubleValue + +typedef GPB_ENUM(GPBDoubleValue_FieldNumber) { + GPBDoubleValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `double`. + * + * The JSON representation for `DoubleValue` is JSON number. + **/ +@interface GPBDoubleValue : GPBMessage + +/** The double value. */ +@property(nonatomic, readwrite) double value; + +@end + +#pragma mark - GPBFloatValue + +typedef GPB_ENUM(GPBFloatValue_FieldNumber) { + GPBFloatValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `float`. + * + * The JSON representation for `FloatValue` is JSON number. + **/ +@interface GPBFloatValue : GPBMessage + +/** The float value. */ +@property(nonatomic, readwrite) float value; + +@end + +#pragma mark - GPBInt64Value + +typedef GPB_ENUM(GPBInt64Value_FieldNumber) { + GPBInt64Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `int64`. + * + * The JSON representation for `Int64Value` is JSON string. + **/ +@interface GPBInt64Value : GPBMessage + +/** The int64 value. */ +@property(nonatomic, readwrite) int64_t value; + +@end + +#pragma mark - GPBUInt64Value + +typedef GPB_ENUM(GPBUInt64Value_FieldNumber) { + GPBUInt64Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `uint64`. + * + * The JSON representation for `UInt64Value` is JSON string. + **/ +@interface GPBUInt64Value : GPBMessage + +/** The uint64 value. */ +@property(nonatomic, readwrite) uint64_t value; + +@end + +#pragma mark - GPBInt32Value + +typedef GPB_ENUM(GPBInt32Value_FieldNumber) { + GPBInt32Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `int32`. + * + * The JSON representation for `Int32Value` is JSON number. + **/ +@interface GPBInt32Value : GPBMessage + +/** The int32 value. */ +@property(nonatomic, readwrite) int32_t value; + +@end + +#pragma mark - GPBUInt32Value + +typedef GPB_ENUM(GPBUInt32Value_FieldNumber) { + GPBUInt32Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `uint32`. + * + * The JSON representation for `UInt32Value` is JSON number. + **/ +@interface GPBUInt32Value : GPBMessage + +/** The uint32 value. */ +@property(nonatomic, readwrite) uint32_t value; + +@end + +#pragma mark - GPBBoolValue + +typedef GPB_ENUM(GPBBoolValue_FieldNumber) { + GPBBoolValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `bool`. + * + * The JSON representation for `BoolValue` is JSON `true` and `false`. + **/ +@interface GPBBoolValue : GPBMessage + +/** The bool value. */ +@property(nonatomic, readwrite) BOOL value; + +@end + +#pragma mark - GPBStringValue + +typedef GPB_ENUM(GPBStringValue_FieldNumber) { + GPBStringValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `string`. + * + * The JSON representation for `StringValue` is JSON string. + **/ +@interface GPBStringValue : GPBMessage + +/** The string value. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *value; + +@end + +#pragma mark - GPBBytesValue + +typedef GPB_ENUM(GPBBytesValue_FieldNumber) { + GPBBytesValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `bytes`. + * + * The JSON representation for `BytesValue` is JSON string. + **/ +@interface GPBBytesValue : GPBMessage + +/** The bytes value. */ +@property(nonatomic, readwrite, copy, null_resettable) NSData *value; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.m b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.m new file mode 100644 index 0000000..5479eb1 --- /dev/null +++ b/My Mind/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.m @@ -0,0 +1,439 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/wrappers.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "google/protobuf/Wrappers.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBWrappersRoot + +@implementation GPBWrappersRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBWrappersRoot_FileDescriptor + +static GPBFileDescriptor *GPBWrappersRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBDoubleValue + +@implementation GPBDoubleValue + +@dynamic value; + +typedef struct GPBDoubleValue__storage_ { + uint32_t _has_storage_[1]; + double value; +} GPBDoubleValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBDoubleValue_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBDoubleValue__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeDouble, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBDoubleValue class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBDoubleValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBFloatValue + +@implementation GPBFloatValue + +@dynamic value; + +typedef struct GPBFloatValue__storage_ { + uint32_t _has_storage_[1]; + float value; +} GPBFloatValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBFloatValue_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBFloatValue__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeFloat, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBFloatValue class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBFloatValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBInt64Value + +@implementation GPBInt64Value + +@dynamic value; + +typedef struct GPBInt64Value__storage_ { + uint32_t _has_storage_[1]; + int64_t value; +} GPBInt64Value__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBInt64Value_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBInt64Value__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBInt64Value class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBInt64Value__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBUInt64Value + +@implementation GPBUInt64Value + +@dynamic value; + +typedef struct GPBUInt64Value__storage_ { + uint32_t _has_storage_[1]; + uint64_t value; +} GPBUInt64Value__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBUInt64Value_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBUInt64Value__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt64, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBUInt64Value class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBUInt64Value__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBInt32Value + +@implementation GPBInt32Value + +@dynamic value; + +typedef struct GPBInt32Value__storage_ { + uint32_t _has_storage_[1]; + int32_t value; +} GPBInt32Value__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBInt32Value_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBInt32Value__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBInt32Value class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBInt32Value__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBUInt32Value + +@implementation GPBUInt32Value + +@dynamic value; + +typedef struct GPBUInt32Value__storage_ { + uint32_t _has_storage_[1]; + uint32_t value; +} GPBUInt32Value__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBUInt32Value_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBUInt32Value__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeUInt32, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBUInt32Value class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBUInt32Value__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBBoolValue + +@implementation GPBBoolValue + +@dynamic value; + +typedef struct GPBBoolValue__storage_ { + uint32_t _has_storage_[1]; +} GPBBoolValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBBoolValue_FieldNumber_Value, + .hasIndex = 0, + .offset = 1, // Stored in _has_storage_ to save space. + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBool, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBBoolValue class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBBoolValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBStringValue + +@implementation GPBStringValue + +@dynamic value; + +typedef struct GPBStringValue__storage_ { + uint32_t _has_storage_[1]; + NSString *value; +} GPBStringValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBStringValue_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBStringValue__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBStringValue class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBStringValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBBytesValue + +@implementation GPBBytesValue + +@dynamic value; + +typedef struct GPBBytesValue__storage_ { + uint32_t _has_storage_[1]; + NSData *value; +} GPBBytesValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "value", + .dataTypeSpecific.className = NULL, + .number = GPBBytesValue_FieldNumber_Value, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBBytesValue__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeBytes, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBBytesValue class] + rootClass:[GPBWrappersRoot class] + file:GPBWrappersRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBBytesValue__storage_) + flags:GPBDescriptorInitializationFlag_None]; + NSAssert(descriptor == nil, @"Startup recursed!"); + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/My Mind/Pods/SwiftForms/LICENSE b/My Mind/Pods/SwiftForms/LICENSE new file mode 100644 index 0000000..03d0bb6 --- /dev/null +++ b/My Mind/Pods/SwiftForms/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Xmartlabs ( http://xmartlabs.com ) +Copyright (c) 2014 Miguel Ángel Ortuño ( ortuman@gmail.com ) + +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/My Mind/Pods/SwiftForms/README.MD b/My Mind/Pods/SwiftForms/README.MD new file mode 100644 index 0000000..dd0afa3 --- /dev/null +++ b/My Mind/Pods/SwiftForms/README.MD @@ -0,0 +1,155 @@ + +[![Version](https://img.shields.io/badge/pod-1.8.2-orange.svg)](http://cocoadocs.org/docsets/SwiftForms) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +[![License](https://img.shields.io/badge/license-MIT-gray.svg)](http://cocoadocs.org/docsets/SwiftForms) +[![Platform](https://img.shields.io/badge/platform-iOS-lightgrey.svg)](http://cocoadocs.org/docsets/SwiftForms) + +SwiftForms +========== + +Purpose +------- +SwiftForms is a powerful and extremely flexible library written in Swift that allows to create forms by just defining them in a couple of lines. It also provides the ability to customize cells appearance, use custom cells and define your own selector controllers. + +Here is an screenshot from an example application using SwiftForms + +![Screenshot of Example application](SwiftFormsApplication/Example.gif) + +How to create a form +-------------------- + +Creating a form using SwiftForms is pretty straightforward. All you need is to derive your controller from `FormViewController` and define a `FormDescriptor` instance along with its sections and rows. Here is an example of how to create a simple form to input an email and a user password. + +```swift + +// Create form instace +var form = FormDescriptor() +form.title = "Example form" + +// Define first section +var section1 = FormSectionDescriptor() + +var row = FormRowDescriptor(tag: "name", rowType: .Email, title: "Email") +section1.rows.append(row) + +row = FormRowDescriptor(tag: "pass", rowType: .Password, title: "Password") +section1.rows.append(row) + +// Define second section +var section2 = FormSectionDescriptor() + +row = FormRowDescriptor(tag: "button", rowType: .Button, title: "Submit") +section2.rows.append(row) + +form.sections = [section1, section2] + +self.form = form +``` +To see a more complex form definition you can take a look to the example application. + +Cell appearance +---------------------- + +Every row descriptor has a `configuration` dictionary that allows to customize cell's appearance and behavior. In order to change concrete visual aspects of a row simply set `row.configuration.cell.appearance` value to a dictionary containing custom key-value coding properties. + +Here's an example: + +```swift +row.configuration.cell.appearance = ["titleLabel.font" : UIFont.boldSystemFontOfSize(30.0), "segmentedControl.tintColor" : UIColor.redColor()] +``` + +Custom cells +----------------- + +In addition, it is possible to create 100% custom cells by deriving from `FormBaseCell` class. In that case, don't forget to override `configure` and `update` methods. First method will be called only once and after cell has been created, and the second one every time cell content should be refreshed. + +Here are the methods that help you to define custom cell behavior. +```swift +func configure() { + /// override +} + +func update() { + /// override +} + +class func formRowCellHeight() -> CGFloat { + return 44.0 +} + +class func formViewController(formViewController: FormViewController, didSelectRow: FormBaseCell) { +} +``` +Once you have defined your custom cell, and in order to use it for a concrete row, you'll have to set `FormRowDescriptor` cellClass property. + +Custom selector controllers +------------------------------------- + +In order to customize selector controller your class should conform to `FormSelector` protocol. That way you'll have access to the cell instance that pushed the controller, being able to alter its properties or setting it's row value accordingly to user interaction. + +After defining your class, don't forget to set `row.configuration.selection.controllerClass` value in the configuration dictionary to use your custom selector controller. + +Requirements +--------------------- + +* iOS 8.0 and above + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. + +CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +To integrate SwiftForms into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'SwiftForms' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +Simply add the following line to your `Cartfile`: + +``` +github "ortuman/SwiftForms" +``` + +Then run: + +```bash +$ carthage update +``` + +For more information on [Carthage](https://github.com/Carthage/Carthage) see the [README](https://github.com/Carthage/Carthage/blob/master/README.md) + +Copyright +--------- + +SwiftForms is originally based on XLForm github project. (https://github.com/xmartlabs/XLForm) + +Check LICENSE file for more details. + +Contact +------- + +If you are using SwiftForms in your project and have any suggestion or question: + +Miguel Angel Ortuño, + +[@ortuman](http://twitter.com/ortuman) + diff --git a/My Mind/Pods/SwiftForms/SwiftForms/FormErrorType.swift b/My Mind/Pods/SwiftForms/SwiftForms/FormErrorType.swift new file mode 100644 index 0000000..37356e8 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/FormErrorType.swift @@ -0,0 +1,12 @@ +// +// FormErrorType.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 2/1/16. +// Copyright © 2016 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +public enum FormErrorType: Error { + case sectionOutOfIndex + case rowOutOfIndex +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormButtonCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormButtonCell.swift new file mode 100644 index 0000000..0d3dcdb --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormButtonCell.swift @@ -0,0 +1,24 @@ +// +// FormButtonCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormButtonCell: FormTitleCell { + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + titleLabel.textAlignment = .center + } + + open override func update() { + super.update() + titleLabel.text = rowDescriptor?.title + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormCheckCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormCheckCell.swift new file mode 100644 index 0000000..818c355 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormCheckCell.swift @@ -0,0 +1,55 @@ +// +// FormCheckCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormCheckCell: FormTitleCell { + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + selectionStyle = .default + accessoryType = .none + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + var rowValue: Bool + if let value = rowDescriptor?.value as? Bool { + rowValue = value + } else { + rowValue = false + rowDescriptor?.value = rowValue as AnyObject + } + + accessoryType = (rowValue) ? .checkmark : .none + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormCheckCell else { return } + row.check() + } + + // MARK: Private interface + + fileprivate func check() { + var newValue: Bool + if let value = rowDescriptor?.value as? Bool { + newValue = !value + } + else { + newValue = true + } + rowDescriptor?.value = newValue as AnyObject + update() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormDateCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormDateCell.swift new file mode 100644 index 0000000..001c805 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormDateCell.swift @@ -0,0 +1,98 @@ +// +// FormDateCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormDateCell: FormValueCell { + + // MARK: Properties + + private let datePicker = UIDatePicker() + private let hiddenTextField = UITextField(frame: CGRect.zero) + + private let defaultDateFormatter = DateFormatter() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + contentView.addSubview(hiddenTextField) + hiddenTextField.inputView = datePicker + hiddenTextField.isAccessibilityElement = false + datePicker.datePickerMode = .date + datePicker.addTarget(self, action: #selector(FormDateCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && hiddenTextField.inputAccessoryView == nil { + hiddenTextField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + + if let rowType = rowDescriptor?.type { + switch rowType { + case .date: + datePicker.datePickerMode = .date + defaultDateFormatter.dateStyle = .long + defaultDateFormatter.timeStyle = .none + case .time: + datePicker.datePickerMode = .time + defaultDateFormatter.dateStyle = .none + defaultDateFormatter.timeStyle = .short + default: + datePicker.datePickerMode = .dateAndTime + defaultDateFormatter.dateStyle = .long + defaultDateFormatter.timeStyle = .short + } + } + + if let date = rowDescriptor?.value as? Date { + datePicker.date = date + valueLabel.text = getDateFormatter().string(from: date) + } + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormDateCell else { return } + + if row.rowDescriptor?.value == nil { + let date = Date() + row.rowDescriptor?.value = date as AnyObject + row.valueLabel.text = row.getDateFormatter().string(from: date) + row.update() + } + + row.hiddenTextField.becomeFirstResponder() + } + + open override func firstResponderElement() -> UIResponder? { + return hiddenTextField + } + + open override class func formRowCanBecomeFirstResponder() -> Bool { + return true + } + + // MARK: Actions + + @objc internal func valueChanged(_ sender: UIDatePicker) { + rowDescriptor?.value = sender.date as AnyObject + valueLabel.text = getDateFormatter().string(from: sender.date) + update() + } + + // MARK: Private interface + + fileprivate func getDateFormatter() -> DateFormatter { + guard let dateFormatter = rowDescriptor?.configuration.date.dateFormatter else { return defaultDateFormatter } + return dateFormatter + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormLabelCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormLabelCell.swift new file mode 100644 index 0000000..c3d9d30 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormLabelCell.swift @@ -0,0 +1,48 @@ +// +// FormTextFieldCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormLabelCell: FormValueCell { + + /// MARK: FormBaseCell + + override open func configure() { + super.configure() + + accessoryType = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + valueLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + valueLabel.textColor = UIColor.lightGray + valueLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(valueLabel) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + // apply constant constraints + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + override open func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + valueLabel.text = rowDescriptor?.configuration.cell.placeholder + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormPickerCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormPickerCell.swift new file mode 100644 index 0000000..cf2cf76 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormPickerCell.swift @@ -0,0 +1,106 @@ +// +// FormPickerCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 22/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource { + + // MARK: Properties + + private let picker = UIPickerView() + private let hiddenTextField = UITextField(frame: CGRect.zero) + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + accessoryType = .none + + picker.delegate = self + picker.dataSource = self + hiddenTextField.inputView = picker + hiddenTextField.isAccessibilityElement = false + + contentView.addSubview(hiddenTextField) + } + + open override func update() { + super.update() + picker.reloadAllComponents() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && hiddenTextField.inputAccessoryView == nil { + hiddenTextField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + valueLabel.text = "" + + if let selectedValue = rowDescriptor?.value { + valueLabel.text = rowDescriptor?.configuration.selection.optionTitleClosure?(selectedValue) + if let options = rowDescriptor?.configuration.selection.options , !options.isEmpty { + var selectedIndex: Int? + for (index, value) in options.enumerated() { + if value === selectedValue { + selectedIndex = index + break + } + } + if let index = selectedIndex { + picker.selectRow(index, inComponent: 0, animated: false) + } + } + } + } + + open override func firstResponderElement() -> UIResponder? { + return hiddenTextField + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormPickerCell else { return } + + if selectedRow.rowDescriptor?.value == nil { + guard let options = selectedRow.rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + let value = options[0] + selectedRow.rowDescriptor?.value = value + row.valueLabel.text = selectedRow.rowDescriptor?.configuration.selection.optionTitleClosure?(value) + row.hiddenTextField.becomeFirstResponder() + } else { + guard let value = selectedRow.rowDescriptor?.value else { return } + row.valueLabel.text = selectedRow.rowDescriptor?.configuration.selection.optionTitleClosure?(value) + row.hiddenTextField.becomeFirstResponder() + } + } + + // MARK: UIPickerViewDelegate + + open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return nil } + guard row < options.count else { return nil } + return rowDescriptor?.configuration.selection.optionTitleClosure?(options[row]) + } + + open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + guard row < options.count else { return } + let newValue = options[row] + rowDescriptor?.value = newValue + valueLabel.text = rowDescriptor?.configuration.selection.optionTitleClosure?(newValue) + } + + // MARK: UIPickerViewDataSource + + open func numberOfComponents(in pickerView: UIPickerView) -> Int { + return 1 + } + + open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + guard let options = rowDescriptor?.configuration.selection.options else { return 0 } + return options.count + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift new file mode 100644 index 0000000..99fe74b --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSegmentedControlCell.swift @@ -0,0 +1,100 @@ +// +// FormSegmentedControlCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +@objc(FormSegmentedControlCell) +open class FormSegmentedControlCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let segmentedControl = UISegmentedControl() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject] = [] + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + segmentedControl.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 500), for: .horizontal) + segmentedControl.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(segmentedControl) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + segmentedControl.addTarget(self, action: #selector(FormSegmentedControlCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + updateSegmentedControl() + + guard let value = rowDescriptor?.value else { return } + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + + var idx = 0 + for optionValue in options { + if optionValue === value { + segmentedControl.selectedSegmentIndex = idx + break + } + idx += 1 + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl] + } + + open override func defaultVisualConstraints() -> [String] { + if let text = titleLabel.text , text.count > 0 { + return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"] + } else { + return ["H:|-16-[segmentedControl]-16-|"] + } + } + + // MARK: Actions + + @objc internal func valueChanged(_ sender: UISegmentedControl) { + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + let value = options[sender.selectedSegmentIndex] + rowDescriptor?.value = value + } + + // MARK: Private + + fileprivate func updateSegmentedControl() { + segmentedControl.removeAllSegments() + + guard let options = rowDescriptor?.configuration.selection.options , !options.isEmpty else { return } + + var idx = 0 + for value in options { + let title = rowDescriptor?.configuration.selection.optionTitleClosure?(value) + segmentedControl.insertSegment(withTitle: title, at: idx, animated: false) + idx += 1 + } + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSelectorCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSelectorCell.swift new file mode 100644 index 0000000..5e7f956 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSelectorCell.swift @@ -0,0 +1,63 @@ +// +// FormSelectorCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormSelectorCell: FormValueCell { + + // MARK: FormBaseCell + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + var title: String? + if let multipleValues = rowDescriptor?.value as? [AnyObject] { + var multipleValuesTitle = "" + for (index, selectedValue) in multipleValues.enumerated() { + guard let selectedValueTitle = rowDescriptor?.configuration.selection.optionTitleClosure?(selectedValue) else { continue } + if index != 0 { + multipleValuesTitle += ", " + } + multipleValuesTitle += selectedValueTitle + } + title = multipleValuesTitle + } else if let singleValue = rowDescriptor?.value { + title = rowDescriptor?.configuration.selection.optionTitleClosure?(singleValue) + } + + if let title = title , title.count > 0 { + valueLabel.text = title + valueLabel.textColor = UIColor.black + } else { + valueLabel.text = rowDescriptor?.configuration.cell.placeholder + valueLabel.textColor = UIColor.lightGray + } + } + + open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { + guard let row = selectedRow as? FormSelectorCell else { return } + + formViewController.view.endEditing(true) + + var selectorControllerClass: UIViewController.Type + + if let controllerClass = row.rowDescriptor?.configuration.selection.controllerClass as? UIViewController.Type { + selectorControllerClass = controllerClass + } else { // fallback to default cell class + selectorControllerClass = FormOptionsSelectorController.self + } + + let selectorController = selectorControllerClass.init() + guard let formRowDescriptorViewController = selectorController as? FormSelector else { return } + + formRowDescriptorViewController.formCell = row + formViewController.navigationController?.pushViewController(selectorController, animated: true) + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSliderCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSliderCell.swift new file mode 100644 index 0000000..5f7c0d5 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSliderCell.swift @@ -0,0 +1,75 @@ +// +// FormSliderCell.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 23/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +import UIKit + +open class FormSliderCell: FormTitleCell { + + // MARK: Cell views + + @objc public let sliderView = UISlider() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + sliderView.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(sliderView) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: sliderView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + sliderView.addTarget(self, action: #selector(FormSliderCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let maximumValue = rowDescriptor?.configuration.stepper.maximumValue { sliderView.maximumValue = Float(maximumValue) } + if let minimumValue = rowDescriptor?.configuration.stepper.minimumValue { sliderView.minimumValue = Float(minimumValue) } + if let continuous = rowDescriptor?.configuration.stepper.continuous { sliderView.isContinuous = continuous } + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Float { + sliderView.value = value + } else { + sliderView.value = sliderView.minimumValue + rowDescriptor?.value = sliderView.minimumValue as AnyObject + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "sliderView" : sliderView] + } + + open override func defaultVisualConstraints() -> [String] { + var constraints: [String] = [] + + constraints.append("V:|[titleLabel]|") + constraints.append("H:|-16-[titleLabel]-16-[sliderView]-16-|") + + return constraints + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISlider) { + rowDescriptor?.value = sliderView.value as AnyObject + update() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormStepperCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormStepperCell.swift new file mode 100644 index 0000000..5780e01 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormStepperCell.swift @@ -0,0 +1,82 @@ +// +// FormStepperCell.swift +// SwiftFormsApplication +// +// Created by Miguel Angel Ortuno Ortuno on 23/5/15. +// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. +// + +import UIKit + +open class FormStepperCell: FormTitleCell { + + // MARK: Cell views + + public let stepperView = UIStepper() + public let countLabel = UILabel() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + stepperView.translatesAutoresizingMaskIntoConstraints = false + countLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + countLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(countLabel) + contentView.addSubview(stepperView) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: stepperView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + stepperView.addTarget(self, action: #selector(FormStepperCell.valueChanged(_:)), for: .valueChanged) + } + + open override func update() { + super.update() + + if let maximumValue = rowDescriptor?.configuration.stepper.maximumValue { stepperView.maximumValue = maximumValue } + if let minimumValue = rowDescriptor?.configuration.stepper.minimumValue { stepperView.minimumValue = minimumValue } + if let steps = rowDescriptor?.configuration.stepper.steps { stepperView.stepValue = steps } + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Double { + stepperView.value = value + countLabel.text = String(value) + } else { + stepperView.value = stepperView.minimumValue + rowDescriptor?.value = stepperView.minimumValue as AnyObject + countLabel.text = String(stepperView.minimumValue) + } + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "countLabel" : countLabel, "stepperView" : stepperView] + } + + open override func defaultVisualConstraints() -> [String] { + var constraints: [String] = [] + + constraints.append("V:|[titleLabel]|") + constraints.append("V:|[countLabel]|") + + constraints.append("H:|-16-[titleLabel][countLabel]-[stepperView]-16-|") + return constraints + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISwitch) { + rowDescriptor?.value = stepperView.value as AnyObject + update() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSwitchCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSwitchCell.swift new file mode 100644 index 0000000..1a49db5 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormSwitchCell.swift @@ -0,0 +1,47 @@ +// +// FormSwitchCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 21/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormSwitchCell: FormTitleCell { + + // MARK: Cell views + + public let switchView = UISwitch() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + switchView.addTarget(self, action: #selector(FormSwitchCell.valueChanged(_:)), for: .valueChanged) + accessoryView = switchView + } + + open override func update() { + super.update() + + titleLabel.text = rowDescriptor?.title + + if let value = rowDescriptor?.value as? Bool { + switchView.isOn = value + } else { + switchView.isOn = false + rowDescriptor?.value = false as AnyObject + } + } + + // MARK: Actions + + @objc internal func valueChanged(_: UISwitch) { + rowDescriptor?.value = switchView.isOn as AnyObject + update() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift new file mode 100644 index 0000000..3916ce1 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift @@ -0,0 +1,148 @@ +// +// FormTextFieldCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTextFieldCell: FormBaseCell { + + // MARK: Cell views + + public let titleLabel = UILabel() + @objc public let textField = UITextField() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject] = [] + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + textField.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + textField.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(textField) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + + textField.addTarget(self, action: #selector(FormTextFieldCell.editingChanged(_:)), for: .editingChanged) + } + + open override func update() { + super.update() + + if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && textField.inputAccessoryView == nil { + textField.inputAccessoryView = inputAccesoryView() + } + + titleLabel.text = rowDescriptor?.title + textField.text = rowDescriptor?.value as? String + textField.placeholder = rowDescriptor?.configuration.cell.placeholder + + textField.isSecureTextEntry = false + textField.clearButtonMode = .whileEditing + + if let type = rowDescriptor?.type { + switch type { + case .text: + textField.autocorrectionType = .default + textField.autocapitalizationType = .sentences + textField.keyboardType = .default + case .number: + textField.keyboardType = .numberPad + case .numbersAndPunctuation: + textField.keyboardType = .numbersAndPunctuation + case .decimal: + textField.keyboardType = .decimalPad + case .name: + textField.autocorrectionType = .no + textField.autocapitalizationType = .words + textField.keyboardType = .default + case .phone: + textField.keyboardType = .phonePad + case .namePhone: + textField.autocorrectionType = .no + textField.autocapitalizationType = .words + textField.keyboardType = .namePhonePad + case .url: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .URL + case .twitter: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .twitter + case .email: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .emailAddress + case .asciiCapable: + textField.autocorrectionType = .no + textField.autocapitalizationType = .none + textField.keyboardType = .asciiCapable + case .password: + textField.isSecureTextEntry = true + textField.clearsOnBeginEditing = false + default: + break + } + } + } + + open override func constraintsViews() -> [String : UIView] { + var views = ["titleLabel" : titleLabel, "textField" : textField] + if self.imageView!.image != nil { + views["imageView"] = imageView + } + return views + } + + open override func defaultVisualConstraints() -> [String] { + if self.imageView!.image != nil { + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:[imageView]-[titleLabel]-[textField]-16-|"] + } else { + return ["H:[imageView]-[textField]-16-|"] + } + } else { + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:|-16-[titleLabel]-[textField]-16-|"] + } else { + return ["H:|-16-[textField]-16-|"] + } + } + } + + open override func firstResponderElement() -> UIResponder? { + return textField + } + + open override class func formRowCanBecomeFirstResponder() -> Bool { + return true + } + + // MARK: Actions + + @objc func editingChanged(_ sender: UITextField) { + guard let text = sender.text, text.count > 0 else { rowDescriptor?.value = nil; update(); return } + rowDescriptor?.value = text as AnyObject + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextViewCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextViewCell.swift new file mode 100644 index 0000000..f507603 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/FormTextViewCell.swift @@ -0,0 +1,96 @@ +// +// FormTextViewCell.swift +// SwiftForms +// +// Created by Joey Padot on 12/6/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTextViewCell : FormBaseCell, UITextViewDelegate { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let textField = UITextView() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject]! + + // MARK: Class Funcs + + open override class func formRowCellHeight() -> CGFloat { + return 110.0 + } + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + selectionStyle = .none + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + textField.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + textField.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + contentView.addSubview(titleLabel) + contentView.addSubview(textField) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1.0, constant: 0.0)) + + textField.delegate = self + } + + open override func update() { + + titleLabel.text = rowDescriptor?.title + textField.text = rowDescriptor?.value as? String + + textField.isSecureTextEntry = false + textField.autocorrectionType = .default + textField.autocapitalizationType = .sentences + textField.keyboardType = .default + } + + open override func constraintsViews() -> [String : UIView] { + var views = ["titleLabel" : titleLabel, "textField" : textField] + if self.imageView!.image != nil { + views["imageView"] = imageView + } + return views + } + + open override func defaultVisualConstraints() -> [String] { + if self.imageView!.image != nil { + if let text = titleLabel.text , text.count > 0 { + return ["H:[imageView]-[titleLabel]-[textField]-16-|"] + } else { + return ["H:[imageView]-[textField]-16-|"] + } + } else { + if let text = titleLabel.text , text.count > 0 { + return ["H:|-16-[titleLabel]-[textField]-16-|"] + } else { + return ["H:|-16-[textField]-16-|"] + } + } + } + + // MARK: UITextViewDelegate + + open func textViewDidChange(_ textView: UITextView) { + guard let text = textView.text , text.count > 0 else { rowDescriptor?.value = nil; update(); return } + rowDescriptor?.value = text as AnyObject + update() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift new file mode 100644 index 0000000..24cf005 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormBaseCell.swift @@ -0,0 +1,118 @@ +// +// FormBaseCell.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormBaseCell: UITableViewCell { + + // MARK: Properties + + open var rowDescriptor: FormRowDescriptor? { + didSet { + self.update() + } + } + + open weak var formViewController: FormViewController? + + fileprivate var customConstraints: [NSLayoutConstraint] = [] + + // MARK: Init + + public required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + } + + public required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + // MARK: Public interface + + open func configure() { + /// override + } + + open func update() { + /// override + } + + open func defaultVisualConstraints() -> [String] { + /// override + return [] + } + + open func constraintsViews() -> [String : UIView] { + /// override + return [:] + } + + open func firstResponderElement() -> UIResponder? { + /// override + return nil + } + + open func inputAccesoryView() -> UIToolbar { + + let actionBar = UIToolbar() + actionBar.isTranslucent = true + actionBar.sizeToFit() + actionBar.barStyle = .default + + let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FormBaseCell.handleDoneAction(_:))) + let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) + actionBar.items = [flexible, doneButton] + + return actionBar + } + + @objc internal func handleDoneAction(_: UIBarButtonItem) { + firstResponderElement()?.resignFirstResponder() + } + + open class func formRowCellHeight() -> CGFloat { + return 44.0 + } + + open class func formRowCanBecomeFirstResponder() -> Bool { + return false + } + + open class func formViewController(_ formViewController: FormViewController, didSelectRow: FormBaseCell) { + } + + // MARK: Constraints + + open override func updateConstraints() { + if customConstraints.count > 0 { + contentView.removeConstraints(customConstraints) + } + + let views = constraintsViews() + + customConstraints.removeAll() + + var visualConstraints = [String]() + + if let visualConstraintsClosure = rowDescriptor?.configuration.cell.visualConstraintsClosure { + visualConstraints = visualConstraintsClosure(self) + } else { + visualConstraints = defaultVisualConstraints() + } + + for visualConstraint in visualConstraints { + let constraints = NSLayoutConstraint.constraints(withVisualFormat: visualConstraint, options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views) + for constraint in constraints { + customConstraints.append(constraint) + } + } + + contentView.addConstraints(customConstraints) + super.updateConstraints() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift new file mode 100644 index 0000000..8cadad5 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormTitleCell.swift @@ -0,0 +1,38 @@ +// +// FormTitleCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 13/11/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormTitleCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + // apply constant constraints + contentView.addSubview(titleLabel) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel] + } + + open override func defaultVisualConstraints() -> [String] { + return ["H:|-16-[titleLabel]-16-|"] + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormValueCell.swift b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormValueCell.swift new file mode 100644 index 0000000..1bc7820 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/cells/base/FormValueCell.swift @@ -0,0 +1,70 @@ +// +// FormValueCell.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 13/11/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormValueCell: FormBaseCell { + + // MARK: Cell views + + @objc public let titleLabel = UILabel() + @objc public let valueLabel = UILabel() + + // MARK: Properties + + fileprivate var customConstraints: [AnyObject]! + + // MARK: FormBaseCell + + open override func configure() { + super.configure() + + accessoryType = .disclosureIndicator + + titleLabel.translatesAutoresizingMaskIntoConstraints = false + valueLabel.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + valueLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) + + valueLabel.textColor = UIColor.lightGray + valueLabel.textAlignment = .right + + contentView.addSubview(titleLabel) + contentView.addSubview(valueLabel) + + titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) + titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) + + // apply constant constraints + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) + } + + open override func constraintsViews() -> [String : UIView] { + return ["titleLabel" : titleLabel, "valueLabel" : valueLabel] + } + + open override func defaultVisualConstraints() -> [String] { + + // apply default constraints + var rightPadding = 0 + if accessoryType == .none { + rightPadding = 16 + } + + if titleLabel.text != nil && (titleLabel.text!).count > 0 { + return ["H:|-16-[titleLabel]-[valueLabel]-\(rightPadding)-|"] + } + else { + return ["H:|-16-[valueLabel]-\(rightPadding)-|"] + } + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift new file mode 100644 index 0000000..1146359 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormOptionsViewController.swift @@ -0,0 +1,125 @@ +// +// FormOptionsSelectorController.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormOptionsSelectorController: UITableViewController, FormSelector { + + // MARK: FormSelector + + open var formCell: FormBaseCell? + + // MARK: Init + + public init() { + super.init(style: .grouped) + } + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + } + + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + open override func viewDidLoad() { + super.viewDidLoad() + self.navigationItem.title = formCell?.rowDescriptor?.title + } + + // MARK: UITableViewDataSource + + open override func numberOfSections(in tableView: UITableView) -> Int { + return 1 + } + + open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + guard let options = formCell?.rowDescriptor?.configuration.selection.options , !options.isEmpty else { return 0 } + return options.count + } + + open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + return 0.1 + } + + open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + + let reuseIdentifier = NSStringFromClass(type(of: self)) + + var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) + if cell == nil { + cell = UITableViewCell(style: .default, reuseIdentifier: reuseIdentifier) + } + + let options = formCell!.rowDescriptor!.configuration.selection.options + let optionValue = options[(indexPath as NSIndexPath).row] + + cell?.textLabel?.text = formCell?.rowDescriptor?.configuration.selection.optionTitleClosure?(optionValue) + + if let selectedOptions = formCell?.rowDescriptor?.value as? [AnyObject] { + if let _ = selectedOptions.index(where: { $0 === optionValue }) { + cell?.accessoryType = .checkmark + } else { + cell?.accessoryType = .none + } + + } else if let selectedOption = formCell?.rowDescriptor?.value { + if optionValue === selectedOption { + cell?.accessoryType = .checkmark + } else { + cell?.accessoryType = .none + } + } + + return cell! + } + + // MARK: UITableViewDelegate + + open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + + let cell = tableView.cellForRow(at: indexPath) + + var allowsMultipleSelection = false + if let allowsMultipleSelectionValue = formCell?.rowDescriptor?.configuration.selection.allowsMultipleSelection { + allowsMultipleSelection = allowsMultipleSelectionValue + } + + let options = formCell!.rowDescriptor!.configuration.selection.options + let selectedOption = options[(indexPath as NSIndexPath).row] + + if allowsMultipleSelection { + if var selectedOptions = formCell?.rowDescriptor?.value as? [AnyObject] { + if let index = selectedOptions.index(where: { $0 === selectedOption }) { + selectedOptions.remove(at: index) + cell?.accessoryType = .none + } else { + selectedOptions.append(selectedOption) + cell?.accessoryType = .checkmark + } + formCell?.rowDescriptor?.value = selectedOptions as AnyObject + + } else { + formCell?.rowDescriptor?.value = [AnyObject](arrayLiteral: selectedOption) as AnyObject + cell?.accessoryType = .checkmark + } + + } else { + formCell?.rowDescriptor?.value = selectedOption + } + + formCell?.update() + + if allowsMultipleSelection { + tableView.deselectRow(at: indexPath, animated: true) + } else { + let _ = self.navigationController?.popViewController(animated: true) + } + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormSelector.swift b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormSelector.swift new file mode 100644 index 0000000..0032995 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormSelector.swift @@ -0,0 +1,13 @@ +// +// FormSelector.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +@objc public protocol FormSelector: NSObjectProtocol { + var formCell: FormBaseCell? { get set } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormViewController.swift b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormViewController.swift new file mode 100644 index 0000000..257f82b --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/controllers/FormViewController.swift @@ -0,0 +1,225 @@ +// +// FormViewController.swift +// SwiftForms +// +// Created by Miguel Angel Ortuño on 20/08/14. +// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +open class FormViewController : UITableViewController { + + private static var __once: () = { + FormViewController.defaultCellClasses[.text] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.label] = FormLabelCell.self + FormViewController.defaultCellClasses[.number] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.numbersAndPunctuation] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.decimal] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.name] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.phone] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.url] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.twitter] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.namePhone] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.email] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.asciiCapable] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.password] = FormTextFieldCell.self + FormViewController.defaultCellClasses[.button] = FormButtonCell.self + FormViewController.defaultCellClasses[.booleanSwitch] = FormSwitchCell.self + FormViewController.defaultCellClasses[.booleanCheck] = FormCheckCell.self + FormViewController.defaultCellClasses[.segmentedControl] = FormSegmentedControlCell.self + FormViewController.defaultCellClasses[.picker] = FormPickerCell.self + FormViewController.defaultCellClasses[.date] = FormDateCell.self + FormViewController.defaultCellClasses[.time] = FormDateCell.self + FormViewController.defaultCellClasses[.dateAndTime] = FormDateCell.self + FormViewController.defaultCellClasses[.stepper] = FormStepperCell.self + FormViewController.defaultCellClasses[.slider] = FormSliderCell.self + FormViewController.defaultCellClasses[.multipleSelector] = FormSelectorCell.self + FormViewController.defaultCellClasses[.multilineText] = FormTextViewCell.self + }() + + // MARK: Class variables + + fileprivate static var onceDefaultCellClass: Int = 0 + fileprivate static var defaultCellClasses: [FormRowDescriptor.RowType : FormBaseCell.Type] = [:] + + // MARK: Properties + + open var form = FormDescriptor() + + // MARK: Init + + public convenience init() { + self.init(style: .grouped) + } + + public convenience init(form: FormDescriptor) { + self.init(style: .grouped) + self.form = form + } + + public override init(style: UITableView.Style) { + super.init(style: style) + } + + public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + public required init(coder aDecoder: NSCoder) { + super.init(coder: aDecoder)! + } + + // MARK: View life cycle + + open override func viewDidLoad() { + super.viewDidLoad() + navigationItem.title = form.title + } + + // MARK: Public interface + + open func valueForTag(_ tag: String) -> AnyObject? { + for section in form.sections { + for row in section.rows { + if row.tag == tag { + return row.value + } + } + } + return nil + } + + open func setValue(_ value: AnyObject, forTag tag: String) { + for (sectionIndex, section) in form.sections.enumerated() { + for (rowIndex, row) in section.rows.enumerated() { + if row.tag == tag { + form.sections[sectionIndex].rows[rowIndex].value = value + if let cell = self.tableView.cellForRow(at: IndexPath(row: rowIndex, section: sectionIndex)) as? FormBaseCell { + cell.update() + } + return + } + } + } + } + + // MARK: UITableViewDataSource + + open override func numberOfSections(in tableView: UITableView) -> Int { + return form.sections.count + } + + open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return form.sections[section].rows.count + } + + open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) + + let reuseIdentifier = NSStringFromClass(formBaseCellClass!) + + var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? FormBaseCell + if cell == nil { + cell = formBaseCellClass?.init(style: .default, reuseIdentifier: reuseIdentifier) + cell?.formViewController = self + cell?.configure() + } + + cell?.rowDescriptor = rowDescriptor + + // apply cell custom design + for (keyPath, value) in rowDescriptor.configuration.cell.appearance { + cell?.setValue(value, forKeyPath: keyPath) + } + return cell! + } + + open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + return form.sections[section].headerTitle + } + + open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { + return form.sections[section].footerTitle + } + + open override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + guard let headerView = form.sections[section].headerView else { return nil } + return headerView + } + + open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { + guard let footerView = form.sections[section].footerView else { return nil } + return footerView + } + + open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + guard let headerView = form.sections[section].headerView , headerView.translatesAutoresizingMaskIntoConstraints else { + return form.sections[section].headerViewHeight + } + return headerView.frame.size.height + } + + open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { + guard let footerView = form.sections[section].footerView , footerView.translatesAutoresizingMaskIntoConstraints else { + return form.sections[section].footerViewHeight + } + return footerView.frame.size.height + } + + // MARK: UITableViewDelegate + + open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { + return formBaseCellClass.formRowCellHeight() + } + return super.tableView(tableView, heightForRowAt: indexPath) + } + + open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + + let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) + + if let selectedRow = tableView.cellForRow(at: indexPath) as? FormBaseCell { + if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { + formBaseCellClass.formViewController(self, didSelectRow: selectedRow) + } + } + + if let didSelectClosure = rowDescriptor.configuration.button.didSelectClosure { + didSelectClosure(rowDescriptor) + } + + tableView.deselectRow(at: indexPath, animated: true) + } + + fileprivate class func defaultCellClassForRowType(_ rowType: FormRowDescriptor.RowType) -> FormBaseCell.Type { + _ = FormViewController.__once + return FormViewController.defaultCellClasses[rowType]! + } + + fileprivate func formRowDescriptorAtIndexPath(_ indexPath: IndexPath) -> FormRowDescriptor { + + let section = form.sections[(indexPath as NSIndexPath).section] + let rowDescriptor = section.rows[(indexPath as NSIndexPath).row] + return rowDescriptor + } + + fileprivate func formBaseCellClassFromRowDescriptor(_ rowDescriptor: FormRowDescriptor) -> FormBaseCell.Type! { + + var formBaseCellClass: FormBaseCell.Type + + if let cellClass = rowDescriptor.configuration.cell.cellClass as? FormBaseCell.Type { + formBaseCellClass = cellClass + } else { + formBaseCellClass = FormViewController.defaultCellClassForRowType(rowDescriptor.type) + } + return formBaseCellClass + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift new file mode 100644 index 0000000..fbe7980 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift @@ -0,0 +1,58 @@ +// +// FormDescriptor.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormDescriptor { + + // MARK: Properties + + public var title: String + public var sections: [FormSectionDescriptor] = [] + + // MARK: Init + + public init() { + self.title = "" + } + + public init(title: String) { + self.title = title + } + + // MARK: Public + + public func formValues() -> [String : AnyObject] { + + var formValues: [String : AnyObject] = [:] + + for section in sections { + for row in section.rows { + if row.type != .button { + if let value = row.value { + formValues[row.tag] = value + } else { + formValues[row.tag] = NSNull() + } + } + } + } + return formValues + } + + public func validateForm() -> FormRowDescriptor? { + for section in sections { + for row in section.rows { + if row.configuration.cell.required && row.value == nil { + return row + } + } + } + return nil + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift new file mode 100644 index 0000000..9760ca3 --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormRowDescriptor.swift @@ -0,0 +1,159 @@ +// +// FormRowDescriptor.swift +// SwiftForms +// +// Created by Miguel Ángel Ortuño Ortuño on 23/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormRowDescriptor { + + // MARK: Types + + public enum RowType { + case unknown + case label + case text + case url + case number + case numbersAndPunctuation + case decimal + case name + case phone + case namePhone + case email + case twitter + case asciiCapable + case password + case button + case booleanSwitch + case booleanCheck + case segmentedControl + case picker + case date + case time + case dateAndTime + case stepper + case slider + case multipleSelector + case multilineText + } + + public struct CellConfiguration { + public var cellClass: AnyClass? + public var appearance: [String : AnyObject] + public var placeholder: String? + public var showsInputToolbar: Bool + public var required: Bool + public var willUpdateClosure: ((FormRowDescriptor) -> Void)? + public var didUpdateClosure: ((FormRowDescriptor) -> Void)? + public var visualConstraintsClosure: ((FormBaseCell) -> [String])? + + public init() { + cellClass = nil + appearance = [:] + placeholder = nil + showsInputToolbar = false + required = true + willUpdateClosure = nil + didUpdateClosure = nil + visualConstraintsClosure = nil + } + } + + public struct SelectionConfiguration { + public var controllerClass: AnyClass? + public var options: [AnyObject] + public var optionTitleClosure: ((AnyObject) -> String)? + public var allowsMultipleSelection: Bool + + public init() { + controllerClass = nil + options = [] + optionTitleClosure = nil + allowsMultipleSelection = false + } + } + + public struct ButtonConfiguration { + public var didSelectClosure: ((FormRowDescriptor) -> Void)? + + public init() { + didSelectClosure = nil + } + } + + public struct StepperConfiguration { + public var maximumValue: Double + public var minimumValue: Double + public var steps: Double + public var continuous: Bool + + public init() { + maximumValue = 0.0 + minimumValue = 0.0 + steps = 0.0 + continuous = false + } + } + + public struct DateConfiguration { + public var dateFormatter: DateFormatter? + } + + public struct RowConfiguration { + public var cell: CellConfiguration + public var selection: SelectionConfiguration + public var button: ButtonConfiguration + public var stepper: StepperConfiguration + public var date: DateConfiguration + public var userInfo: [String : AnyObject] + + init() { + cell = CellConfiguration() + selection = SelectionConfiguration() + button = ButtonConfiguration() + stepper = StepperConfiguration() + date = DateConfiguration() + userInfo = [:] + } + } + + // MARK: Properties + + public let tag: String + public let type: RowType + + public var title: String? + + public var value: AnyObject? { + willSet { + guard let willUpdateBlock = configuration.cell.willUpdateClosure else { return } + willUpdateBlock(self) + } + didSet { + guard let didUpdateBlock = configuration.cell.didUpdateClosure else { return } + didUpdateBlock(self) + } + } + + public var configuration: RowConfiguration + + // MARK: Init + + public init(tag: String, type: RowType, title: String, configuration: RowConfiguration) { + self.tag = tag + self.type = type + self.title = title + self.configuration = configuration + } + + public init(tag: String, type: RowType, title: String) { + self.tag = tag + self.type = type + self.title = title + self.configuration = RowConfiguration() + } +} diff --git a/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift new file mode 100644 index 0000000..eab041a --- /dev/null +++ b/My Mind/Pods/SwiftForms/SwiftForms/descriptors/FormSectionDescriptor.swift @@ -0,0 +1,32 @@ +// +// FormSectionDescriptor.swift +// SwiftForms +// +// Created by Miguel Angel Ortuno on 20/08/14. +// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. +// + +import UIKit + +public final class FormSectionDescriptor { + + // MARK: Properties + + public var rows: [FormRowDescriptor] = [] + + public var headerTitle: String? + public var footerTitle: String? + + public var headerView: UIView? + public var footerView: UIView? + + public var headerViewHeight: CGFloat = UITableView.automaticDimension + public var footerViewHeight: CGFloat = UITableView.automaticDimension + + // MARK: Init + + public init(headerTitle: String?, footerTitle: String?) { + self.headerTitle = headerTitle + self.footerTitle = footerTitle + } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-dummy.m b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-dummy.m new file mode 100644 index 0000000..63dc459 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FirebaseAuth : NSObject +@end +@implementation PodsDummy_FirebaseAuth +@end diff --git a/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-umbrella.h b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-umbrella.h new file mode 100644 index 0000000..f2c99f8 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth-umbrella.h @@ -0,0 +1,40 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FIRActionCodeSettings.h" +#import "FIRAdditionalUserInfo.h" +#import "FIRAuth.h" +#import "FIRAuthAPNSTokenType.h" +#import "FIRAuthCredential.h" +#import "FIRAuthDataResult.h" +#import "FIRAuthErrors.h" +#import "FIRAuthSettings.h" +#import "FIRAuthTokenResult.h" +#import "FIRAuthUIDelegate.h" +#import "FirebaseAuth.h" +#import "FirebaseAuthVersion.h" +#import "FIREmailAuthProvider.h" +#import "FIRFacebookAuthProvider.h" +#import "FIRGameCenterAuthProvider.h" +#import "FIRGitHubAuthProvider.h" +#import "FIRGoogleAuthProvider.h" +#import "FIROAuthProvider.h" +#import "FIRPhoneAuthCredential.h" +#import "FIRPhoneAuthProvider.h" +#import "FIRTwitterAuthProvider.h" +#import "FIRUser.h" +#import "FIRUserInfo.h" +#import "FIRUserMetadata.h" + +FOUNDATION_EXPORT double FirebaseAuthVersionNumber; +FOUNDATION_EXPORT const unsigned char FirebaseAuthVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.modulemap b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.modulemap new file mode 100644 index 0000000..7ee6c70 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseAuth { + umbrella header "FirebaseAuth-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.xcconfig b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.xcconfig new file mode 100644 index 0000000..c90a3d1 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseAuth/FirebaseAuth.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" +GCC_C_LANGUAGE_STANDARD = c99 +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 FIRAuth_VERSION=5.2.0 FIRAuth_MINOR_VERSION=5.2 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "SafariServices" -framework "Security" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FirebaseAuth +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-dummy.m b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-dummy.m new file mode 100644 index 0000000..4f1eb27 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FirebaseCore : NSObject +@end +@implementation PodsDummy_FirebaseCore +@end diff --git a/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-umbrella.h b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-umbrella.h new file mode 100644 index 0000000..791a7c0 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore-umbrella.h @@ -0,0 +1,22 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FIRAnalyticsConfiguration.h" +#import "FIRApp.h" +#import "FIRConfiguration.h" +#import "FirebaseCore.h" +#import "FIRLoggerLevel.h" +#import "FIROptions.h" + +FOUNDATION_EXPORT double FirebaseCoreVersionNumber; +FOUNDATION_EXPORT const unsigned char FirebaseCoreVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.modulemap b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.modulemap new file mode 100644 index 0000000..4c38b87 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseCore { + umbrella header "FirebaseCore-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.xcconfig b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.xcconfig new file mode 100644 index 0000000..ef0a9bc --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseCore/FirebaseCore.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" +GCC_C_LANGUAGE_STANDARD = c99 +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 FIRCore_VERSION=5.1.10 Firebase_VERSION=5.15.0 +OTHER_CFLAGS = $(inherited) -fno-autolink +OTHER_LDFLAGS = -framework "Foundation" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FirebaseCore +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-dummy.m b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-dummy.m new file mode 100644 index 0000000..40813e7 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FirebaseDatabase : NSObject +@end +@implementation PodsDummy_FirebaseDatabase +@end diff --git a/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-umbrella.h b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-umbrella.h new file mode 100644 index 0000000..b9b40ff --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase-umbrella.h @@ -0,0 +1,25 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FIRDatabase.h" +#import "FIRDatabaseQuery.h" +#import "FIRDatabaseReference.h" +#import "FIRDataEventType.h" +#import "FIRDataSnapshot.h" +#import "FirebaseDatabase.h" +#import "FIRMutableData.h" +#import "FIRServerValue.h" +#import "FIRTransactionResult.h" + +FOUNDATION_EXPORT double FirebaseDatabaseVersionNumber; +FOUNDATION_EXPORT const unsigned char FirebaseDatabaseVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.modulemap b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.modulemap new file mode 100644 index 0000000..7424a95 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseDatabase { + umbrella header "FirebaseDatabase-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.xcconfig b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.xcconfig new file mode 100644 index 0000000..7708540 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseDatabase/FirebaseDatabase.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" +GCC_C_LANGUAGE_STANDARD = c99 +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 FIRDatabase_VERSION=5.0.4 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -l"c++" -l"icucore" -framework "CFNetwork" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FirebaseDatabase +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-dummy.m b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-dummy.m new file mode 100644 index 0000000..ec94549 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FirebaseMessaging : NSObject +@end +@implementation PodsDummy_FirebaseMessaging +@end diff --git a/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-umbrella.h b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-umbrella.h new file mode 100644 index 0000000..c2f51ed --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging-umbrella.h @@ -0,0 +1,18 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FirebaseMessaging.h" +#import "FIRMessaging.h" + +FOUNDATION_EXPORT double FirebaseMessagingVersionNumber; +FOUNDATION_EXPORT const unsigned char FirebaseMessagingVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.modulemap b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.modulemap new file mode 100644 index 0000000..4ab5827 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseMessaging { + umbrella header "FirebaseMessaging-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.xcconfig b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.xcconfig new file mode 100644 index 0000000..17f6448 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseMessaging/FirebaseMessaging.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" +GCC_C_LANGUAGE_STANDARD = c99 +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 FIRMessaging_LIB_VERSION=3.2.2 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -l"sqlite3" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FirebaseMessaging +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-dummy.m b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-dummy.m new file mode 100644 index 0000000..15945ee --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FirebaseStorage : NSObject +@end +@implementation PodsDummy_FirebaseStorage +@end diff --git a/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-umbrella.h b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-umbrella.h new file mode 100644 index 0000000..93cc60a --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage-umbrella.h @@ -0,0 +1,26 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FirebaseStorage.h" +#import "FIRStorage.h" +#import "FIRStorageConstants.h" +#import "FIRStorageDownloadTask.h" +#import "FIRStorageMetadata.h" +#import "FIRStorageObservableTask.h" +#import "FIRStorageReference.h" +#import "FIRStorageTask.h" +#import "FIRStorageTaskSnapshot.h" +#import "FIRStorageUploadTask.h" + +FOUNDATION_EXPORT double FirebaseStorageVersionNumber; +FOUNDATION_EXPORT const unsigned char FirebaseStorageVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.modulemap b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.modulemap new file mode 100644 index 0000000..627ff18 --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.modulemap @@ -0,0 +1,6 @@ +framework module FirebaseStorage { + umbrella header "FirebaseStorage-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.xcconfig b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.xcconfig new file mode 100644 index 0000000..b53158d --- /dev/null +++ b/My Mind/Pods/Target Support Files/FirebaseStorage/FirebaseStorage.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" +GCC_C_LANGUAGE_STANDARD = c99 +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 FIRStorage_VERSION=3.0.3 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "MobileCoreServices" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FirebaseStorage +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m new file mode 100644 index 0000000..13d68b3 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_GTMSessionFetcher : NSObject +@end +@implementation PodsDummy_GTMSessionFetcher +@end diff --git a/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h new file mode 100644 index 0000000..1c0b7b8 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h @@ -0,0 +1,20 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "GTMSessionFetcher.h" +#import "GTMSessionFetcherLogging.h" +#import "GTMSessionFetcherService.h" +#import "GTMSessionUploadFetcher.h" + +FOUNDATION_EXPORT double GTMSessionFetcherVersionNumber; +FOUNDATION_EXPORT const unsigned char GTMSessionFetcherVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap new file mode 100644 index 0000000..5121a4d --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap @@ -0,0 +1,6 @@ +framework module GTMSessionFetcher { + umbrella header "GTMSessionFetcher-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig new file mode 100644 index 0000000..53566fd --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "Security" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/GTMSessionFetcher +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/GTMSessionFetcher/Info.plist b/My Mind/Pods/Target Support Files/GTMSessionFetcher/Info.plist new file mode 100644 index 0000000..19f73ea --- /dev/null +++ b/My Mind/Pods/Target Support Files/GTMSessionFetcher/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.2.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-dummy.m b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-dummy.m new file mode 100644 index 0000000..98ac4e9 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_GoogleUtilities : NSObject +@end +@implementation PodsDummy_GoogleUtilities +@end diff --git a/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-prefix.pch b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-umbrella.h b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-umbrella.h new file mode 100644 index 0000000..508e631 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities-umbrella.h @@ -0,0 +1,19 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "GULLoggerLevel.h" +#import "GULLoggerCodes.h" +#import "GULNSData+zlib.h" + +FOUNDATION_EXPORT double GoogleUtilitiesVersionNumber; +FOUNDATION_EXPORT const unsigned char GoogleUtilitiesVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.modulemap b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.modulemap new file mode 100644 index 0000000..491dd0a --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.modulemap @@ -0,0 +1,6 @@ +framework module GoogleUtilities { + umbrella header "GoogleUtilities-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.xcconfig b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.xcconfig new file mode 100644 index 0000000..dd562e2 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/GoogleUtilities.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -l"z" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/GoogleUtilities +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/GoogleUtilities/Info.plist b/My Mind/Pods/Target Support Files/GoogleUtilities/Info.plist new file mode 100644 index 0000000..afb56d6 --- /dev/null +++ b/My Mind/Pods/Target Support Files/GoogleUtilities/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.3.6 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Info.plist b/My Mind/Pods/Target Support Files/Pods-My Mind/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Info.plist @@ -0,0 +1,26 @@ + + + + + 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/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.markdown b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.markdown new file mode 100644 index 0000000..896ae8d --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.markdown @@ -0,0 +1,1989 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Firebase + +Copyright 2018 Google + +## FirebaseAnalytics + +Copyright 2018 Google + +## FirebaseAnalyticsInterop + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseAuth + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseAuthInterop + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseCore + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseDatabase + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseInstanceID + +Copyright 2018 Google + +## FirebaseMessaging + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## FirebaseStorage + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## GTMSessionFetcher + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## GoogleAppMeasurement + +Copyright 2018 Google + +## GoogleUtilities + + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## Protobuf + +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + + +## SwiftForms + +The MIT License (MIT) + +Copyright (c) 2014 Xmartlabs ( http://xmartlabs.com ) +Copyright (c) 2014 Miguel Ángel Ortuño ( ortuman@gmail.com ) + +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. + + +## leveldb-library + +Copyright (c) 2011 The LevelDB Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. + + +## nanopb + +Copyright (c) 2011 Petteri Aimonen + +This software is provided 'as-is', without any express or +implied warranty. In no event will the authors be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. + +Generated by CocoaPods - https://cocoapods.org diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.plist b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.plist new file mode 100644 index 0000000..668c212 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-acknowledgements.plist @@ -0,0 +1,2117 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright 2018 Google + License + Copyright + Title + Firebase + Type + PSGroupSpecifier + + + FooterText + Copyright 2018 Google + License + Copyright + Title + FirebaseAnalytics + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseAnalyticsInterop + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseAuth + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseAuthInterop + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseCore + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseDatabase + Type + PSGroupSpecifier + + + FooterText + Copyright 2018 Google + License + Copyright + Title + FirebaseInstanceID + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseMessaging + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + FirebaseStorage + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + GTMSessionFetcher + Type + PSGroupSpecifier + + + FooterText + Copyright 2018 Google + License + Copyright + Title + GoogleAppMeasurement + Type + PSGroupSpecifier + + + FooterText + + 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + GoogleUtilities + Type + PSGroupSpecifier + + + FooterText + Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + + License + 3-Clause BSD License + Title + Protobuf + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 Xmartlabs ( http://xmartlabs.com ) +Copyright (c) 2014 Miguel Ángel Ortuño ( ortuman@gmail.com ) + +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 + SwiftForms + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011 The LevelDB Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. + + License + New BSD + Title + leveldb-library + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011 Petteri Aimonen <jpa at nanopb.mail.kapsi.fi> + +This software is provided 'as-is', without any express or +implied warranty. In no event will the authors be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. + + License + zlib + Title + nanopb + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-dummy.m b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-dummy.m new file mode 100644 index 0000000..0ed997e --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_My_Mind : NSObject +@end +@implementation PodsDummy_Pods_My_Mind +@end diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-frameworks.sh b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-frameworks.sh new file mode 100755 index 0000000..2c39c98 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-frameworks.sh @@ -0,0 +1,163 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +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}" + 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 && exit ${PIPESTATUS[0]}) + 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 +} + +# 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_identitiy + 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" || exit 1 + 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}/GTMSessionFetcher/GTMSessionFetcher.framework" + install_framework "${BUILT_PRODUCTS_DIR}/GoogleUtilities/GoogleUtilities.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Protobuf/Protobuf.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftForms/SwiftForms.framework" + install_framework "${BUILT_PRODUCTS_DIR}/leveldb-library/leveldb.framework" + install_framework "${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework" + install_framework "${BUILT_PRODUCTS_DIR}/GoogleUtilities/GoogleUtilities.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Protobuf/Protobuf.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftForms/SwiftForms.framework" + install_framework "${BUILT_PRODUCTS_DIR}/leveldb-library/leveldb.framework" + install_framework "${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-resources.sh b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-resources.sh new file mode 100755 index 0000000..345301f --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-resources.sh @@ -0,0 +1,118 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then + # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy + # resources to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +# 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 .*.??????") + +case "${TARGETED_DEVICE_FAMILY:-}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" || true + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + else + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" + fi +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-umbrella.h b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-umbrella.h new file mode 100644 index 0000000..1220131 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind-umbrella.h @@ -0,0 +1,16 @@ +#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_My_MindVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_My_MindVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.debug.xcconfig b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.debug.xcconfig new file mode 100644 index 0000000..0da8a50 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.debug.xcconfig @@ -0,0 +1,12 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 $(inherited) PB_FIELD_32BIT=1 PB_NO_PACKED_STRUCTS=1 PB_ENABLE_MALLOC=1 +HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FIRAnalyticsConnector" -framework "FirebaseAnalytics" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseCoreDiagnostics" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleAppMeasurement" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.modulemap b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.modulemap new file mode 100644 index 0000000..d34bdf8 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.modulemap @@ -0,0 +1,6 @@ +framework module Pods_My_Mind { + umbrella header "Pods-My Mind-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.release.xcconfig b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.release.xcconfig new file mode 100644 index 0000000..0da8a50 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My Mind/Pods-My Mind.release.xcconfig @@ -0,0 +1,12 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 $(inherited) PB_FIELD_32BIT=1 PB_NO_PACKED_STRUCTS=1 PB_ENABLE_MALLOC=1 +HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FIRAnalyticsConnector" -framework "FirebaseAnalytics" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseCoreDiagnostics" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleAppMeasurement" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Info.plist b/My Mind/Pods/Target Support Files/Pods-My MindTests/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Info.plist @@ -0,0 +1,26 @@ + + + + + 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/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.markdown b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.markdown new file mode 100644 index 0000000..102af75 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.plist b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.plist new file mode 100644 index 0000000..7acbad1 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-dummy.m b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-dummy.m new file mode 100644 index 0000000..f84b2a7 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_My_MindTests : NSObject +@end +@implementation PodsDummy_Pods_My_MindTests +@end diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-frameworks.sh b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-frameworks.sh new file mode 100755 index 0000000..08e3eaa --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-frameworks.sh @@ -0,0 +1,146 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +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}" + 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 && exit ${PIPESTATUS[0]}) + 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 +} + +# 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_identitiy + 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" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=1 +} + +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-resources.sh b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-resources.sh new file mode 100755 index 0000000..345301f --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-resources.sh @@ -0,0 +1,118 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then + # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy + # resources to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +# 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 .*.??????") + +case "${TARGETED_DEVICE_FAMILY:-}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" || true + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + else + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" + fi +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-umbrella.h b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-umbrella.h new file mode 100644 index 0000000..e44f227 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests-umbrella.h @@ -0,0 +1,16 @@ +#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_My_MindTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_My_MindTestsVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.debug.xcconfig b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.debug.xcconfig new file mode 100644 index 0000000..20be3ff --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.debug.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.modulemap b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.modulemap new file mode 100644 index 0000000..6fa4ca3 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_My_MindTests { + umbrella header "Pods-My MindTests-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.release.xcconfig b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.release.xcconfig new file mode 100644 index 0000000..20be3ff --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindTests/Pods-My MindTests.release.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Info.plist b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Info.plist @@ -0,0 +1,26 @@ + + + + + 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/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.markdown b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.markdown new file mode 100644 index 0000000..102af75 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.plist b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.plist new file mode 100644 index 0000000..7acbad1 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-dummy.m b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-dummy.m new file mode 100644 index 0000000..bc15bcd --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_My_MindUITests : NSObject +@end +@implementation PodsDummy_Pods_My_MindUITests +@end diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-frameworks.sh b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-frameworks.sh new file mode 100755 index 0000000..08e3eaa --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-frameworks.sh @@ -0,0 +1,146 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +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}" + 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 && exit ${PIPESTATUS[0]}) + 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 +} + +# 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_identitiy + 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" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=1 +} + +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-resources.sh b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-resources.sh new file mode 100755 index 0000000..345301f --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-resources.sh @@ -0,0 +1,118 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then + # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy + # resources to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +# 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 .*.??????") + +case "${TARGETED_DEVICE_FAMILY:-}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" || true + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + else + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" + fi +fi diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-umbrella.h b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-umbrella.h new file mode 100644 index 0000000..58425c8 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests-umbrella.h @@ -0,0 +1,16 @@ +#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_My_MindUITestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_My_MindUITestsVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.debug.xcconfig b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.debug.xcconfig new file mode 100644 index 0000000..20be3ff --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.debug.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.modulemap b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.modulemap new file mode 100644 index 0000000..4143236 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_My_MindUITests { + umbrella header "Pods-My MindUITests-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.release.xcconfig b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.release.xcconfig new file mode 100644 index 0000000..20be3ff --- /dev/null +++ b/My Mind/Pods/Target Support Files/Pods-My MindUITests/Pods-My MindUITests.release.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging" "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage" "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher" "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities" "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms" "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library" "${PODS_CONFIGURATION_BUILD_DIR}/nanopb" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/GoogleAppMeasurement/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" $(inherited) ${PODS_ROOT}/Firebase/CoreOnly/Sources +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseAuth/FirebaseAuth.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseCore/FirebaseCore.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseDatabase/FirebaseDatabase.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseMessaging/FirebaseMessaging.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FirebaseStorage/FirebaseStorage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/GoogleUtilities/GoogleUtilities.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Protobuf/Protobuf.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms/SwiftForms.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library/leveldb.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/nanopb/nanopb.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalyticsInterop" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAuthInterop" +OTHER_LDFLAGS = $(inherited) -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "CFNetwork" -framework "FirebaseAuth" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseMessaging" -framework "FirebaseStorage" -framework "Foundation" -framework "GTMSessionFetcher" -framework "GoogleUtilities" -framework "MobileCoreServices" -framework "Protobuf" -framework "SafariServices" -framework "Security" -framework "StoreKit" -framework "SwiftForms" -framework "SystemConfiguration" -framework "leveldb" -framework "nanopb" +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 diff --git a/My Mind/Pods/Target Support Files/Protobuf/Info.plist b/My Mind/Pods/Target Support Files/Protobuf/Info.plist new file mode 100644 index 0000000..646f73c --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.6.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/Protobuf/Protobuf-dummy.m b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-dummy.m new file mode 100644 index 0000000..e0f0a33 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Protobuf : NSObject +@end +@implementation PodsDummy_Protobuf +@end diff --git a/My Mind/Pods/Target Support Files/Protobuf/Protobuf-prefix.pch b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/Protobuf/Protobuf-umbrella.h b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-umbrella.h new file mode 100644 index 0000000..9242d72 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Protobuf-umbrella.h @@ -0,0 +1,54 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "GPBArray.h" +#import "GPBArray_PackagePrivate.h" +#import "GPBBootstrap.h" +#import "GPBCodedInputStream.h" +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream.h" +#import "GPBCodedOutputStream_PackagePrivate.h" +#import "GPBDescriptor.h" +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBDictionary.h" +#import "GPBDictionary_PackagePrivate.h" +#import "GPBExtensionInternals.h" +#import "GPBExtensionRegistry.h" +#import "GPBMessage.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBProtocolBuffers.h" +#import "GPBProtocolBuffers_RuntimeSupport.h" +#import "GPBRootObject.h" +#import "GPBRootObject_PackagePrivate.h" +#import "GPBRuntimeTypes.h" +#import "GPBUnknownField.h" +#import "GPBUnknownFieldSet.h" +#import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUnknownField_PackagePrivate.h" +#import "GPBUtilities.h" +#import "GPBUtilities_PackagePrivate.h" +#import "GPBWellKnownTypes.h" +#import "GPBWireFormat.h" +#import "Any.pbobjc.h" +#import "Api.pbobjc.h" +#import "Duration.pbobjc.h" +#import "Empty.pbobjc.h" +#import "FieldMask.pbobjc.h" +#import "SourceContext.pbobjc.h" +#import "Struct.pbobjc.h" +#import "Timestamp.pbobjc.h" +#import "Type.pbobjc.h" +#import "Wrappers.pbobjc.h" + +FOUNDATION_EXPORT double ProtobufVersionNumber; +FOUNDATION_EXPORT const unsigned char ProtobufVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/Protobuf/Protobuf.modulemap b/My Mind/Pods/Target Support Files/Protobuf/Protobuf.modulemap new file mode 100644 index 0000000..57d3b39 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Protobuf.modulemap @@ -0,0 +1,6 @@ +framework module Protobuf { + umbrella header "Protobuf-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/Protobuf/Protobuf.xcconfig b/My Mind/Pods/Target Support Files/Protobuf/Protobuf.xcconfig new file mode 100644 index 0000000..12e3c31 --- /dev/null +++ b/My Mind/Pods/Target Support Files/Protobuf/Protobuf.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Protobuf +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Protobuf +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/SwiftForms/Info.plist b/My Mind/Pods/Target Support Files/SwiftForms/Info.plist new file mode 100644 index 0000000..7cfa284 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.8.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-dummy.m b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-dummy.m new file mode 100644 index 0000000..0f311b1 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftForms : NSObject +@end +@implementation PodsDummy_SwiftForms +@end diff --git a/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-prefix.pch b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-umbrella.h b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-umbrella.h new file mode 100644 index 0000000..3545fd2 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms-umbrella.h @@ -0,0 +1,16 @@ +#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 SwiftFormsVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftFormsVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.modulemap b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.modulemap new file mode 100644 index 0000000..789f293 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.modulemap @@ -0,0 +1,6 @@ +framework module SwiftForms { + umbrella header "SwiftForms-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.xcconfig b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.xcconfig new file mode 100644 index 0000000..862e865 --- /dev/null +++ b/My Mind/Pods/Target Support Files/SwiftForms/SwiftForms.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftForms +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}/SwiftForms +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/Target Support Files/leveldb-library/Info.plist b/My Mind/Pods/Target Support Files/leveldb-library/Info.plist new file mode 100644 index 0000000..c994e4a --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.20.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-dummy.m b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-dummy.m new file mode 100644 index 0000000..dba1492 --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_leveldb_library : NSObject +@end +@implementation PodsDummy_leveldb_library +@end diff --git a/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-prefix.pch b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-umbrella.h b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-umbrella.h new file mode 100644 index 0000000..8b281be --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library-umbrella.h @@ -0,0 +1,30 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "c.h" +#import "cache.h" +#import "comparator.h" +#import "db.h" +#import "dumpfile.h" +#import "env.h" +#import "filter_policy.h" +#import "iterator.h" +#import "options.h" +#import "slice.h" +#import "status.h" +#import "table.h" +#import "table_builder.h" +#import "write_batch.h" + +FOUNDATION_EXPORT double leveldbVersionNumber; +FOUNDATION_EXPORT const unsigned char leveldbVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.modulemap b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.modulemap new file mode 100644 index 0000000..fd77435 --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.modulemap @@ -0,0 +1,6 @@ +framework module leveldb { + umbrella header "leveldb-library-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.xcconfig b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.xcconfig new file mode 100644 index 0000000..eed93cc --- /dev/null +++ b/My Mind/Pods/Target Support Files/leveldb-library/leveldb-library.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/leveldb-library +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/leveldb-library" "${PODS_ROOT}/leveldb-library/include" +OTHER_LDFLAGS = -l"c++" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/leveldb-library +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_HEADERMAP = No +WARNING_CFLAGS = -Wno-shorten-64-to-32 -Wno-comma -Wno-unreachable-code -Wno-conditional-uninitialized -Wno-deprecated-declarations diff --git a/My Mind/Pods/Target Support Files/nanopb/Info.plist b/My Mind/Pods/Target Support Files/nanopb/Info.plist new file mode 100644 index 0000000..dbeb19f --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.3.901 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/My Mind/Pods/Target Support Files/nanopb/nanopb-dummy.m b/My Mind/Pods/Target Support Files/nanopb/nanopb-dummy.m new file mode 100644 index 0000000..b3fa595 --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/nanopb-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_nanopb : NSObject +@end +@implementation PodsDummy_nanopb +@end diff --git a/My Mind/Pods/Target Support Files/nanopb/nanopb-prefix.pch b/My Mind/Pods/Target Support Files/nanopb/nanopb-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/nanopb-prefix.pch @@ -0,0 +1,12 @@ +#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/My Mind/Pods/Target Support Files/nanopb/nanopb-umbrella.h b/My Mind/Pods/Target Support Files/nanopb/nanopb-umbrella.h new file mode 100644 index 0000000..07e77b3 --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/nanopb-umbrella.h @@ -0,0 +1,26 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "pb.h" +#import "pb_common.h" +#import "pb_decode.h" +#import "pb_encode.h" +#import "pb.h" +#import "pb_decode.h" +#import "pb_common.h" +#import "pb.h" +#import "pb_encode.h" +#import "pb_common.h" + +FOUNDATION_EXPORT double nanopbVersionNumber; +FOUNDATION_EXPORT const unsigned char nanopbVersionString[]; + diff --git a/My Mind/Pods/Target Support Files/nanopb/nanopb.modulemap b/My Mind/Pods/Target Support Files/nanopb/nanopb.modulemap new file mode 100644 index 0000000..e8d4b53 --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/nanopb.modulemap @@ -0,0 +1,6 @@ +framework module nanopb { + umbrella header "nanopb-umbrella.h" + + export * + module * { export * } +} diff --git a/My Mind/Pods/Target Support Files/nanopb/nanopb.xcconfig b/My Mind/Pods/Target Support Files/nanopb/nanopb.xcconfig new file mode 100644 index 0000000..704a532 --- /dev/null +++ b/My Mind/Pods/Target Support Files/nanopb/nanopb.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/nanopb +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) PB_FIELD_32BIT=1 PB_NO_PACKED_STRUCTS=1 PB_ENABLE_MALLOC=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/nanopb +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/My Mind/Pods/leveldb-library/LICENSE b/My Mind/Pods/leveldb-library/LICENSE new file mode 100644 index 0000000..8e80208 --- /dev/null +++ b/My Mind/Pods/leveldb-library/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2011 The LevelDB Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. diff --git a/My Mind/Pods/leveldb-library/README.md b/My Mind/Pods/leveldb-library/README.md new file mode 100644 index 0000000..a010c50 --- /dev/null +++ b/My Mind/Pods/leveldb-library/README.md @@ -0,0 +1,174 @@ +**LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.** + +[![Build Status](https://travis-ci.org/google/leveldb.svg?branch=master)](https://travis-ci.org/google/leveldb) + +Authors: Sanjay Ghemawat (sanjay@google.com) and Jeff Dean (jeff@google.com) + +# Features + * Keys and values are arbitrary byte arrays. + * Data is stored sorted by key. + * Callers can provide a custom comparison function to override the sort order. + * The basic operations are `Put(key,value)`, `Get(key)`, `Delete(key)`. + * Multiple changes can be made in one atomic batch. + * Users can create a transient snapshot to get a consistent view of data. + * Forward and backward iteration is supported over the data. + * Data is automatically compressed using the [Snappy compression library](http://google.github.io/snappy/). + * External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions. + +# Documentation + [LevelDB library documentation](https://github.com/google/leveldb/blob/master/doc/index.md) is online and bundled with the source code. + + +# Limitations + * This is not a SQL database. It does not have a relational data model, it does not support SQL queries, and it has no support for indexes. + * Only a single process (possibly multi-threaded) can access a particular database at a time. + * There is no client-server support builtin to the library. An application that needs such support will have to wrap their own server around the library. + +# Contributing to the leveldb Project +The leveldb project welcomes contributions. leveldb's primary goal is to be +a reliable and fast key/value store. Changes that are in line with the +features/limitations outlined above, and meet the requirements below, +will be considered. + +Contribution requirements: + +1. **POSIX only**. We _generally_ will only accept changes that are both + compiled, and tested on a POSIX platform - usually Linux. Very small + changes will sometimes be accepted, but consider that more of an + exception than the rule. + +2. **Stable API**. We strive very hard to maintain a stable API. Changes that + require changes for projects using leveldb _might_ be rejected without + sufficient benefit to the project. + +3. **Tests**: All changes must be accompanied by a new (or changed) test, or + a sufficient explanation as to why a new (or changed) test is not required. + +## Submitting a Pull Request +Before any pull request will be accepted the author must first sign a +Contributor License Agreement (CLA) at https://cla.developers.google.com/. + +In order to keep the commit timeline linear +[squash](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Squashing-Commits) +your changes down to a single commit and [rebase](https://git-scm.com/docs/git-rebase) +on google/leveldb/master. This keeps the commit timeline linear and more easily sync'ed +with the internal repository at Google. More information at GitHub's +[About Git rebase](https://help.github.com/articles/about-git-rebase/) page. + +# Performance + +Here is a performance report (with explanations) from the run of the +included db_bench program. The results are somewhat noisy, but should +be enough to get a ballpark performance estimate. + +## Setup + +We use a database with a million entries. Each entry has a 16 byte +key, and a 100 byte value. Values used by the benchmark compress to +about half their original size. + + LevelDB: version 1.1 + Date: Sun May 1 12:11:26 2011 + CPU: 4 x Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz + CPUCache: 4096 KB + Keys: 16 bytes each + Values: 100 bytes each (50 bytes after compression) + Entries: 1000000 + Raw Size: 110.6 MB (estimated) + File Size: 62.9 MB (estimated) + +## Write performance + +The "fill" benchmarks create a brand new database, in either +sequential, or random order. The "fillsync" benchmark flushes data +from the operating system to the disk after every operation; the other +write operations leave the data sitting in the operating system buffer +cache for a while. The "overwrite" benchmark does random writes that +update existing keys in the database. + + fillseq : 1.765 micros/op; 62.7 MB/s + fillsync : 268.409 micros/op; 0.4 MB/s (10000 ops) + fillrandom : 2.460 micros/op; 45.0 MB/s + overwrite : 2.380 micros/op; 46.5 MB/s + +Each "op" above corresponds to a write of a single key/value pair. +I.e., a random write benchmark goes at approximately 400,000 writes per second. + +Each "fillsync" operation costs much less (0.3 millisecond) +than a disk seek (typically 10 milliseconds). We suspect that this is +because the hard disk itself is buffering the update in its memory and +responding before the data has been written to the platter. This may +or may not be safe based on whether or not the hard disk has enough +power to save its memory in the event of a power failure. + +## Read performance + +We list the performance of reading sequentially in both the forward +and reverse direction, and also the performance of a random lookup. +Note that the database created by the benchmark is quite small. +Therefore the report characterizes the performance of leveldb when the +working set fits in memory. The cost of reading a piece of data that +is not present in the operating system buffer cache will be dominated +by the one or two disk seeks needed to fetch the data from disk. +Write performance will be mostly unaffected by whether or not the +working set fits in memory. + + readrandom : 16.677 micros/op; (approximately 60,000 reads per second) + readseq : 0.476 micros/op; 232.3 MB/s + readreverse : 0.724 micros/op; 152.9 MB/s + +LevelDB compacts its underlying storage data in the background to +improve read performance. The results listed above were done +immediately after a lot of random writes. The results after +compactions (which are usually triggered automatically) are better. + + readrandom : 11.602 micros/op; (approximately 85,000 reads per second) + readseq : 0.423 micros/op; 261.8 MB/s + readreverse : 0.663 micros/op; 166.9 MB/s + +Some of the high cost of reads comes from repeated decompression of blocks +read from disk. If we supply enough cache to the leveldb so it can hold the +uncompressed blocks in memory, the read performance improves again: + + readrandom : 9.775 micros/op; (approximately 100,000 reads per second before compaction) + readrandom : 5.215 micros/op; (approximately 190,000 reads per second after compaction) + +## Repository contents + +See [doc/index.md](doc/index.md) for more explanation. See +[doc/impl.md](doc/impl.md) for a brief overview of the implementation. + +The public interface is in include/*.h. Callers should not include or +rely on the details of any other header files in this package. Those +internal APIs may be changed without warning. + +Guide to header files: + +* **include/db.h**: Main interface to the DB: Start here + +* **include/options.h**: Control over the behavior of an entire database, +and also control over the behavior of individual reads and writes. + +* **include/comparator.h**: Abstraction for user-specified comparison function. +If you want just bytewise comparison of keys, you can use the default +comparator, but clients can write their own comparator implementations if they +want custom ordering (e.g. to handle different character encodings, etc.) + +* **include/iterator.h**: Interface for iterating over data. You can get +an iterator from a DB object. + +* **include/write_batch.h**: Interface for atomically applying multiple +updates to a database. + +* **include/slice.h**: A simple module for maintaining a pointer and a +length into some other byte array. + +* **include/status.h**: Status is returned from many of the public interfaces +and is used to report success and various kinds of errors. + +* **include/env.h**: +Abstraction of the OS environment. A posix implementation of this interface is +in util/env_posix.cc + +* **include/table.h, include/table_builder.h**: Lower-level modules that most +clients probably won't use directly diff --git a/My Mind/Pods/leveldb-library/db/builder.cc b/My Mind/Pods/leveldb-library/db/builder.cc new file mode 100644 index 0000000..f419882 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/builder.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/builder.h" + +#include "db/filename.h" +#include "db/dbformat.h" +#include "db/table_cache.h" +#include "db/version_edit.h" +#include "leveldb/db.h" +#include "leveldb/env.h" +#include "leveldb/iterator.h" + +namespace leveldb { + +Status BuildTable(const std::string& dbname, + Env* env, + const Options& options, + TableCache* table_cache, + Iterator* iter, + FileMetaData* meta) { + Status s; + meta->file_size = 0; + iter->SeekToFirst(); + + std::string fname = TableFileName(dbname, meta->number); + if (iter->Valid()) { + WritableFile* file; + s = env->NewWritableFile(fname, &file); + if (!s.ok()) { + return s; + } + + TableBuilder* builder = new TableBuilder(options, file); + meta->smallest.DecodeFrom(iter->key()); + for (; iter->Valid(); iter->Next()) { + Slice key = iter->key(); + meta->largest.DecodeFrom(key); + builder->Add(key, iter->value()); + } + + // Finish and check for builder errors + if (s.ok()) { + s = builder->Finish(); + if (s.ok()) { + meta->file_size = builder->FileSize(); + assert(meta->file_size > 0); + } + } else { + builder->Abandon(); + } + delete builder; + + // Finish and check for file errors + if (s.ok()) { + s = file->Sync(); + } + if (s.ok()) { + s = file->Close(); + } + delete file; + file = NULL; + + if (s.ok()) { + // Verify that the table is usable + Iterator* it = table_cache->NewIterator(ReadOptions(), + meta->number, + meta->file_size); + s = it->status(); + delete it; + } + } + + // Check for input iterator errors + if (!iter->status().ok()) { + s = iter->status(); + } + + if (s.ok() && meta->file_size > 0) { + // Keep it + } else { + env->DeleteFile(fname); + } + return s; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/builder.h b/My Mind/Pods/leveldb-library/db/builder.h new file mode 100644 index 0000000..62431fc --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/builder.h @@ -0,0 +1,34 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_BUILDER_H_ +#define STORAGE_LEVELDB_DB_BUILDER_H_ + +#include "leveldb/status.h" + +namespace leveldb { + +struct Options; +struct FileMetaData; + +class Env; +class Iterator; +class TableCache; +class VersionEdit; + +// Build a Table file from the contents of *iter. The generated file +// will be named according to meta->number. On success, the rest of +// *meta will be filled with metadata about the generated table. +// If no data is present in *iter, meta->file_size will be set to +// zero, and no Table file will be produced. +extern Status BuildTable(const std::string& dbname, + Env* env, + const Options& options, + TableCache* table_cache, + Iterator* iter, + FileMetaData* meta); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_BUILDER_H_ diff --git a/My Mind/Pods/leveldb-library/db/c.cc b/My Mind/Pods/leveldb-library/db/c.cc new file mode 100644 index 0000000..08ff0ad --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/c.cc @@ -0,0 +1,595 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/c.h" + +#include +#include +#include "leveldb/cache.h" +#include "leveldb/comparator.h" +#include "leveldb/db.h" +#include "leveldb/env.h" +#include "leveldb/filter_policy.h" +#include "leveldb/iterator.h" +#include "leveldb/options.h" +#include "leveldb/status.h" +#include "leveldb/write_batch.h" + +using leveldb::Cache; +using leveldb::Comparator; +using leveldb::CompressionType; +using leveldb::DB; +using leveldb::Env; +using leveldb::FileLock; +using leveldb::FilterPolicy; +using leveldb::Iterator; +using leveldb::kMajorVersion; +using leveldb::kMinorVersion; +using leveldb::Logger; +using leveldb::NewBloomFilterPolicy; +using leveldb::NewLRUCache; +using leveldb::Options; +using leveldb::RandomAccessFile; +using leveldb::Range; +using leveldb::ReadOptions; +using leveldb::SequentialFile; +using leveldb::Slice; +using leveldb::Snapshot; +using leveldb::Status; +using leveldb::WritableFile; +using leveldb::WriteBatch; +using leveldb::WriteOptions; + +extern "C" { + +struct leveldb_t { DB* rep; }; +struct leveldb_iterator_t { Iterator* rep; }; +struct leveldb_writebatch_t { WriteBatch rep; }; +struct leveldb_snapshot_t { const Snapshot* rep; }; +struct leveldb_readoptions_t { ReadOptions rep; }; +struct leveldb_writeoptions_t { WriteOptions rep; }; +struct leveldb_options_t { Options rep; }; +struct leveldb_cache_t { Cache* rep; }; +struct leveldb_seqfile_t { SequentialFile* rep; }; +struct leveldb_randomfile_t { RandomAccessFile* rep; }; +struct leveldb_writablefile_t { WritableFile* rep; }; +struct leveldb_logger_t { Logger* rep; }; +struct leveldb_filelock_t { FileLock* rep; }; + +struct leveldb_comparator_t : public Comparator { + void* state_; + void (*destructor_)(void*); + int (*compare_)( + void*, + const char* a, size_t alen, + const char* b, size_t blen); + const char* (*name_)(void*); + + virtual ~leveldb_comparator_t() { + (*destructor_)(state_); + } + + virtual int Compare(const Slice& a, const Slice& b) const { + return (*compare_)(state_, a.data(), a.size(), b.data(), b.size()); + } + + virtual const char* Name() const { + return (*name_)(state_); + } + + // No-ops since the C binding does not support key shortening methods. + virtual void FindShortestSeparator(std::string*, const Slice&) const { } + virtual void FindShortSuccessor(std::string* key) const { } +}; + +struct leveldb_filterpolicy_t : public FilterPolicy { + void* state_; + void (*destructor_)(void*); + const char* (*name_)(void*); + char* (*create_)( + void*, + const char* const* key_array, const size_t* key_length_array, + int num_keys, + size_t* filter_length); + unsigned char (*key_match_)( + void*, + const char* key, size_t length, + const char* filter, size_t filter_length); + + virtual ~leveldb_filterpolicy_t() { + (*destructor_)(state_); + } + + virtual const char* Name() const { + return (*name_)(state_); + } + + virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const { + std::vector key_pointers(n); + std::vector key_sizes(n); + for (int i = 0; i < n; i++) { + key_pointers[i] = keys[i].data(); + key_sizes[i] = keys[i].size(); + } + size_t len; + char* filter = (*create_)(state_, &key_pointers[0], &key_sizes[0], n, &len); + dst->append(filter, len); + free(filter); + } + + virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const { + return (*key_match_)(state_, key.data(), key.size(), + filter.data(), filter.size()); + } +}; + +struct leveldb_env_t { + Env* rep; + bool is_default; +}; + +static bool SaveError(char** errptr, const Status& s) { + assert(errptr != NULL); + if (s.ok()) { + return false; + } else if (*errptr == NULL) { + *errptr = strdup(s.ToString().c_str()); + } else { + // TODO(sanjay): Merge with existing error? + free(*errptr); + *errptr = strdup(s.ToString().c_str()); + } + return true; +} + +static char* CopyString(const std::string& str) { + char* result = reinterpret_cast(malloc(sizeof(char) * str.size())); + memcpy(result, str.data(), sizeof(char) * str.size()); + return result; +} + +leveldb_t* leveldb_open( + const leveldb_options_t* options, + const char* name, + char** errptr) { + DB* db; + if (SaveError(errptr, DB::Open(options->rep, std::string(name), &db))) { + return NULL; + } + leveldb_t* result = new leveldb_t; + result->rep = db; + return result; +} + +void leveldb_close(leveldb_t* db) { + delete db->rep; + delete db; +} + +void leveldb_put( + leveldb_t* db, + const leveldb_writeoptions_t* options, + const char* key, size_t keylen, + const char* val, size_t vallen, + char** errptr) { + SaveError(errptr, + db->rep->Put(options->rep, Slice(key, keylen), Slice(val, vallen))); +} + +void leveldb_delete( + leveldb_t* db, + const leveldb_writeoptions_t* options, + const char* key, size_t keylen, + char** errptr) { + SaveError(errptr, db->rep->Delete(options->rep, Slice(key, keylen))); +} + + +void leveldb_write( + leveldb_t* db, + const leveldb_writeoptions_t* options, + leveldb_writebatch_t* batch, + char** errptr) { + SaveError(errptr, db->rep->Write(options->rep, &batch->rep)); +} + +char* leveldb_get( + leveldb_t* db, + const leveldb_readoptions_t* options, + const char* key, size_t keylen, + size_t* vallen, + char** errptr) { + char* result = NULL; + std::string tmp; + Status s = db->rep->Get(options->rep, Slice(key, keylen), &tmp); + if (s.ok()) { + *vallen = tmp.size(); + result = CopyString(tmp); + } else { + *vallen = 0; + if (!s.IsNotFound()) { + SaveError(errptr, s); + } + } + return result; +} + +leveldb_iterator_t* leveldb_create_iterator( + leveldb_t* db, + const leveldb_readoptions_t* options) { + leveldb_iterator_t* result = new leveldb_iterator_t; + result->rep = db->rep->NewIterator(options->rep); + return result; +} + +const leveldb_snapshot_t* leveldb_create_snapshot( + leveldb_t* db) { + leveldb_snapshot_t* result = new leveldb_snapshot_t; + result->rep = db->rep->GetSnapshot(); + return result; +} + +void leveldb_release_snapshot( + leveldb_t* db, + const leveldb_snapshot_t* snapshot) { + db->rep->ReleaseSnapshot(snapshot->rep); + delete snapshot; +} + +char* leveldb_property_value( + leveldb_t* db, + const char* propname) { + std::string tmp; + if (db->rep->GetProperty(Slice(propname), &tmp)) { + // We use strdup() since we expect human readable output. + return strdup(tmp.c_str()); + } else { + return NULL; + } +} + +void leveldb_approximate_sizes( + leveldb_t* db, + int num_ranges, + const char* const* range_start_key, const size_t* range_start_key_len, + const char* const* range_limit_key, const size_t* range_limit_key_len, + uint64_t* sizes) { + Range* ranges = new Range[num_ranges]; + for (int i = 0; i < num_ranges; i++) { + ranges[i].start = Slice(range_start_key[i], range_start_key_len[i]); + ranges[i].limit = Slice(range_limit_key[i], range_limit_key_len[i]); + } + db->rep->GetApproximateSizes(ranges, num_ranges, sizes); + delete[] ranges; +} + +void leveldb_compact_range( + leveldb_t* db, + const char* start_key, size_t start_key_len, + const char* limit_key, size_t limit_key_len) { + Slice a, b; + db->rep->CompactRange( + // Pass NULL Slice if corresponding "const char*" is NULL + (start_key ? (a = Slice(start_key, start_key_len), &a) : NULL), + (limit_key ? (b = Slice(limit_key, limit_key_len), &b) : NULL)); +} + +void leveldb_destroy_db( + const leveldb_options_t* options, + const char* name, + char** errptr) { + SaveError(errptr, DestroyDB(name, options->rep)); +} + +void leveldb_repair_db( + const leveldb_options_t* options, + const char* name, + char** errptr) { + SaveError(errptr, RepairDB(name, options->rep)); +} + +void leveldb_iter_destroy(leveldb_iterator_t* iter) { + delete iter->rep; + delete iter; +} + +unsigned char leveldb_iter_valid(const leveldb_iterator_t* iter) { + return iter->rep->Valid(); +} + +void leveldb_iter_seek_to_first(leveldb_iterator_t* iter) { + iter->rep->SeekToFirst(); +} + +void leveldb_iter_seek_to_last(leveldb_iterator_t* iter) { + iter->rep->SeekToLast(); +} + +void leveldb_iter_seek(leveldb_iterator_t* iter, const char* k, size_t klen) { + iter->rep->Seek(Slice(k, klen)); +} + +void leveldb_iter_next(leveldb_iterator_t* iter) { + iter->rep->Next(); +} + +void leveldb_iter_prev(leveldb_iterator_t* iter) { + iter->rep->Prev(); +} + +const char* leveldb_iter_key(const leveldb_iterator_t* iter, size_t* klen) { + Slice s = iter->rep->key(); + *klen = s.size(); + return s.data(); +} + +const char* leveldb_iter_value(const leveldb_iterator_t* iter, size_t* vlen) { + Slice s = iter->rep->value(); + *vlen = s.size(); + return s.data(); +} + +void leveldb_iter_get_error(const leveldb_iterator_t* iter, char** errptr) { + SaveError(errptr, iter->rep->status()); +} + +leveldb_writebatch_t* leveldb_writebatch_create() { + return new leveldb_writebatch_t; +} + +void leveldb_writebatch_destroy(leveldb_writebatch_t* b) { + delete b; +} + +void leveldb_writebatch_clear(leveldb_writebatch_t* b) { + b->rep.Clear(); +} + +void leveldb_writebatch_put( + leveldb_writebatch_t* b, + const char* key, size_t klen, + const char* val, size_t vlen) { + b->rep.Put(Slice(key, klen), Slice(val, vlen)); +} + +void leveldb_writebatch_delete( + leveldb_writebatch_t* b, + const char* key, size_t klen) { + b->rep.Delete(Slice(key, klen)); +} + +void leveldb_writebatch_iterate( + leveldb_writebatch_t* b, + void* state, + void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), + void (*deleted)(void*, const char* k, size_t klen)) { + class H : public WriteBatch::Handler { + public: + void* state_; + void (*put_)(void*, const char* k, size_t klen, const char* v, size_t vlen); + void (*deleted_)(void*, const char* k, size_t klen); + virtual void Put(const Slice& key, const Slice& value) { + (*put_)(state_, key.data(), key.size(), value.data(), value.size()); + } + virtual void Delete(const Slice& key) { + (*deleted_)(state_, key.data(), key.size()); + } + }; + H handler; + handler.state_ = state; + handler.put_ = put; + handler.deleted_ = deleted; + b->rep.Iterate(&handler); +} + +leveldb_options_t* leveldb_options_create() { + return new leveldb_options_t; +} + +void leveldb_options_destroy(leveldb_options_t* options) { + delete options; +} + +void leveldb_options_set_comparator( + leveldb_options_t* opt, + leveldb_comparator_t* cmp) { + opt->rep.comparator = cmp; +} + +void leveldb_options_set_filter_policy( + leveldb_options_t* opt, + leveldb_filterpolicy_t* policy) { + opt->rep.filter_policy = policy; +} + +void leveldb_options_set_create_if_missing( + leveldb_options_t* opt, unsigned char v) { + opt->rep.create_if_missing = v; +} + +void leveldb_options_set_error_if_exists( + leveldb_options_t* opt, unsigned char v) { + opt->rep.error_if_exists = v; +} + +void leveldb_options_set_paranoid_checks( + leveldb_options_t* opt, unsigned char v) { + opt->rep.paranoid_checks = v; +} + +void leveldb_options_set_env(leveldb_options_t* opt, leveldb_env_t* env) { + opt->rep.env = (env ? env->rep : NULL); +} + +void leveldb_options_set_info_log(leveldb_options_t* opt, leveldb_logger_t* l) { + opt->rep.info_log = (l ? l->rep : NULL); +} + +void leveldb_options_set_write_buffer_size(leveldb_options_t* opt, size_t s) { + opt->rep.write_buffer_size = s; +} + +void leveldb_options_set_max_open_files(leveldb_options_t* opt, int n) { + opt->rep.max_open_files = n; +} + +void leveldb_options_set_cache(leveldb_options_t* opt, leveldb_cache_t* c) { + opt->rep.block_cache = c->rep; +} + +void leveldb_options_set_block_size(leveldb_options_t* opt, size_t s) { + opt->rep.block_size = s; +} + +void leveldb_options_set_block_restart_interval(leveldb_options_t* opt, int n) { + opt->rep.block_restart_interval = n; +} + +void leveldb_options_set_compression(leveldb_options_t* opt, int t) { + opt->rep.compression = static_cast(t); +} + +leveldb_comparator_t* leveldb_comparator_create( + void* state, + void (*destructor)(void*), + int (*compare)( + void*, + const char* a, size_t alen, + const char* b, size_t blen), + const char* (*name)(void*)) { + leveldb_comparator_t* result = new leveldb_comparator_t; + result->state_ = state; + result->destructor_ = destructor; + result->compare_ = compare; + result->name_ = name; + return result; +} + +void leveldb_comparator_destroy(leveldb_comparator_t* cmp) { + delete cmp; +} + +leveldb_filterpolicy_t* leveldb_filterpolicy_create( + void* state, + void (*destructor)(void*), + char* (*create_filter)( + void*, + const char* const* key_array, const size_t* key_length_array, + int num_keys, + size_t* filter_length), + unsigned char (*key_may_match)( + void*, + const char* key, size_t length, + const char* filter, size_t filter_length), + const char* (*name)(void*)) { + leveldb_filterpolicy_t* result = new leveldb_filterpolicy_t; + result->state_ = state; + result->destructor_ = destructor; + result->create_ = create_filter; + result->key_match_ = key_may_match; + result->name_ = name; + return result; +} + +void leveldb_filterpolicy_destroy(leveldb_filterpolicy_t* filter) { + delete filter; +} + +leveldb_filterpolicy_t* leveldb_filterpolicy_create_bloom(int bits_per_key) { + // Make a leveldb_filterpolicy_t, but override all of its methods so + // they delegate to a NewBloomFilterPolicy() instead of user + // supplied C functions. + struct Wrapper : public leveldb_filterpolicy_t { + const FilterPolicy* rep_; + ~Wrapper() { delete rep_; } + const char* Name() const { return rep_->Name(); } + void CreateFilter(const Slice* keys, int n, std::string* dst) const { + return rep_->CreateFilter(keys, n, dst); + } + bool KeyMayMatch(const Slice& key, const Slice& filter) const { + return rep_->KeyMayMatch(key, filter); + } + static void DoNothing(void*) { } + }; + Wrapper* wrapper = new Wrapper; + wrapper->rep_ = NewBloomFilterPolicy(bits_per_key); + wrapper->state_ = NULL; + wrapper->destructor_ = &Wrapper::DoNothing; + return wrapper; +} + +leveldb_readoptions_t* leveldb_readoptions_create() { + return new leveldb_readoptions_t; +} + +void leveldb_readoptions_destroy(leveldb_readoptions_t* opt) { + delete opt; +} + +void leveldb_readoptions_set_verify_checksums( + leveldb_readoptions_t* opt, + unsigned char v) { + opt->rep.verify_checksums = v; +} + +void leveldb_readoptions_set_fill_cache( + leveldb_readoptions_t* opt, unsigned char v) { + opt->rep.fill_cache = v; +} + +void leveldb_readoptions_set_snapshot( + leveldb_readoptions_t* opt, + const leveldb_snapshot_t* snap) { + opt->rep.snapshot = (snap ? snap->rep : NULL); +} + +leveldb_writeoptions_t* leveldb_writeoptions_create() { + return new leveldb_writeoptions_t; +} + +void leveldb_writeoptions_destroy(leveldb_writeoptions_t* opt) { + delete opt; +} + +void leveldb_writeoptions_set_sync( + leveldb_writeoptions_t* opt, unsigned char v) { + opt->rep.sync = v; +} + +leveldb_cache_t* leveldb_cache_create_lru(size_t capacity) { + leveldb_cache_t* c = new leveldb_cache_t; + c->rep = NewLRUCache(capacity); + return c; +} + +void leveldb_cache_destroy(leveldb_cache_t* cache) { + delete cache->rep; + delete cache; +} + +leveldb_env_t* leveldb_create_default_env() { + leveldb_env_t* result = new leveldb_env_t; + result->rep = Env::Default(); + result->is_default = true; + return result; +} + +void leveldb_env_destroy(leveldb_env_t* env) { + if (!env->is_default) delete env->rep; + delete env; +} + +void leveldb_free(void* ptr) { + free(ptr); +} + +int leveldb_major_version() { + return kMajorVersion; +} + +int leveldb_minor_version() { + return kMinorVersion; +} + +} // end extern "C" diff --git a/My Mind/Pods/leveldb-library/db/db_impl.cc b/My Mind/Pods/leveldb-library/db/db_impl.cc new file mode 100644 index 0000000..f43ad76 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/db_impl.cc @@ -0,0 +1,1568 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/db_impl.h" + +#include +#include +#include +#include +#include +#include +#include "db/builder.h" +#include "db/db_iter.h" +#include "db/dbformat.h" +#include "db/filename.h" +#include "db/log_reader.h" +#include "db/log_writer.h" +#include "db/memtable.h" +#include "db/table_cache.h" +#include "db/version_set.h" +#include "db/write_batch_internal.h" +#include "leveldb/db.h" +#include "leveldb/env.h" +#include "leveldb/status.h" +#include "leveldb/table.h" +#include "leveldb/table_builder.h" +#include "port/port.h" +#include "table/block.h" +#include "table/merger.h" +#include "table/two_level_iterator.h" +#include "util/coding.h" +#include "util/logging.h" +#include "util/mutexlock.h" + +namespace leveldb { + +const int kNumNonTableCacheFiles = 10; + +// Information kept for every waiting writer +struct DBImpl::Writer { + Status status; + WriteBatch* batch; + bool sync; + bool done; + port::CondVar cv; + + explicit Writer(port::Mutex* mu) : cv(mu) { } +}; + +struct DBImpl::CompactionState { + Compaction* const compaction; + + // Sequence numbers < smallest_snapshot are not significant since we + // will never have to service a snapshot below smallest_snapshot. + // Therefore if we have seen a sequence number S <= smallest_snapshot, + // we can drop all entries for the same key with sequence numbers < S. + SequenceNumber smallest_snapshot; + + // Files produced by compaction + struct Output { + uint64_t number; + uint64_t file_size; + InternalKey smallest, largest; + }; + std::vector outputs; + + // State kept for output being generated + WritableFile* outfile; + TableBuilder* builder; + + uint64_t total_bytes; + + Output* current_output() { return &outputs[outputs.size()-1]; } + + explicit CompactionState(Compaction* c) + : compaction(c), + outfile(NULL), + builder(NULL), + total_bytes(0) { + } +}; + +// Fix user-supplied options to be reasonable +template +static void ClipToRange(T* ptr, V minvalue, V maxvalue) { + if (static_cast(*ptr) > maxvalue) *ptr = maxvalue; + if (static_cast(*ptr) < minvalue) *ptr = minvalue; +} +Options SanitizeOptions(const std::string& dbname, + const InternalKeyComparator* icmp, + const InternalFilterPolicy* ipolicy, + const Options& src) { + Options result = src; + result.comparator = icmp; + result.filter_policy = (src.filter_policy != NULL) ? ipolicy : NULL; + ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000); + ClipToRange(&result.write_buffer_size, 64<<10, 1<<30); + ClipToRange(&result.max_file_size, 1<<20, 1<<30); + ClipToRange(&result.block_size, 1<<10, 4<<20); + if (result.info_log == NULL) { + // Open a log file in the same directory as the db + src.env->CreateDir(dbname); // In case it does not exist + src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname)); + Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log); + if (!s.ok()) { + // No place suitable for logging + result.info_log = NULL; + } + } + if (result.block_cache == NULL) { + result.block_cache = NewLRUCache(8 << 20); + } + return result; +} + +DBImpl::DBImpl(const Options& raw_options, const std::string& dbname) + : env_(raw_options.env), + internal_comparator_(raw_options.comparator), + internal_filter_policy_(raw_options.filter_policy), + options_(SanitizeOptions(dbname, &internal_comparator_, + &internal_filter_policy_, raw_options)), + owns_info_log_(options_.info_log != raw_options.info_log), + owns_cache_(options_.block_cache != raw_options.block_cache), + dbname_(dbname), + db_lock_(NULL), + shutting_down_(NULL), + bg_cv_(&mutex_), + mem_(NULL), + imm_(NULL), + logfile_(NULL), + logfile_number_(0), + log_(NULL), + seed_(0), + tmp_batch_(new WriteBatch), + bg_compaction_scheduled_(false), + manual_compaction_(NULL) { + has_imm_.Release_Store(NULL); + + // Reserve ten files or so for other uses and give the rest to TableCache. + const int table_cache_size = options_.max_open_files - kNumNonTableCacheFiles; + table_cache_ = new TableCache(dbname_, &options_, table_cache_size); + + versions_ = new VersionSet(dbname_, &options_, table_cache_, + &internal_comparator_); +} + +DBImpl::~DBImpl() { + // Wait for background work to finish + mutex_.Lock(); + shutting_down_.Release_Store(this); // Any non-NULL value is ok + while (bg_compaction_scheduled_) { + bg_cv_.Wait(); + } + mutex_.Unlock(); + + if (db_lock_ != NULL) { + env_->UnlockFile(db_lock_); + } + + delete versions_; + if (mem_ != NULL) mem_->Unref(); + if (imm_ != NULL) imm_->Unref(); + delete tmp_batch_; + delete log_; + delete logfile_; + delete table_cache_; + + if (owns_info_log_) { + delete options_.info_log; + } + if (owns_cache_) { + delete options_.block_cache; + } +} + +Status DBImpl::NewDB() { + VersionEdit new_db; + new_db.SetComparatorName(user_comparator()->Name()); + new_db.SetLogNumber(0); + new_db.SetNextFile(2); + new_db.SetLastSequence(0); + + const std::string manifest = DescriptorFileName(dbname_, 1); + WritableFile* file; + Status s = env_->NewWritableFile(manifest, &file); + if (!s.ok()) { + return s; + } + { + log::Writer log(file); + std::string record; + new_db.EncodeTo(&record); + s = log.AddRecord(record); + if (s.ok()) { + s = file->Close(); + } + } + delete file; + if (s.ok()) { + // Make "CURRENT" file that points to the new manifest file. + s = SetCurrentFile(env_, dbname_, 1); + } else { + env_->DeleteFile(manifest); + } + return s; +} + +void DBImpl::MaybeIgnoreError(Status* s) const { + if (s->ok() || options_.paranoid_checks) { + // No change needed + } else { + Log(options_.info_log, "Ignoring error %s", s->ToString().c_str()); + *s = Status::OK(); + } +} + +void DBImpl::DeleteObsoleteFiles() { + if (!bg_error_.ok()) { + // After a background error, we don't know whether a new version may + // or may not have been committed, so we cannot safely garbage collect. + return; + } + + // Make a set of all of the live files + std::set live = pending_outputs_; + versions_->AddLiveFiles(&live); + + std::vector filenames; + env_->GetChildren(dbname_, &filenames); // Ignoring errors on purpose + uint64_t number; + FileType type; + for (size_t i = 0; i < filenames.size(); i++) { + if (ParseFileName(filenames[i], &number, &type)) { + bool keep = true; + switch (type) { + case kLogFile: + keep = ((number >= versions_->LogNumber()) || + (number == versions_->PrevLogNumber())); + break; + case kDescriptorFile: + // Keep my manifest file, and any newer incarnations' + // (in case there is a race that allows other incarnations) + keep = (number >= versions_->ManifestFileNumber()); + break; + case kTableFile: + keep = (live.find(number) != live.end()); + break; + case kTempFile: + // Any temp files that are currently being written to must + // be recorded in pending_outputs_, which is inserted into "live" + keep = (live.find(number) != live.end()); + break; + case kCurrentFile: + case kDBLockFile: + case kInfoLogFile: + keep = true; + break; + } + + if (!keep) { + if (type == kTableFile) { + table_cache_->Evict(number); + } + Log(options_.info_log, "Delete type=%d #%lld\n", + int(type), + static_cast(number)); + env_->DeleteFile(dbname_ + "/" + filenames[i]); + } + } + } +} + +Status DBImpl::Recover(VersionEdit* edit, bool *save_manifest) { + mutex_.AssertHeld(); + + // Ignore error from CreateDir since the creation of the DB is + // committed only when the descriptor is created, and this directory + // may already exist from a previous failed creation attempt. + env_->CreateDir(dbname_); + assert(db_lock_ == NULL); + Status s = env_->LockFile(LockFileName(dbname_), &db_lock_); + if (!s.ok()) { + return s; + } + + if (!env_->FileExists(CurrentFileName(dbname_))) { + if (options_.create_if_missing) { + s = NewDB(); + if (!s.ok()) { + return s; + } + } else { + return Status::InvalidArgument( + dbname_, "does not exist (create_if_missing is false)"); + } + } else { + if (options_.error_if_exists) { + return Status::InvalidArgument( + dbname_, "exists (error_if_exists is true)"); + } + } + + s = versions_->Recover(save_manifest); + if (!s.ok()) { + return s; + } + SequenceNumber max_sequence(0); + + // Recover from all newer log files than the ones named in the + // descriptor (new log files may have been added by the previous + // incarnation without registering them in the descriptor). + // + // Note that PrevLogNumber() is no longer used, but we pay + // attention to it in case we are recovering a database + // produced by an older version of leveldb. + const uint64_t min_log = versions_->LogNumber(); + const uint64_t prev_log = versions_->PrevLogNumber(); + std::vector filenames; + s = env_->GetChildren(dbname_, &filenames); + if (!s.ok()) { + return s; + } + std::set expected; + versions_->AddLiveFiles(&expected); + uint64_t number; + FileType type; + std::vector logs; + for (size_t i = 0; i < filenames.size(); i++) { + if (ParseFileName(filenames[i], &number, &type)) { + expected.erase(number); + if (type == kLogFile && ((number >= min_log) || (number == prev_log))) + logs.push_back(number); + } + } + if (!expected.empty()) { + char buf[50]; + snprintf(buf, sizeof(buf), "%d missing files; e.g.", + static_cast(expected.size())); + return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin()))); + } + + // Recover in the order in which the logs were generated + std::sort(logs.begin(), logs.end()); + for (size_t i = 0; i < logs.size(); i++) { + s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit, + &max_sequence); + if (!s.ok()) { + return s; + } + + // The previous incarnation may not have written any MANIFEST + // records after allocating this log number. So we manually + // update the file number allocation counter in VersionSet. + versions_->MarkFileNumberUsed(logs[i]); + } + + if (versions_->LastSequence() < max_sequence) { + versions_->SetLastSequence(max_sequence); + } + + return Status::OK(); +} + +Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log, + bool* save_manifest, VersionEdit* edit, + SequenceNumber* max_sequence) { + struct LogReporter : public log::Reader::Reporter { + Env* env; + Logger* info_log; + const char* fname; + Status* status; // NULL if options_.paranoid_checks==false + virtual void Corruption(size_t bytes, const Status& s) { + Log(info_log, "%s%s: dropping %d bytes; %s", + (this->status == NULL ? "(ignoring error) " : ""), + fname, static_cast(bytes), s.ToString().c_str()); + if (this->status != NULL && this->status->ok()) *this->status = s; + } + }; + + mutex_.AssertHeld(); + + // Open the log file + std::string fname = LogFileName(dbname_, log_number); + SequentialFile* file; + Status status = env_->NewSequentialFile(fname, &file); + if (!status.ok()) { + MaybeIgnoreError(&status); + return status; + } + + // Create the log reader. + LogReporter reporter; + reporter.env = env_; + reporter.info_log = options_.info_log; + reporter.fname = fname.c_str(); + reporter.status = (options_.paranoid_checks ? &status : NULL); + // We intentionally make log::Reader do checksumming even if + // paranoid_checks==false so that corruptions cause entire commits + // to be skipped instead of propagating bad information (like overly + // large sequence numbers). + log::Reader reader(file, &reporter, true/*checksum*/, + 0/*initial_offset*/); + Log(options_.info_log, "Recovering log #%llu", + (unsigned long long) log_number); + + // Read all the records and add to a memtable + std::string scratch; + Slice record; + WriteBatch batch; + int compactions = 0; + MemTable* mem = NULL; + while (reader.ReadRecord(&record, &scratch) && + status.ok()) { + if (record.size() < 12) { + reporter.Corruption( + record.size(), Status::Corruption("log record too small")); + continue; + } + WriteBatchInternal::SetContents(&batch, record); + + if (mem == NULL) { + mem = new MemTable(internal_comparator_); + mem->Ref(); + } + status = WriteBatchInternal::InsertInto(&batch, mem); + MaybeIgnoreError(&status); + if (!status.ok()) { + break; + } + const SequenceNumber last_seq = + WriteBatchInternal::Sequence(&batch) + + WriteBatchInternal::Count(&batch) - 1; + if (last_seq > *max_sequence) { + *max_sequence = last_seq; + } + + if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) { + compactions++; + *save_manifest = true; + status = WriteLevel0Table(mem, edit, NULL); + mem->Unref(); + mem = NULL; + if (!status.ok()) { + // Reflect errors immediately so that conditions like full + // file-systems cause the DB::Open() to fail. + break; + } + } + } + + delete file; + + // See if we should keep reusing the last log file. + if (status.ok() && options_.reuse_logs && last_log && compactions == 0) { + assert(logfile_ == NULL); + assert(log_ == NULL); + assert(mem_ == NULL); + uint64_t lfile_size; + if (env_->GetFileSize(fname, &lfile_size).ok() && + env_->NewAppendableFile(fname, &logfile_).ok()) { + Log(options_.info_log, "Reusing old log %s \n", fname.c_str()); + log_ = new log::Writer(logfile_, lfile_size); + logfile_number_ = log_number; + if (mem != NULL) { + mem_ = mem; + mem = NULL; + } else { + // mem can be NULL if lognum exists but was empty. + mem_ = new MemTable(internal_comparator_); + mem_->Ref(); + } + } + } + + if (mem != NULL) { + // mem did not get reused; compact it. + if (status.ok()) { + *save_manifest = true; + status = WriteLevel0Table(mem, edit, NULL); + } + mem->Unref(); + } + + return status; +} + +Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit, + Version* base) { + mutex_.AssertHeld(); + const uint64_t start_micros = env_->NowMicros(); + FileMetaData meta; + meta.number = versions_->NewFileNumber(); + pending_outputs_.insert(meta.number); + Iterator* iter = mem->NewIterator(); + Log(options_.info_log, "Level-0 table #%llu: started", + (unsigned long long) meta.number); + + Status s; + { + mutex_.Unlock(); + s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta); + mutex_.Lock(); + } + + Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s", + (unsigned long long) meta.number, + (unsigned long long) meta.file_size, + s.ToString().c_str()); + delete iter; + pending_outputs_.erase(meta.number); + + + // Note that if file_size is zero, the file has been deleted and + // should not be added to the manifest. + int level = 0; + if (s.ok() && meta.file_size > 0) { + const Slice min_user_key = meta.smallest.user_key(); + const Slice max_user_key = meta.largest.user_key(); + if (base != NULL) { + level = base->PickLevelForMemTableOutput(min_user_key, max_user_key); + } + edit->AddFile(level, meta.number, meta.file_size, + meta.smallest, meta.largest); + } + + CompactionStats stats; + stats.micros = env_->NowMicros() - start_micros; + stats.bytes_written = meta.file_size; + stats_[level].Add(stats); + return s; +} + +void DBImpl::CompactMemTable() { + mutex_.AssertHeld(); + assert(imm_ != NULL); + + // Save the contents of the memtable as a new Table + VersionEdit edit; + Version* base = versions_->current(); + base->Ref(); + Status s = WriteLevel0Table(imm_, &edit, base); + base->Unref(); + + if (s.ok() && shutting_down_.Acquire_Load()) { + s = Status::IOError("Deleting DB during memtable compaction"); + } + + // Replace immutable memtable with the generated Table + if (s.ok()) { + edit.SetPrevLogNumber(0); + edit.SetLogNumber(logfile_number_); // Earlier logs no longer needed + s = versions_->LogAndApply(&edit, &mutex_); + } + + if (s.ok()) { + // Commit to the new state + imm_->Unref(); + imm_ = NULL; + has_imm_.Release_Store(NULL); + DeleteObsoleteFiles(); + } else { + RecordBackgroundError(s); + } +} + +void DBImpl::CompactRange(const Slice* begin, const Slice* end) { + int max_level_with_files = 1; + { + MutexLock l(&mutex_); + Version* base = versions_->current(); + for (int level = 1; level < config::kNumLevels; level++) { + if (base->OverlapInLevel(level, begin, end)) { + max_level_with_files = level; + } + } + } + TEST_CompactMemTable(); // TODO(sanjay): Skip if memtable does not overlap + for (int level = 0; level < max_level_with_files; level++) { + TEST_CompactRange(level, begin, end); + } +} + +void DBImpl::TEST_CompactRange(int level, const Slice* begin,const Slice* end) { + assert(level >= 0); + assert(level + 1 < config::kNumLevels); + + InternalKey begin_storage, end_storage; + + ManualCompaction manual; + manual.level = level; + manual.done = false; + if (begin == NULL) { + manual.begin = NULL; + } else { + begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek); + manual.begin = &begin_storage; + } + if (end == NULL) { + manual.end = NULL; + } else { + end_storage = InternalKey(*end, 0, static_cast(0)); + manual.end = &end_storage; + } + + MutexLock l(&mutex_); + while (!manual.done && !shutting_down_.Acquire_Load() && bg_error_.ok()) { + if (manual_compaction_ == NULL) { // Idle + manual_compaction_ = &manual; + MaybeScheduleCompaction(); + } else { // Running either my compaction or another compaction. + bg_cv_.Wait(); + } + } + if (manual_compaction_ == &manual) { + // Cancel my manual compaction since we aborted early for some reason. + manual_compaction_ = NULL; + } +} + +Status DBImpl::TEST_CompactMemTable() { + // NULL batch means just wait for earlier writes to be done + Status s = Write(WriteOptions(), NULL); + if (s.ok()) { + // Wait until the compaction completes + MutexLock l(&mutex_); + while (imm_ != NULL && bg_error_.ok()) { + bg_cv_.Wait(); + } + if (imm_ != NULL) { + s = bg_error_; + } + } + return s; +} + +void DBImpl::RecordBackgroundError(const Status& s) { + mutex_.AssertHeld(); + if (bg_error_.ok()) { + bg_error_ = s; + bg_cv_.SignalAll(); + } +} + +void DBImpl::MaybeScheduleCompaction() { + mutex_.AssertHeld(); + if (bg_compaction_scheduled_) { + // Already scheduled + } else if (shutting_down_.Acquire_Load()) { + // DB is being deleted; no more background compactions + } else if (!bg_error_.ok()) { + // Already got an error; no more changes + } else if (imm_ == NULL && + manual_compaction_ == NULL && + !versions_->NeedsCompaction()) { + // No work to be done + } else { + bg_compaction_scheduled_ = true; + env_->Schedule(&DBImpl::BGWork, this); + } +} + +void DBImpl::BGWork(void* db) { + reinterpret_cast(db)->BackgroundCall(); +} + +void DBImpl::BackgroundCall() { + MutexLock l(&mutex_); + assert(bg_compaction_scheduled_); + if (shutting_down_.Acquire_Load()) { + // No more background work when shutting down. + } else if (!bg_error_.ok()) { + // No more background work after a background error. + } else { + BackgroundCompaction(); + } + + bg_compaction_scheduled_ = false; + + // Previous compaction may have produced too many files in a level, + // so reschedule another compaction if needed. + MaybeScheduleCompaction(); + bg_cv_.SignalAll(); +} + +void DBImpl::BackgroundCompaction() { + mutex_.AssertHeld(); + + if (imm_ != NULL) { + CompactMemTable(); + return; + } + + Compaction* c; + bool is_manual = (manual_compaction_ != NULL); + InternalKey manual_end; + if (is_manual) { + ManualCompaction* m = manual_compaction_; + c = versions_->CompactRange(m->level, m->begin, m->end); + m->done = (c == NULL); + if (c != NULL) { + manual_end = c->input(0, c->num_input_files(0) - 1)->largest; + } + Log(options_.info_log, + "Manual compaction at level-%d from %s .. %s; will stop at %s\n", + m->level, + (m->begin ? m->begin->DebugString().c_str() : "(begin)"), + (m->end ? m->end->DebugString().c_str() : "(end)"), + (m->done ? "(end)" : manual_end.DebugString().c_str())); + } else { + c = versions_->PickCompaction(); + } + + Status status; + if (c == NULL) { + // Nothing to do + } else if (!is_manual && c->IsTrivialMove()) { + // Move file to next level + assert(c->num_input_files(0) == 1); + FileMetaData* f = c->input(0, 0); + c->edit()->DeleteFile(c->level(), f->number); + c->edit()->AddFile(c->level() + 1, f->number, f->file_size, + f->smallest, f->largest); + status = versions_->LogAndApply(c->edit(), &mutex_); + if (!status.ok()) { + RecordBackgroundError(status); + } + VersionSet::LevelSummaryStorage tmp; + Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n", + static_cast(f->number), + c->level() + 1, + static_cast(f->file_size), + status.ToString().c_str(), + versions_->LevelSummary(&tmp)); + } else { + CompactionState* compact = new CompactionState(c); + status = DoCompactionWork(compact); + if (!status.ok()) { + RecordBackgroundError(status); + } + CleanupCompaction(compact); + c->ReleaseInputs(); + DeleteObsoleteFiles(); + } + delete c; + + if (status.ok()) { + // Done + } else if (shutting_down_.Acquire_Load()) { + // Ignore compaction errors found during shutting down + } else { + Log(options_.info_log, + "Compaction error: %s", status.ToString().c_str()); + } + + if (is_manual) { + ManualCompaction* m = manual_compaction_; + if (!status.ok()) { + m->done = true; + } + if (!m->done) { + // We only compacted part of the requested range. Update *m + // to the range that is left to be compacted. + m->tmp_storage = manual_end; + m->begin = &m->tmp_storage; + } + manual_compaction_ = NULL; + } +} + +void DBImpl::CleanupCompaction(CompactionState* compact) { + mutex_.AssertHeld(); + if (compact->builder != NULL) { + // May happen if we get a shutdown call in the middle of compaction + compact->builder->Abandon(); + delete compact->builder; + } else { + assert(compact->outfile == NULL); + } + delete compact->outfile; + for (size_t i = 0; i < compact->outputs.size(); i++) { + const CompactionState::Output& out = compact->outputs[i]; + pending_outputs_.erase(out.number); + } + delete compact; +} + +Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) { + assert(compact != NULL); + assert(compact->builder == NULL); + uint64_t file_number; + { + mutex_.Lock(); + file_number = versions_->NewFileNumber(); + pending_outputs_.insert(file_number); + CompactionState::Output out; + out.number = file_number; + out.smallest.Clear(); + out.largest.Clear(); + compact->outputs.push_back(out); + mutex_.Unlock(); + } + + // Make the output file + std::string fname = TableFileName(dbname_, file_number); + Status s = env_->NewWritableFile(fname, &compact->outfile); + if (s.ok()) { + compact->builder = new TableBuilder(options_, compact->outfile); + } + return s; +} + +Status DBImpl::FinishCompactionOutputFile(CompactionState* compact, + Iterator* input) { + assert(compact != NULL); + assert(compact->outfile != NULL); + assert(compact->builder != NULL); + + const uint64_t output_number = compact->current_output()->number; + assert(output_number != 0); + + // Check for iterator errors + Status s = input->status(); + const uint64_t current_entries = compact->builder->NumEntries(); + if (s.ok()) { + s = compact->builder->Finish(); + } else { + compact->builder->Abandon(); + } + const uint64_t current_bytes = compact->builder->FileSize(); + compact->current_output()->file_size = current_bytes; + compact->total_bytes += current_bytes; + delete compact->builder; + compact->builder = NULL; + + // Finish and check for file errors + if (s.ok()) { + s = compact->outfile->Sync(); + } + if (s.ok()) { + s = compact->outfile->Close(); + } + delete compact->outfile; + compact->outfile = NULL; + + if (s.ok() && current_entries > 0) { + // Verify that the table is usable + Iterator* iter = table_cache_->NewIterator(ReadOptions(), + output_number, + current_bytes); + s = iter->status(); + delete iter; + if (s.ok()) { + Log(options_.info_log, + "Generated table #%llu@%d: %lld keys, %lld bytes", + (unsigned long long) output_number, + compact->compaction->level(), + (unsigned long long) current_entries, + (unsigned long long) current_bytes); + } + } + return s; +} + + +Status DBImpl::InstallCompactionResults(CompactionState* compact) { + mutex_.AssertHeld(); + Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes", + compact->compaction->num_input_files(0), + compact->compaction->level(), + compact->compaction->num_input_files(1), + compact->compaction->level() + 1, + static_cast(compact->total_bytes)); + + // Add compaction outputs + compact->compaction->AddInputDeletions(compact->compaction->edit()); + const int level = compact->compaction->level(); + for (size_t i = 0; i < compact->outputs.size(); i++) { + const CompactionState::Output& out = compact->outputs[i]; + compact->compaction->edit()->AddFile( + level + 1, + out.number, out.file_size, out.smallest, out.largest); + } + return versions_->LogAndApply(compact->compaction->edit(), &mutex_); +} + +Status DBImpl::DoCompactionWork(CompactionState* compact) { + const uint64_t start_micros = env_->NowMicros(); + int64_t imm_micros = 0; // Micros spent doing imm_ compactions + + Log(options_.info_log, "Compacting %d@%d + %d@%d files", + compact->compaction->num_input_files(0), + compact->compaction->level(), + compact->compaction->num_input_files(1), + compact->compaction->level() + 1); + + assert(versions_->NumLevelFiles(compact->compaction->level()) > 0); + assert(compact->builder == NULL); + assert(compact->outfile == NULL); + if (snapshots_.empty()) { + compact->smallest_snapshot = versions_->LastSequence(); + } else { + compact->smallest_snapshot = snapshots_.oldest()->number_; + } + + // Release mutex while we're actually doing the compaction work + mutex_.Unlock(); + + Iterator* input = versions_->MakeInputIterator(compact->compaction); + input->SeekToFirst(); + Status status; + ParsedInternalKey ikey; + std::string current_user_key; + bool has_current_user_key = false; + SequenceNumber last_sequence_for_key = kMaxSequenceNumber; + for (; input->Valid() && !shutting_down_.Acquire_Load(); ) { + // Prioritize immutable compaction work + if (has_imm_.NoBarrier_Load() != NULL) { + const uint64_t imm_start = env_->NowMicros(); + mutex_.Lock(); + if (imm_ != NULL) { + CompactMemTable(); + bg_cv_.SignalAll(); // Wakeup MakeRoomForWrite() if necessary + } + mutex_.Unlock(); + imm_micros += (env_->NowMicros() - imm_start); + } + + Slice key = input->key(); + if (compact->compaction->ShouldStopBefore(key) && + compact->builder != NULL) { + status = FinishCompactionOutputFile(compact, input); + if (!status.ok()) { + break; + } + } + + // Handle key/value, add to state, etc. + bool drop = false; + if (!ParseInternalKey(key, &ikey)) { + // Do not hide error keys + current_user_key.clear(); + has_current_user_key = false; + last_sequence_for_key = kMaxSequenceNumber; + } else { + if (!has_current_user_key || + user_comparator()->Compare(ikey.user_key, + Slice(current_user_key)) != 0) { + // First occurrence of this user key + current_user_key.assign(ikey.user_key.data(), ikey.user_key.size()); + has_current_user_key = true; + last_sequence_for_key = kMaxSequenceNumber; + } + + if (last_sequence_for_key <= compact->smallest_snapshot) { + // Hidden by an newer entry for same user key + drop = true; // (A) + } else if (ikey.type == kTypeDeletion && + ikey.sequence <= compact->smallest_snapshot && + compact->compaction->IsBaseLevelForKey(ikey.user_key)) { + // For this user key: + // (1) there is no data in higher levels + // (2) data in lower levels will have larger sequence numbers + // (3) data in layers that are being compacted here and have + // smaller sequence numbers will be dropped in the next + // few iterations of this loop (by rule (A) above). + // Therefore this deletion marker is obsolete and can be dropped. + drop = true; + } + + last_sequence_for_key = ikey.sequence; + } +#if 0 + Log(options_.info_log, + " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, " + "%d smallest_snapshot: %d", + ikey.user_key.ToString().c_str(), + (int)ikey.sequence, ikey.type, kTypeValue, drop, + compact->compaction->IsBaseLevelForKey(ikey.user_key), + (int)last_sequence_for_key, (int)compact->smallest_snapshot); +#endif + + if (!drop) { + // Open output file if necessary + if (compact->builder == NULL) { + status = OpenCompactionOutputFile(compact); + if (!status.ok()) { + break; + } + } + if (compact->builder->NumEntries() == 0) { + compact->current_output()->smallest.DecodeFrom(key); + } + compact->current_output()->largest.DecodeFrom(key); + compact->builder->Add(key, input->value()); + + // Close output file if it is big enough + if (compact->builder->FileSize() >= + compact->compaction->MaxOutputFileSize()) { + status = FinishCompactionOutputFile(compact, input); + if (!status.ok()) { + break; + } + } + } + + input->Next(); + } + + if (status.ok() && shutting_down_.Acquire_Load()) { + status = Status::IOError("Deleting DB during compaction"); + } + if (status.ok() && compact->builder != NULL) { + status = FinishCompactionOutputFile(compact, input); + } + if (status.ok()) { + status = input->status(); + } + delete input; + input = NULL; + + CompactionStats stats; + stats.micros = env_->NowMicros() - start_micros - imm_micros; + for (int which = 0; which < 2; which++) { + for (int i = 0; i < compact->compaction->num_input_files(which); i++) { + stats.bytes_read += compact->compaction->input(which, i)->file_size; + } + } + for (size_t i = 0; i < compact->outputs.size(); i++) { + stats.bytes_written += compact->outputs[i].file_size; + } + + mutex_.Lock(); + stats_[compact->compaction->level() + 1].Add(stats); + + if (status.ok()) { + status = InstallCompactionResults(compact); + } + if (!status.ok()) { + RecordBackgroundError(status); + } + VersionSet::LevelSummaryStorage tmp; + Log(options_.info_log, + "compacted to: %s", versions_->LevelSummary(&tmp)); + return status; +} + +namespace { +struct IterState { + port::Mutex* mu; + Version* version; + MemTable* mem; + MemTable* imm; +}; + +static void CleanupIteratorState(void* arg1, void* arg2) { + IterState* state = reinterpret_cast(arg1); + state->mu->Lock(); + state->mem->Unref(); + if (state->imm != NULL) state->imm->Unref(); + state->version->Unref(); + state->mu->Unlock(); + delete state; +} +} // namespace + +Iterator* DBImpl::NewInternalIterator(const ReadOptions& options, + SequenceNumber* latest_snapshot, + uint32_t* seed) { + IterState* cleanup = new IterState; + mutex_.Lock(); + *latest_snapshot = versions_->LastSequence(); + + // Collect together all needed child iterators + std::vector list; + list.push_back(mem_->NewIterator()); + mem_->Ref(); + if (imm_ != NULL) { + list.push_back(imm_->NewIterator()); + imm_->Ref(); + } + versions_->current()->AddIterators(options, &list); + Iterator* internal_iter = + NewMergingIterator(&internal_comparator_, &list[0], list.size()); + versions_->current()->Ref(); + + cleanup->mu = &mutex_; + cleanup->mem = mem_; + cleanup->imm = imm_; + cleanup->version = versions_->current(); + internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL); + + *seed = ++seed_; + mutex_.Unlock(); + return internal_iter; +} + +Iterator* DBImpl::TEST_NewInternalIterator() { + SequenceNumber ignored; + uint32_t ignored_seed; + return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed); +} + +int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() { + MutexLock l(&mutex_); + return versions_->MaxNextLevelOverlappingBytes(); +} + +Status DBImpl::Get(const ReadOptions& options, + const Slice& key, + std::string* value) { + Status s; + MutexLock l(&mutex_); + SequenceNumber snapshot; + if (options.snapshot != NULL) { + snapshot = reinterpret_cast(options.snapshot)->number_; + } else { + snapshot = versions_->LastSequence(); + } + + MemTable* mem = mem_; + MemTable* imm = imm_; + Version* current = versions_->current(); + mem->Ref(); + if (imm != NULL) imm->Ref(); + current->Ref(); + + bool have_stat_update = false; + Version::GetStats stats; + + // Unlock while reading from files and memtables + { + mutex_.Unlock(); + // First look in the memtable, then in the immutable memtable (if any). + LookupKey lkey(key, snapshot); + if (mem->Get(lkey, value, &s)) { + // Done + } else if (imm != NULL && imm->Get(lkey, value, &s)) { + // Done + } else { + s = current->Get(options, lkey, value, &stats); + have_stat_update = true; + } + mutex_.Lock(); + } + + if (have_stat_update && current->UpdateStats(stats)) { + MaybeScheduleCompaction(); + } + mem->Unref(); + if (imm != NULL) imm->Unref(); + current->Unref(); + return s; +} + +Iterator* DBImpl::NewIterator(const ReadOptions& options) { + SequenceNumber latest_snapshot; + uint32_t seed; + Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed); + return NewDBIterator( + this, user_comparator(), iter, + (options.snapshot != NULL + ? reinterpret_cast(options.snapshot)->number_ + : latest_snapshot), + seed); +} + +void DBImpl::RecordReadSample(Slice key) { + MutexLock l(&mutex_); + if (versions_->current()->RecordReadSample(key)) { + MaybeScheduleCompaction(); + } +} + +const Snapshot* DBImpl::GetSnapshot() { + MutexLock l(&mutex_); + return snapshots_.New(versions_->LastSequence()); +} + +void DBImpl::ReleaseSnapshot(const Snapshot* s) { + MutexLock l(&mutex_); + snapshots_.Delete(reinterpret_cast(s)); +} + +// Convenience methods +Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) { + return DB::Put(o, key, val); +} + +Status DBImpl::Delete(const WriteOptions& options, const Slice& key) { + return DB::Delete(options, key); +} + +Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) { + Writer w(&mutex_); + w.batch = my_batch; + w.sync = options.sync; + w.done = false; + + MutexLock l(&mutex_); + writers_.push_back(&w); + while (!w.done && &w != writers_.front()) { + w.cv.Wait(); + } + if (w.done) { + return w.status; + } + + // May temporarily unlock and wait. + Status status = MakeRoomForWrite(my_batch == NULL); + uint64_t last_sequence = versions_->LastSequence(); + Writer* last_writer = &w; + if (status.ok() && my_batch != NULL) { // NULL batch is for compactions + WriteBatch* updates = BuildBatchGroup(&last_writer); + WriteBatchInternal::SetSequence(updates, last_sequence + 1); + last_sequence += WriteBatchInternal::Count(updates); + + // Add to log and apply to memtable. We can release the lock + // during this phase since &w is currently responsible for logging + // and protects against concurrent loggers and concurrent writes + // into mem_. + { + mutex_.Unlock(); + status = log_->AddRecord(WriteBatchInternal::Contents(updates)); + bool sync_error = false; + if (status.ok() && options.sync) { + status = logfile_->Sync(); + if (!status.ok()) { + sync_error = true; + } + } + if (status.ok()) { + status = WriteBatchInternal::InsertInto(updates, mem_); + } + mutex_.Lock(); + if (sync_error) { + // The state of the log file is indeterminate: the log record we + // just added may or may not show up when the DB is re-opened. + // So we force the DB into a mode where all future writes fail. + RecordBackgroundError(status); + } + } + if (updates == tmp_batch_) tmp_batch_->Clear(); + + versions_->SetLastSequence(last_sequence); + } + + while (true) { + Writer* ready = writers_.front(); + writers_.pop_front(); + if (ready != &w) { + ready->status = status; + ready->done = true; + ready->cv.Signal(); + } + if (ready == last_writer) break; + } + + // Notify new head of write queue + if (!writers_.empty()) { + writers_.front()->cv.Signal(); + } + + return status; +} + +// REQUIRES: Writer list must be non-empty +// REQUIRES: First writer must have a non-NULL batch +WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) { + assert(!writers_.empty()); + Writer* first = writers_.front(); + WriteBatch* result = first->batch; + assert(result != NULL); + + size_t size = WriteBatchInternal::ByteSize(first->batch); + + // Allow the group to grow up to a maximum size, but if the + // original write is small, limit the growth so we do not slow + // down the small write too much. + size_t max_size = 1 << 20; + if (size <= (128<<10)) { + max_size = size + (128<<10); + } + + *last_writer = first; + std::deque::iterator iter = writers_.begin(); + ++iter; // Advance past "first" + for (; iter != writers_.end(); ++iter) { + Writer* w = *iter; + if (w->sync && !first->sync) { + // Do not include a sync write into a batch handled by a non-sync write. + break; + } + + if (w->batch != NULL) { + size += WriteBatchInternal::ByteSize(w->batch); + if (size > max_size) { + // Do not make batch too big + break; + } + + // Append to *result + if (result == first->batch) { + // Switch to temporary batch instead of disturbing caller's batch + result = tmp_batch_; + assert(WriteBatchInternal::Count(result) == 0); + WriteBatchInternal::Append(result, first->batch); + } + WriteBatchInternal::Append(result, w->batch); + } + *last_writer = w; + } + return result; +} + +// REQUIRES: mutex_ is held +// REQUIRES: this thread is currently at the front of the writer queue +Status DBImpl::MakeRoomForWrite(bool force) { + mutex_.AssertHeld(); + assert(!writers_.empty()); + bool allow_delay = !force; + Status s; + while (true) { + if (!bg_error_.ok()) { + // Yield previous error + s = bg_error_; + break; + } else if ( + allow_delay && + versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) { + // We are getting close to hitting a hard limit on the number of + // L0 files. Rather than delaying a single write by several + // seconds when we hit the hard limit, start delaying each + // individual write by 1ms to reduce latency variance. Also, + // this delay hands over some CPU to the compaction thread in + // case it is sharing the same core as the writer. + mutex_.Unlock(); + env_->SleepForMicroseconds(1000); + allow_delay = false; // Do not delay a single write more than once + mutex_.Lock(); + } else if (!force && + (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) { + // There is room in current memtable + break; + } else if (imm_ != NULL) { + // We have filled up the current memtable, but the previous + // one is still being compacted, so we wait. + Log(options_.info_log, "Current memtable full; waiting...\n"); + bg_cv_.Wait(); + } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) { + // There are too many level-0 files. + Log(options_.info_log, "Too many L0 files; waiting...\n"); + bg_cv_.Wait(); + } else { + // Attempt to switch to a new memtable and trigger compaction of old + assert(versions_->PrevLogNumber() == 0); + uint64_t new_log_number = versions_->NewFileNumber(); + WritableFile* lfile = NULL; + s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile); + if (!s.ok()) { + // Avoid chewing through file number space in a tight loop. + versions_->ReuseFileNumber(new_log_number); + break; + } + delete log_; + delete logfile_; + logfile_ = lfile; + logfile_number_ = new_log_number; + log_ = new log::Writer(lfile); + imm_ = mem_; + has_imm_.Release_Store(imm_); + mem_ = new MemTable(internal_comparator_); + mem_->Ref(); + force = false; // Do not force another compaction if have room + MaybeScheduleCompaction(); + } + } + return s; +} + +bool DBImpl::GetProperty(const Slice& property, std::string* value) { + value->clear(); + + MutexLock l(&mutex_); + Slice in = property; + Slice prefix("leveldb."); + if (!in.starts_with(prefix)) return false; + in.remove_prefix(prefix.size()); + + if (in.starts_with("num-files-at-level")) { + in.remove_prefix(strlen("num-files-at-level")); + uint64_t level; + bool ok = ConsumeDecimalNumber(&in, &level) && in.empty(); + if (!ok || level >= config::kNumLevels) { + return false; + } else { + char buf[100]; + snprintf(buf, sizeof(buf), "%d", + versions_->NumLevelFiles(static_cast(level))); + *value = buf; + return true; + } + } else if (in == "stats") { + char buf[200]; + snprintf(buf, sizeof(buf), + " Compactions\n" + "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n" + "--------------------------------------------------\n" + ); + value->append(buf); + for (int level = 0; level < config::kNumLevels; level++) { + int files = versions_->NumLevelFiles(level); + if (stats_[level].micros > 0 || files > 0) { + snprintf( + buf, sizeof(buf), + "%3d %8d %8.0f %9.0f %8.0f %9.0f\n", + level, + files, + versions_->NumLevelBytes(level) / 1048576.0, + stats_[level].micros / 1e6, + stats_[level].bytes_read / 1048576.0, + stats_[level].bytes_written / 1048576.0); + value->append(buf); + } + } + return true; + } else if (in == "sstables") { + *value = versions_->current()->DebugString(); + return true; + } else if (in == "approximate-memory-usage") { + size_t total_usage = options_.block_cache->TotalCharge(); + if (mem_) { + total_usage += mem_->ApproximateMemoryUsage(); + } + if (imm_) { + total_usage += imm_->ApproximateMemoryUsage(); + } + char buf[50]; + snprintf(buf, sizeof(buf), "%llu", + static_cast(total_usage)); + value->append(buf); + return true; + } + + return false; +} + +void DBImpl::GetApproximateSizes( + const Range* range, int n, + uint64_t* sizes) { + // TODO(opt): better implementation + Version* v; + { + MutexLock l(&mutex_); + versions_->current()->Ref(); + v = versions_->current(); + } + + for (int i = 0; i < n; i++) { + // Convert user_key into a corresponding internal key. + InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek); + InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek); + uint64_t start = versions_->ApproximateOffsetOf(v, k1); + uint64_t limit = versions_->ApproximateOffsetOf(v, k2); + sizes[i] = (limit >= start ? limit - start : 0); + } + + { + MutexLock l(&mutex_); + v->Unref(); + } +} + +// Default implementations of convenience methods that subclasses of DB +// can call if they wish +Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) { + WriteBatch batch; + batch.Put(key, value); + return Write(opt, &batch); +} + +Status DB::Delete(const WriteOptions& opt, const Slice& key) { + WriteBatch batch; + batch.Delete(key); + return Write(opt, &batch); +} + +DB::~DB() { } + +Status DB::Open(const Options& options, const std::string& dbname, + DB** dbptr) { + *dbptr = NULL; + + DBImpl* impl = new DBImpl(options, dbname); + impl->mutex_.Lock(); + VersionEdit edit; + // Recover handles create_if_missing, error_if_exists + bool save_manifest = false; + Status s = impl->Recover(&edit, &save_manifest); + if (s.ok() && impl->mem_ == NULL) { + // Create new log and a corresponding memtable. + uint64_t new_log_number = impl->versions_->NewFileNumber(); + WritableFile* lfile; + s = options.env->NewWritableFile(LogFileName(dbname, new_log_number), + &lfile); + if (s.ok()) { + edit.SetLogNumber(new_log_number); + impl->logfile_ = lfile; + impl->logfile_number_ = new_log_number; + impl->log_ = new log::Writer(lfile); + impl->mem_ = new MemTable(impl->internal_comparator_); + impl->mem_->Ref(); + } + } + if (s.ok() && save_manifest) { + edit.SetPrevLogNumber(0); // No older logs needed after recovery. + edit.SetLogNumber(impl->logfile_number_); + s = impl->versions_->LogAndApply(&edit, &impl->mutex_); + } + if (s.ok()) { + impl->DeleteObsoleteFiles(); + impl->MaybeScheduleCompaction(); + } + impl->mutex_.Unlock(); + if (s.ok()) { + assert(impl->mem_ != NULL); + *dbptr = impl; + } else { + delete impl; + } + return s; +} + +Snapshot::~Snapshot() { +} + +Status DestroyDB(const std::string& dbname, const Options& options) { + Env* env = options.env; + std::vector filenames; + // Ignore error in case directory does not exist + env->GetChildren(dbname, &filenames); + if (filenames.empty()) { + return Status::OK(); + } + + FileLock* lock; + const std::string lockname = LockFileName(dbname); + Status result = env->LockFile(lockname, &lock); + if (result.ok()) { + uint64_t number; + FileType type; + for (size_t i = 0; i < filenames.size(); i++) { + if (ParseFileName(filenames[i], &number, &type) && + type != kDBLockFile) { // Lock file will be deleted at end + Status del = env->DeleteFile(dbname + "/" + filenames[i]); + if (result.ok() && !del.ok()) { + result = del; + } + } + } + env->UnlockFile(lock); // Ignore error since state is already gone + env->DeleteFile(lockname); + env->DeleteDir(dbname); // Ignore error in case dir contains other files + } + return result; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/db_impl.h b/My Mind/Pods/leveldb-library/db/db_impl.h new file mode 100644 index 0000000..8ff323e --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/db_impl.h @@ -0,0 +1,211 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_DB_IMPL_H_ +#define STORAGE_LEVELDB_DB_DB_IMPL_H_ + +#include +#include +#include "db/dbformat.h" +#include "db/log_writer.h" +#include "db/snapshot.h" +#include "leveldb/db.h" +#include "leveldb/env.h" +#include "port/port.h" +#include "port/thread_annotations.h" + +namespace leveldb { + +class MemTable; +class TableCache; +class Version; +class VersionEdit; +class VersionSet; + +class DBImpl : public DB { + public: + DBImpl(const Options& options, const std::string& dbname); + virtual ~DBImpl(); + + // Implementations of the DB interface + virtual Status Put(const WriteOptions&, const Slice& key, const Slice& value); + virtual Status Delete(const WriteOptions&, const Slice& key); + virtual Status Write(const WriteOptions& options, WriteBatch* updates); + virtual Status Get(const ReadOptions& options, + const Slice& key, + std::string* value); + virtual Iterator* NewIterator(const ReadOptions&); + virtual const Snapshot* GetSnapshot(); + virtual void ReleaseSnapshot(const Snapshot* snapshot); + virtual bool GetProperty(const Slice& property, std::string* value); + virtual void GetApproximateSizes(const Range* range, int n, uint64_t* sizes); + virtual void CompactRange(const Slice* begin, const Slice* end); + + // Extra methods (for testing) that are not in the public DB interface + + // Compact any files in the named level that overlap [*begin,*end] + void TEST_CompactRange(int level, const Slice* begin, const Slice* end); + + // Force current memtable contents to be compacted. + Status TEST_CompactMemTable(); + + // Return an internal iterator over the current state of the database. + // The keys of this iterator are internal keys (see format.h). + // The returned iterator should be deleted when no longer needed. + Iterator* TEST_NewInternalIterator(); + + // Return the maximum overlapping data (in bytes) at next level for any + // file at a level >= 1. + int64_t TEST_MaxNextLevelOverlappingBytes(); + + // Record a sample of bytes read at the specified internal key. + // Samples are taken approximately once every config::kReadBytesPeriod + // bytes. + void RecordReadSample(Slice key); + + private: + friend class DB; + struct CompactionState; + struct Writer; + + Iterator* NewInternalIterator(const ReadOptions&, + SequenceNumber* latest_snapshot, + uint32_t* seed); + + Status NewDB(); + + // Recover the descriptor from persistent storage. May do a significant + // amount of work to recover recently logged updates. Any changes to + // be made to the descriptor are added to *edit. + Status Recover(VersionEdit* edit, bool* save_manifest) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + void MaybeIgnoreError(Status* s) const; + + // Delete any unneeded files and stale in-memory entries. + void DeleteObsoleteFiles(); + + // Compact the in-memory write buffer to disk. Switches to a new + // log-file/memtable and writes a new descriptor iff successful. + // Errors are recorded in bg_error_. + void CompactMemTable() EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + Status RecoverLogFile(uint64_t log_number, bool last_log, bool* save_manifest, + VersionEdit* edit, SequenceNumber* max_sequence) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + Status WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + Status MakeRoomForWrite(bool force /* compact even if there is room? */) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + WriteBatch* BuildBatchGroup(Writer** last_writer); + + void RecordBackgroundError(const Status& s); + + void MaybeScheduleCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_); + static void BGWork(void* db); + void BackgroundCall(); + void BackgroundCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_); + void CleanupCompaction(CompactionState* compact) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + Status DoCompactionWork(CompactionState* compact) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + Status OpenCompactionOutputFile(CompactionState* compact); + Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input); + Status InstallCompactionResults(CompactionState* compact) + EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Constant after construction + Env* const env_; + const InternalKeyComparator internal_comparator_; + const InternalFilterPolicy internal_filter_policy_; + const Options options_; // options_.comparator == &internal_comparator_ + bool owns_info_log_; + bool owns_cache_; + const std::string dbname_; + + // table_cache_ provides its own synchronization + TableCache* table_cache_; + + // Lock over the persistent DB state. Non-NULL iff successfully acquired. + FileLock* db_lock_; + + // State below is protected by mutex_ + port::Mutex mutex_; + port::AtomicPointer shutting_down_; + port::CondVar bg_cv_; // Signalled when background work finishes + MemTable* mem_; + MemTable* imm_; // Memtable being compacted + port::AtomicPointer has_imm_; // So bg thread can detect non-NULL imm_ + WritableFile* logfile_; + uint64_t logfile_number_; + log::Writer* log_; + uint32_t seed_; // For sampling. + + // Queue of writers. + std::deque writers_; + WriteBatch* tmp_batch_; + + SnapshotList snapshots_; + + // Set of table files to protect from deletion because they are + // part of ongoing compactions. + std::set pending_outputs_; + + // Has a background compaction been scheduled or is running? + bool bg_compaction_scheduled_; + + // Information for a manual compaction + struct ManualCompaction { + int level; + bool done; + const InternalKey* begin; // NULL means beginning of key range + const InternalKey* end; // NULL means end of key range + InternalKey tmp_storage; // Used to keep track of compaction progress + }; + ManualCompaction* manual_compaction_; + + VersionSet* versions_; + + // Have we encountered a background error in paranoid mode? + Status bg_error_; + + // Per level compaction stats. stats_[level] stores the stats for + // compactions that produced data for the specified "level". + struct CompactionStats { + int64_t micros; + int64_t bytes_read; + int64_t bytes_written; + + CompactionStats() : micros(0), bytes_read(0), bytes_written(0) { } + + void Add(const CompactionStats& c) { + this->micros += c.micros; + this->bytes_read += c.bytes_read; + this->bytes_written += c.bytes_written; + } + }; + CompactionStats stats_[config::kNumLevels]; + + // No copying allowed + DBImpl(const DBImpl&); + void operator=(const DBImpl&); + + const Comparator* user_comparator() const { + return internal_comparator_.user_comparator(); + } +}; + +// Sanitize db options. The caller should delete result.info_log if +// it is not equal to src.info_log. +extern Options SanitizeOptions(const std::string& db, + const InternalKeyComparator* icmp, + const InternalFilterPolicy* ipolicy, + const Options& src); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_DB_IMPL_H_ diff --git a/My Mind/Pods/leveldb-library/db/db_iter.cc b/My Mind/Pods/leveldb-library/db/db_iter.cc new file mode 100644 index 0000000..3b2035e --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/db_iter.cc @@ -0,0 +1,317 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/db_iter.h" + +#include "db/filename.h" +#include "db/db_impl.h" +#include "db/dbformat.h" +#include "leveldb/env.h" +#include "leveldb/iterator.h" +#include "port/port.h" +#include "util/logging.h" +#include "util/mutexlock.h" +#include "util/random.h" + +namespace leveldb { + +#if 0 +static void DumpInternalIter(Iterator* iter) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { + ParsedInternalKey k; + if (!ParseInternalKey(iter->key(), &k)) { + fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str()); + } else { + fprintf(stderr, "@ '%s'\n", k.DebugString().c_str()); + } + } +} +#endif + +namespace { + +// Memtables and sstables that make the DB representation contain +// (userkey,seq,type) => uservalue entries. DBIter +// combines multiple entries for the same userkey found in the DB +// representation into a single entry while accounting for sequence +// numbers, deletion markers, overwrites, etc. +class DBIter: public Iterator { + public: + // Which direction is the iterator currently moving? + // (1) When moving forward, the internal iterator is positioned at + // the exact entry that yields this->key(), this->value() + // (2) When moving backwards, the internal iterator is positioned + // just before all entries whose user key == this->key(). + enum Direction { + kForward, + kReverse + }; + + DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s, + uint32_t seed) + : db_(db), + user_comparator_(cmp), + iter_(iter), + sequence_(s), + direction_(kForward), + valid_(false), + rnd_(seed), + bytes_counter_(RandomPeriod()) { + } + virtual ~DBIter() { + delete iter_; + } + virtual bool Valid() const { return valid_; } + virtual Slice key() const { + assert(valid_); + return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_; + } + virtual Slice value() const { + assert(valid_); + return (direction_ == kForward) ? iter_->value() : saved_value_; + } + virtual Status status() const { + if (status_.ok()) { + return iter_->status(); + } else { + return status_; + } + } + + virtual void Next(); + virtual void Prev(); + virtual void Seek(const Slice& target); + virtual void SeekToFirst(); + virtual void SeekToLast(); + + private: + void FindNextUserEntry(bool skipping, std::string* skip); + void FindPrevUserEntry(); + bool ParseKey(ParsedInternalKey* key); + + inline void SaveKey(const Slice& k, std::string* dst) { + dst->assign(k.data(), k.size()); + } + + inline void ClearSavedValue() { + if (saved_value_.capacity() > 1048576) { + std::string empty; + swap(empty, saved_value_); + } else { + saved_value_.clear(); + } + } + + // Pick next gap with average value of config::kReadBytesPeriod. + ssize_t RandomPeriod() { + return rnd_.Uniform(2*config::kReadBytesPeriod); + } + + DBImpl* db_; + const Comparator* const user_comparator_; + Iterator* const iter_; + SequenceNumber const sequence_; + + Status status_; + std::string saved_key_; // == current key when direction_==kReverse + std::string saved_value_; // == current raw value when direction_==kReverse + Direction direction_; + bool valid_; + + Random rnd_; + ssize_t bytes_counter_; + + // No copying allowed + DBIter(const DBIter&); + void operator=(const DBIter&); +}; + +inline bool DBIter::ParseKey(ParsedInternalKey* ikey) { + Slice k = iter_->key(); + ssize_t n = k.size() + iter_->value().size(); + bytes_counter_ -= n; + while (bytes_counter_ < 0) { + bytes_counter_ += RandomPeriod(); + db_->RecordReadSample(k); + } + if (!ParseInternalKey(k, ikey)) { + status_ = Status::Corruption("corrupted internal key in DBIter"); + return false; + } else { + return true; + } +} + +void DBIter::Next() { + assert(valid_); + + if (direction_ == kReverse) { // Switch directions? + direction_ = kForward; + // iter_ is pointing just before the entries for this->key(), + // so advance into the range of entries for this->key() and then + // use the normal skipping code below. + if (!iter_->Valid()) { + iter_->SeekToFirst(); + } else { + iter_->Next(); + } + if (!iter_->Valid()) { + valid_ = false; + saved_key_.clear(); + return; + } + // saved_key_ already contains the key to skip past. + } else { + // Store in saved_key_ the current key so we skip it below. + SaveKey(ExtractUserKey(iter_->key()), &saved_key_); + } + + FindNextUserEntry(true, &saved_key_); +} + +void DBIter::FindNextUserEntry(bool skipping, std::string* skip) { + // Loop until we hit an acceptable entry to yield + assert(iter_->Valid()); + assert(direction_ == kForward); + do { + ParsedInternalKey ikey; + if (ParseKey(&ikey) && ikey.sequence <= sequence_) { + switch (ikey.type) { + case kTypeDeletion: + // Arrange to skip all upcoming entries for this key since + // they are hidden by this deletion. + SaveKey(ikey.user_key, skip); + skipping = true; + break; + case kTypeValue: + if (skipping && + user_comparator_->Compare(ikey.user_key, *skip) <= 0) { + // Entry hidden + } else { + valid_ = true; + saved_key_.clear(); + return; + } + break; + } + } + iter_->Next(); + } while (iter_->Valid()); + saved_key_.clear(); + valid_ = false; +} + +void DBIter::Prev() { + assert(valid_); + + if (direction_ == kForward) { // Switch directions? + // iter_ is pointing at the current entry. Scan backwards until + // the key changes so we can use the normal reverse scanning code. + assert(iter_->Valid()); // Otherwise valid_ would have been false + SaveKey(ExtractUserKey(iter_->key()), &saved_key_); + while (true) { + iter_->Prev(); + if (!iter_->Valid()) { + valid_ = false; + saved_key_.clear(); + ClearSavedValue(); + return; + } + if (user_comparator_->Compare(ExtractUserKey(iter_->key()), + saved_key_) < 0) { + break; + } + } + direction_ = kReverse; + } + + FindPrevUserEntry(); +} + +void DBIter::FindPrevUserEntry() { + assert(direction_ == kReverse); + + ValueType value_type = kTypeDeletion; + if (iter_->Valid()) { + do { + ParsedInternalKey ikey; + if (ParseKey(&ikey) && ikey.sequence <= sequence_) { + if ((value_type != kTypeDeletion) && + user_comparator_->Compare(ikey.user_key, saved_key_) < 0) { + // We encountered a non-deleted value in entries for previous keys, + break; + } + value_type = ikey.type; + if (value_type == kTypeDeletion) { + saved_key_.clear(); + ClearSavedValue(); + } else { + Slice raw_value = iter_->value(); + if (saved_value_.capacity() > raw_value.size() + 1048576) { + std::string empty; + swap(empty, saved_value_); + } + SaveKey(ExtractUserKey(iter_->key()), &saved_key_); + saved_value_.assign(raw_value.data(), raw_value.size()); + } + } + iter_->Prev(); + } while (iter_->Valid()); + } + + if (value_type == kTypeDeletion) { + // End + valid_ = false; + saved_key_.clear(); + ClearSavedValue(); + direction_ = kForward; + } else { + valid_ = true; + } +} + +void DBIter::Seek(const Slice& target) { + direction_ = kForward; + ClearSavedValue(); + saved_key_.clear(); + AppendInternalKey( + &saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek)); + iter_->Seek(saved_key_); + if (iter_->Valid()) { + FindNextUserEntry(false, &saved_key_ /* temporary storage */); + } else { + valid_ = false; + } +} + +void DBIter::SeekToFirst() { + direction_ = kForward; + ClearSavedValue(); + iter_->SeekToFirst(); + if (iter_->Valid()) { + FindNextUserEntry(false, &saved_key_ /* temporary storage */); + } else { + valid_ = false; + } +} + +void DBIter::SeekToLast() { + direction_ = kReverse; + ClearSavedValue(); + iter_->SeekToLast(); + FindPrevUserEntry(); +} + +} // anonymous namespace + +Iterator* NewDBIterator( + DBImpl* db, + const Comparator* user_key_comparator, + Iterator* internal_iter, + SequenceNumber sequence, + uint32_t seed) { + return new DBIter(db, user_key_comparator, internal_iter, sequence, seed); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/db_iter.h b/My Mind/Pods/leveldb-library/db/db_iter.h new file mode 100644 index 0000000..04927e9 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/db_iter.h @@ -0,0 +1,28 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_DB_ITER_H_ +#define STORAGE_LEVELDB_DB_DB_ITER_H_ + +#include +#include "leveldb/db.h" +#include "db/dbformat.h" + +namespace leveldb { + +class DBImpl; + +// Return a new iterator that converts internal keys (yielded by +// "*internal_iter") that were live at the specified "sequence" number +// into appropriate user keys. +extern Iterator* NewDBIterator( + DBImpl* db, + const Comparator* user_key_comparator, + Iterator* internal_iter, + SequenceNumber sequence, + uint32_t seed); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_DB_ITER_H_ diff --git a/My Mind/Pods/leveldb-library/db/dbformat.cc b/My Mind/Pods/leveldb-library/db/dbformat.cc new file mode 100644 index 0000000..20a7ca4 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/dbformat.cc @@ -0,0 +1,140 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include "db/dbformat.h" +#include "port/port.h" +#include "util/coding.h" + +namespace leveldb { + +static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) { + assert(seq <= kMaxSequenceNumber); + assert(t <= kValueTypeForSeek); + return (seq << 8) | t; +} + +void AppendInternalKey(std::string* result, const ParsedInternalKey& key) { + result->append(key.user_key.data(), key.user_key.size()); + PutFixed64(result, PackSequenceAndType(key.sequence, key.type)); +} + +std::string ParsedInternalKey::DebugString() const { + char buf[50]; + snprintf(buf, sizeof(buf), "' @ %llu : %d", + (unsigned long long) sequence, + int(type)); + std::string result = "'"; + result += EscapeString(user_key.ToString()); + result += buf; + return result; +} + +std::string InternalKey::DebugString() const { + std::string result; + ParsedInternalKey parsed; + if (ParseInternalKey(rep_, &parsed)) { + result = parsed.DebugString(); + } else { + result = "(bad)"; + result.append(EscapeString(rep_)); + } + return result; +} + +const char* InternalKeyComparator::Name() const { + return "leveldb.InternalKeyComparator"; +} + +int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const { + // Order by: + // increasing user key (according to user-supplied comparator) + // decreasing sequence number + // decreasing type (though sequence# should be enough to disambiguate) + int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey)); + if (r == 0) { + const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8); + const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8); + if (anum > bnum) { + r = -1; + } else if (anum < bnum) { + r = +1; + } + } + return r; +} + +void InternalKeyComparator::FindShortestSeparator( + std::string* start, + const Slice& limit) const { + // Attempt to shorten the user portion of the key + Slice user_start = ExtractUserKey(*start); + Slice user_limit = ExtractUserKey(limit); + std::string tmp(user_start.data(), user_start.size()); + user_comparator_->FindShortestSeparator(&tmp, user_limit); + if (tmp.size() < user_start.size() && + user_comparator_->Compare(user_start, tmp) < 0) { + // User key has become shorter physically, but larger logically. + // Tack on the earliest possible number to the shortened user key. + PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek)); + assert(this->Compare(*start, tmp) < 0); + assert(this->Compare(tmp, limit) < 0); + start->swap(tmp); + } +} + +void InternalKeyComparator::FindShortSuccessor(std::string* key) const { + Slice user_key = ExtractUserKey(*key); + std::string tmp(user_key.data(), user_key.size()); + user_comparator_->FindShortSuccessor(&tmp); + if (tmp.size() < user_key.size() && + user_comparator_->Compare(user_key, tmp) < 0) { + // User key has become shorter physically, but larger logically. + // Tack on the earliest possible number to the shortened user key. + PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek)); + assert(this->Compare(*key, tmp) < 0); + key->swap(tmp); + } +} + +const char* InternalFilterPolicy::Name() const { + return user_policy_->Name(); +} + +void InternalFilterPolicy::CreateFilter(const Slice* keys, int n, + std::string* dst) const { + // We rely on the fact that the code in table.cc does not mind us + // adjusting keys[]. + Slice* mkey = const_cast(keys); + for (int i = 0; i < n; i++) { + mkey[i] = ExtractUserKey(keys[i]); + // TODO(sanjay): Suppress dups? + } + user_policy_->CreateFilter(keys, n, dst); +} + +bool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const { + return user_policy_->KeyMayMatch(ExtractUserKey(key), f); +} + +LookupKey::LookupKey(const Slice& user_key, SequenceNumber s) { + size_t usize = user_key.size(); + size_t needed = usize + 13; // A conservative estimate + char* dst; + if (needed <= sizeof(space_)) { + dst = space_; + } else { + dst = new char[needed]; + } + start_ = dst; + dst = EncodeVarint32(dst, usize + 8); + kstart_ = dst; + memcpy(dst, user_key.data(), usize); + dst += usize; + EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek)); + dst += 8; + end_ = dst; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/dbformat.h b/My Mind/Pods/leveldb-library/db/dbformat.h new file mode 100644 index 0000000..ea897b1 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/dbformat.h @@ -0,0 +1,230 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_DBFORMAT_H_ +#define STORAGE_LEVELDB_DB_DBFORMAT_H_ + +#include +#include "leveldb/comparator.h" +#include "leveldb/db.h" +#include "leveldb/filter_policy.h" +#include "leveldb/slice.h" +#include "leveldb/table_builder.h" +#include "util/coding.h" +#include "util/logging.h" + +namespace leveldb { + +// Grouping of constants. We may want to make some of these +// parameters set via options. +namespace config { +static const int kNumLevels = 7; + +// Level-0 compaction is started when we hit this many files. +static const int kL0_CompactionTrigger = 4; + +// Soft limit on number of level-0 files. We slow down writes at this point. +static const int kL0_SlowdownWritesTrigger = 8; + +// Maximum number of level-0 files. We stop writes at this point. +static const int kL0_StopWritesTrigger = 12; + +// Maximum level to which a new compacted memtable is pushed if it +// does not create overlap. We try to push to level 2 to avoid the +// relatively expensive level 0=>1 compactions and to avoid some +// expensive manifest file operations. We do not push all the way to +// the largest level since that can generate a lot of wasted disk +// space if the same key space is being repeatedly overwritten. +static const int kMaxMemCompactLevel = 2; + +// Approximate gap in bytes between samples of data read during iteration. +static const int kReadBytesPeriod = 1048576; + +} // namespace config + +class InternalKey; + +// Value types encoded as the last component of internal keys. +// DO NOT CHANGE THESE ENUM VALUES: they are embedded in the on-disk +// data structures. +enum ValueType { + kTypeDeletion = 0x0, + kTypeValue = 0x1 +}; +// kValueTypeForSeek defines the ValueType that should be passed when +// constructing a ParsedInternalKey object for seeking to a particular +// sequence number (since we sort sequence numbers in decreasing order +// and the value type is embedded as the low 8 bits in the sequence +// number in internal keys, we need to use the highest-numbered +// ValueType, not the lowest). +static const ValueType kValueTypeForSeek = kTypeValue; + +typedef uint64_t SequenceNumber; + +// We leave eight bits empty at the bottom so a type and sequence# +// can be packed together into 64-bits. +static const SequenceNumber kMaxSequenceNumber = + ((0x1ull << 56) - 1); + +struct ParsedInternalKey { + Slice user_key; + SequenceNumber sequence; + ValueType type; + + ParsedInternalKey() { } // Intentionally left uninitialized (for speed) + ParsedInternalKey(const Slice& u, const SequenceNumber& seq, ValueType t) + : user_key(u), sequence(seq), type(t) { } + std::string DebugString() const; +}; + +// Return the length of the encoding of "key". +inline size_t InternalKeyEncodingLength(const ParsedInternalKey& key) { + return key.user_key.size() + 8; +} + +// Append the serialization of "key" to *result. +extern void AppendInternalKey(std::string* result, + const ParsedInternalKey& key); + +// Attempt to parse an internal key from "internal_key". On success, +// stores the parsed data in "*result", and returns true. +// +// On error, returns false, leaves "*result" in an undefined state. +extern bool ParseInternalKey(const Slice& internal_key, + ParsedInternalKey* result); + +// Returns the user key portion of an internal key. +inline Slice ExtractUserKey(const Slice& internal_key) { + assert(internal_key.size() >= 8); + return Slice(internal_key.data(), internal_key.size() - 8); +} + +inline ValueType ExtractValueType(const Slice& internal_key) { + assert(internal_key.size() >= 8); + const size_t n = internal_key.size(); + uint64_t num = DecodeFixed64(internal_key.data() + n - 8); + unsigned char c = num & 0xff; + return static_cast(c); +} + +// A comparator for internal keys that uses a specified comparator for +// the user key portion and breaks ties by decreasing sequence number. +class InternalKeyComparator : public Comparator { + private: + const Comparator* user_comparator_; + public: + explicit InternalKeyComparator(const Comparator* c) : user_comparator_(c) { } + virtual const char* Name() const; + virtual int Compare(const Slice& a, const Slice& b) const; + virtual void FindShortestSeparator( + std::string* start, + const Slice& limit) const; + virtual void FindShortSuccessor(std::string* key) const; + + const Comparator* user_comparator() const { return user_comparator_; } + + int Compare(const InternalKey& a, const InternalKey& b) const; +}; + +// Filter policy wrapper that converts from internal keys to user keys +class InternalFilterPolicy : public FilterPolicy { + private: + const FilterPolicy* const user_policy_; + public: + explicit InternalFilterPolicy(const FilterPolicy* p) : user_policy_(p) { } + virtual const char* Name() const; + virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const; + virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const; +}; + +// Modules in this directory should keep internal keys wrapped inside +// the following class instead of plain strings so that we do not +// incorrectly use string comparisons instead of an InternalKeyComparator. +class InternalKey { + private: + std::string rep_; + public: + InternalKey() { } // Leave rep_ as empty to indicate it is invalid + InternalKey(const Slice& user_key, SequenceNumber s, ValueType t) { + AppendInternalKey(&rep_, ParsedInternalKey(user_key, s, t)); + } + + void DecodeFrom(const Slice& s) { rep_.assign(s.data(), s.size()); } + Slice Encode() const { + assert(!rep_.empty()); + return rep_; + } + + Slice user_key() const { return ExtractUserKey(rep_); } + + void SetFrom(const ParsedInternalKey& p) { + rep_.clear(); + AppendInternalKey(&rep_, p); + } + + void Clear() { rep_.clear(); } + + std::string DebugString() const; +}; + +inline int InternalKeyComparator::Compare( + const InternalKey& a, const InternalKey& b) const { + return Compare(a.Encode(), b.Encode()); +} + +inline bool ParseInternalKey(const Slice& internal_key, + ParsedInternalKey* result) { + const size_t n = internal_key.size(); + if (n < 8) return false; + uint64_t num = DecodeFixed64(internal_key.data() + n - 8); + unsigned char c = num & 0xff; + result->sequence = num >> 8; + result->type = static_cast(c); + result->user_key = Slice(internal_key.data(), n - 8); + return (c <= static_cast(kTypeValue)); +} + +// A helper class useful for DBImpl::Get() +class LookupKey { + public: + // Initialize *this for looking up user_key at a snapshot with + // the specified sequence number. + LookupKey(const Slice& user_key, SequenceNumber sequence); + + ~LookupKey(); + + // Return a key suitable for lookup in a MemTable. + Slice memtable_key() const { return Slice(start_, end_ - start_); } + + // Return an internal key (suitable for passing to an internal iterator) + Slice internal_key() const { return Slice(kstart_, end_ - kstart_); } + + // Return the user key + Slice user_key() const { return Slice(kstart_, end_ - kstart_ - 8); } + + private: + // We construct a char array of the form: + // klength varint32 <-- start_ + // userkey char[klength] <-- kstart_ + // tag uint64 + // <-- end_ + // The array is a suitable MemTable key. + // The suffix starting with "userkey" can be used as an InternalKey. + const char* start_; + const char* kstart_; + const char* end_; + char space_[200]; // Avoid allocation for short keys + + // No copying allowed + LookupKey(const LookupKey&); + void operator=(const LookupKey&); +}; + +inline LookupKey::~LookupKey() { + if (start_ != space_) delete[] start_; +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_DBFORMAT_H_ diff --git a/My Mind/Pods/leveldb-library/db/dumpfile.cc b/My Mind/Pods/leveldb-library/db/dumpfile.cc new file mode 100644 index 0000000..61c47c2 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/dumpfile.cc @@ -0,0 +1,225 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include "db/dbformat.h" +#include "db/filename.h" +#include "db/log_reader.h" +#include "db/version_edit.h" +#include "db/write_batch_internal.h" +#include "leveldb/env.h" +#include "leveldb/iterator.h" +#include "leveldb/options.h" +#include "leveldb/status.h" +#include "leveldb/table.h" +#include "leveldb/write_batch.h" +#include "util/logging.h" + +namespace leveldb { + +namespace { + +bool GuessType(const std::string& fname, FileType* type) { + size_t pos = fname.rfind('/'); + std::string basename; + if (pos == std::string::npos) { + basename = fname; + } else { + basename = std::string(fname.data() + pos + 1, fname.size() - pos - 1); + } + uint64_t ignored; + return ParseFileName(basename, &ignored, type); +} + +// Notified when log reader encounters corruption. +class CorruptionReporter : public log::Reader::Reporter { + public: + WritableFile* dst_; + virtual void Corruption(size_t bytes, const Status& status) { + std::string r = "corruption: "; + AppendNumberTo(&r, bytes); + r += " bytes; "; + r += status.ToString(); + r.push_back('\n'); + dst_->Append(r); + } +}; + +// Print contents of a log file. (*func)() is called on every record. +Status PrintLogContents(Env* env, const std::string& fname, + void (*func)(uint64_t, Slice, WritableFile*), + WritableFile* dst) { + SequentialFile* file; + Status s = env->NewSequentialFile(fname, &file); + if (!s.ok()) { + return s; + } + CorruptionReporter reporter; + reporter.dst_ = dst; + log::Reader reader(file, &reporter, true, 0); + Slice record; + std::string scratch; + while (reader.ReadRecord(&record, &scratch)) { + (*func)(reader.LastRecordOffset(), record, dst); + } + delete file; + return Status::OK(); +} + +// Called on every item found in a WriteBatch. +class WriteBatchItemPrinter : public WriteBatch::Handler { + public: + WritableFile* dst_; + virtual void Put(const Slice& key, const Slice& value) { + std::string r = " put '"; + AppendEscapedStringTo(&r, key); + r += "' '"; + AppendEscapedStringTo(&r, value); + r += "'\n"; + dst_->Append(r); + } + virtual void Delete(const Slice& key) { + std::string r = " del '"; + AppendEscapedStringTo(&r, key); + r += "'\n"; + dst_->Append(r); + } +}; + + +// Called on every log record (each one of which is a WriteBatch) +// found in a kLogFile. +static void WriteBatchPrinter(uint64_t pos, Slice record, WritableFile* dst) { + std::string r = "--- offset "; + AppendNumberTo(&r, pos); + r += "; "; + if (record.size() < 12) { + r += "log record length "; + AppendNumberTo(&r, record.size()); + r += " is too small\n"; + dst->Append(r); + return; + } + WriteBatch batch; + WriteBatchInternal::SetContents(&batch, record); + r += "sequence "; + AppendNumberTo(&r, WriteBatchInternal::Sequence(&batch)); + r.push_back('\n'); + dst->Append(r); + WriteBatchItemPrinter batch_item_printer; + batch_item_printer.dst_ = dst; + Status s = batch.Iterate(&batch_item_printer); + if (!s.ok()) { + dst->Append(" error: " + s.ToString() + "\n"); + } +} + +Status DumpLog(Env* env, const std::string& fname, WritableFile* dst) { + return PrintLogContents(env, fname, WriteBatchPrinter, dst); +} + +// Called on every log record (each one of which is a WriteBatch) +// found in a kDescriptorFile. +static void VersionEditPrinter(uint64_t pos, Slice record, WritableFile* dst) { + std::string r = "--- offset "; + AppendNumberTo(&r, pos); + r += "; "; + VersionEdit edit; + Status s = edit.DecodeFrom(record); + if (!s.ok()) { + r += s.ToString(); + r.push_back('\n'); + } else { + r += edit.DebugString(); + } + dst->Append(r); +} + +Status DumpDescriptor(Env* env, const std::string& fname, WritableFile* dst) { + return PrintLogContents(env, fname, VersionEditPrinter, dst); +} + +Status DumpTable(Env* env, const std::string& fname, WritableFile* dst) { + uint64_t file_size; + RandomAccessFile* file = NULL; + Table* table = NULL; + Status s = env->GetFileSize(fname, &file_size); + if (s.ok()) { + s = env->NewRandomAccessFile(fname, &file); + } + if (s.ok()) { + // We use the default comparator, which may or may not match the + // comparator used in this database. However this should not cause + // problems since we only use Table operations that do not require + // any comparisons. In particular, we do not call Seek or Prev. + s = Table::Open(Options(), file, file_size, &table); + } + if (!s.ok()) { + delete table; + delete file; + return s; + } + + ReadOptions ro; + ro.fill_cache = false; + Iterator* iter = table->NewIterator(ro); + std::string r; + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { + r.clear(); + ParsedInternalKey key; + if (!ParseInternalKey(iter->key(), &key)) { + r = "badkey '"; + AppendEscapedStringTo(&r, iter->key()); + r += "' => '"; + AppendEscapedStringTo(&r, iter->value()); + r += "'\n"; + dst->Append(r); + } else { + r = "'"; + AppendEscapedStringTo(&r, key.user_key); + r += "' @ "; + AppendNumberTo(&r, key.sequence); + r += " : "; + if (key.type == kTypeDeletion) { + r += "del"; + } else if (key.type == kTypeValue) { + r += "val"; + } else { + AppendNumberTo(&r, key.type); + } + r += " => '"; + AppendEscapedStringTo(&r, iter->value()); + r += "'\n"; + dst->Append(r); + } + } + s = iter->status(); + if (!s.ok()) { + dst->Append("iterator error: " + s.ToString() + "\n"); + } + + delete iter; + delete table; + delete file; + return Status::OK(); +} + +} // namespace + +Status DumpFile(Env* env, const std::string& fname, WritableFile* dst) { + FileType ftype; + if (!GuessType(fname, &ftype)) { + return Status::InvalidArgument(fname + ": unknown file type"); + } + switch (ftype) { + case kLogFile: return DumpLog(env, fname, dst); + case kDescriptorFile: return DumpDescriptor(env, fname, dst); + case kTableFile: return DumpTable(env, fname, dst); + default: + break; + } + return Status::InvalidArgument(fname + ": not a dump-able file type"); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/filename.cc b/My Mind/Pods/leveldb-library/db/filename.cc new file mode 100644 index 0000000..da32946 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/filename.cc @@ -0,0 +1,144 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include +#include "db/filename.h" +#include "db/dbformat.h" +#include "leveldb/env.h" +#include "util/logging.h" + +namespace leveldb { + +// A utility routine: write "data" to the named file and Sync() it. +extern Status WriteStringToFileSync(Env* env, const Slice& data, + const std::string& fname); + +static std::string MakeFileName(const std::string& name, uint64_t number, + const char* suffix) { + char buf[100]; + snprintf(buf, sizeof(buf), "/%06llu.%s", + static_cast(number), + suffix); + return name + buf; +} + +std::string LogFileName(const std::string& name, uint64_t number) { + assert(number > 0); + return MakeFileName(name, number, "log"); +} + +std::string TableFileName(const std::string& name, uint64_t number) { + assert(number > 0); + return MakeFileName(name, number, "ldb"); +} + +std::string SSTTableFileName(const std::string& name, uint64_t number) { + assert(number > 0); + return MakeFileName(name, number, "sst"); +} + +std::string DescriptorFileName(const std::string& dbname, uint64_t number) { + assert(number > 0); + char buf[100]; + snprintf(buf, sizeof(buf), "/MANIFEST-%06llu", + static_cast(number)); + return dbname + buf; +} + +std::string CurrentFileName(const std::string& dbname) { + return dbname + "/CURRENT"; +} + +std::string LockFileName(const std::string& dbname) { + return dbname + "/LOCK"; +} + +std::string TempFileName(const std::string& dbname, uint64_t number) { + assert(number > 0); + return MakeFileName(dbname, number, "dbtmp"); +} + +std::string InfoLogFileName(const std::string& dbname) { + return dbname + "/LOG"; +} + +// Return the name of the old info log file for "dbname". +std::string OldInfoLogFileName(const std::string& dbname) { + return dbname + "/LOG.old"; +} + + +// Owned filenames have the form: +// dbname/CURRENT +// dbname/LOCK +// dbname/LOG +// dbname/LOG.old +// dbname/MANIFEST-[0-9]+ +// dbname/[0-9]+.(log|sst|ldb) +bool ParseFileName(const std::string& fname, + uint64_t* number, + FileType* type) { + Slice rest(fname); + if (rest == "CURRENT") { + *number = 0; + *type = kCurrentFile; + } else if (rest == "LOCK") { + *number = 0; + *type = kDBLockFile; + } else if (rest == "LOG" || rest == "LOG.old") { + *number = 0; + *type = kInfoLogFile; + } else if (rest.starts_with("MANIFEST-")) { + rest.remove_prefix(strlen("MANIFEST-")); + uint64_t num; + if (!ConsumeDecimalNumber(&rest, &num)) { + return false; + } + if (!rest.empty()) { + return false; + } + *type = kDescriptorFile; + *number = num; + } else { + // Avoid strtoull() to keep filename format independent of the + // current locale + uint64_t num; + if (!ConsumeDecimalNumber(&rest, &num)) { + return false; + } + Slice suffix = rest; + if (suffix == Slice(".log")) { + *type = kLogFile; + } else if (suffix == Slice(".sst") || suffix == Slice(".ldb")) { + *type = kTableFile; + } else if (suffix == Slice(".dbtmp")) { + *type = kTempFile; + } else { + return false; + } + *number = num; + } + return true; +} + +Status SetCurrentFile(Env* env, const std::string& dbname, + uint64_t descriptor_number) { + // Remove leading "dbname/" and add newline to manifest file name + std::string manifest = DescriptorFileName(dbname, descriptor_number); + Slice contents = manifest; + assert(contents.starts_with(dbname + "/")); + contents.remove_prefix(dbname.size() + 1); + std::string tmp = TempFileName(dbname, descriptor_number); + Status s = WriteStringToFileSync(env, contents.ToString() + "\n", tmp); + if (s.ok()) { + s = env->RenameFile(tmp, CurrentFileName(dbname)); + } + if (!s.ok()) { + env->DeleteFile(tmp); + } + return s; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/filename.h b/My Mind/Pods/leveldb-library/db/filename.h new file mode 100644 index 0000000..87a7526 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/filename.h @@ -0,0 +1,85 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// File names used by DB code + +#ifndef STORAGE_LEVELDB_DB_FILENAME_H_ +#define STORAGE_LEVELDB_DB_FILENAME_H_ + +#include +#include +#include "leveldb/slice.h" +#include "leveldb/status.h" +#include "port/port.h" + +namespace leveldb { + +class Env; + +enum FileType { + kLogFile, + kDBLockFile, + kTableFile, + kDescriptorFile, + kCurrentFile, + kTempFile, + kInfoLogFile // Either the current one, or an old one +}; + +// Return the name of the log file with the specified number +// in the db named by "dbname". The result will be prefixed with +// "dbname". +extern std::string LogFileName(const std::string& dbname, uint64_t number); + +// Return the name of the sstable with the specified number +// in the db named by "dbname". The result will be prefixed with +// "dbname". +extern std::string TableFileName(const std::string& dbname, uint64_t number); + +// Return the legacy file name for an sstable with the specified number +// in the db named by "dbname". The result will be prefixed with +// "dbname". +extern std::string SSTTableFileName(const std::string& dbname, uint64_t number); + +// Return the name of the descriptor file for the db named by +// "dbname" and the specified incarnation number. The result will be +// prefixed with "dbname". +extern std::string DescriptorFileName(const std::string& dbname, + uint64_t number); + +// Return the name of the current file. This file contains the name +// of the current manifest file. The result will be prefixed with +// "dbname". +extern std::string CurrentFileName(const std::string& dbname); + +// Return the name of the lock file for the db named by +// "dbname". The result will be prefixed with "dbname". +extern std::string LockFileName(const std::string& dbname); + +// Return the name of a temporary file owned by the db named "dbname". +// The result will be prefixed with "dbname". +extern std::string TempFileName(const std::string& dbname, uint64_t number); + +// Return the name of the info log file for "dbname". +extern std::string InfoLogFileName(const std::string& dbname); + +// Return the name of the old info log file for "dbname". +extern std::string OldInfoLogFileName(const std::string& dbname); + +// If filename is a leveldb file, store the type of the file in *type. +// The number encoded in the filename is stored in *number. If the +// filename was successfully parsed, returns true. Else return false. +extern bool ParseFileName(const std::string& filename, + uint64_t* number, + FileType* type); + +// Make the CURRENT file point to the descriptor file with the +// specified number. +extern Status SetCurrentFile(Env* env, const std::string& dbname, + uint64_t descriptor_number); + + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_FILENAME_H_ diff --git a/My Mind/Pods/leveldb-library/db/log_format.h b/My Mind/Pods/leveldb-library/db/log_format.h new file mode 100644 index 0000000..356e69f --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/log_format.h @@ -0,0 +1,35 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Log format information shared by reader and writer. +// See ../doc/log_format.md for more detail. + +#ifndef STORAGE_LEVELDB_DB_LOG_FORMAT_H_ +#define STORAGE_LEVELDB_DB_LOG_FORMAT_H_ + +namespace leveldb { +namespace log { + +enum RecordType { + // Zero is reserved for preallocated files + kZeroType = 0, + + kFullType = 1, + + // For fragments + kFirstType = 2, + kMiddleType = 3, + kLastType = 4 +}; +static const int kMaxRecordType = kLastType; + +static const int kBlockSize = 32768; + +// Header is checksum (4 bytes), length (2 bytes), type (1 byte). +static const int kHeaderSize = 4 + 2 + 1; + +} // namespace log +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_LOG_FORMAT_H_ diff --git a/My Mind/Pods/leveldb-library/db/log_reader.cc b/My Mind/Pods/leveldb-library/db/log_reader.cc new file mode 100644 index 0000000..a6d3045 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/log_reader.cc @@ -0,0 +1,284 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/log_reader.h" + +#include +#include "leveldb/env.h" +#include "util/coding.h" +#include "util/crc32c.h" + +namespace leveldb { +namespace log { + +Reader::Reporter::~Reporter() { +} + +Reader::Reader(SequentialFile* file, Reporter* reporter, bool checksum, + uint64_t initial_offset) + : file_(file), + reporter_(reporter), + checksum_(checksum), + backing_store_(new char[kBlockSize]), + buffer_(), + eof_(false), + last_record_offset_(0), + end_of_buffer_offset_(0), + initial_offset_(initial_offset), + resyncing_(initial_offset > 0) { +} + +Reader::~Reader() { + delete[] backing_store_; +} + +bool Reader::SkipToInitialBlock() { + size_t offset_in_block = initial_offset_ % kBlockSize; + uint64_t block_start_location = initial_offset_ - offset_in_block; + + // Don't search a block if we'd be in the trailer + if (offset_in_block > kBlockSize - 6) { + offset_in_block = 0; + block_start_location += kBlockSize; + } + + end_of_buffer_offset_ = block_start_location; + + // Skip to start of first block that can contain the initial record + if (block_start_location > 0) { + Status skip_status = file_->Skip(block_start_location); + if (!skip_status.ok()) { + ReportDrop(block_start_location, skip_status); + return false; + } + } + + return true; +} + +bool Reader::ReadRecord(Slice* record, std::string* scratch) { + if (last_record_offset_ < initial_offset_) { + if (!SkipToInitialBlock()) { + return false; + } + } + + scratch->clear(); + record->clear(); + bool in_fragmented_record = false; + // Record offset of the logical record that we're reading + // 0 is a dummy value to make compilers happy + uint64_t prospective_record_offset = 0; + + Slice fragment; + while (true) { + const unsigned int record_type = ReadPhysicalRecord(&fragment); + + // ReadPhysicalRecord may have only had an empty trailer remaining in its + // internal buffer. Calculate the offset of the next physical record now + // that it has returned, properly accounting for its header size. + uint64_t physical_record_offset = + end_of_buffer_offset_ - buffer_.size() - kHeaderSize - fragment.size(); + + if (resyncing_) { + if (record_type == kMiddleType) { + continue; + } else if (record_type == kLastType) { + resyncing_ = false; + continue; + } else { + resyncing_ = false; + } + } + + switch (record_type) { + case kFullType: + if (in_fragmented_record) { + // Handle bug in earlier versions of log::Writer where + // it could emit an empty kFirstType record at the tail end + // of a block followed by a kFullType or kFirstType record + // at the beginning of the next block. + if (scratch->empty()) { + in_fragmented_record = false; + } else { + ReportCorruption(scratch->size(), "partial record without end(1)"); + } + } + prospective_record_offset = physical_record_offset; + scratch->clear(); + *record = fragment; + last_record_offset_ = prospective_record_offset; + return true; + + case kFirstType: + if (in_fragmented_record) { + // Handle bug in earlier versions of log::Writer where + // it could emit an empty kFirstType record at the tail end + // of a block followed by a kFullType or kFirstType record + // at the beginning of the next block. + if (scratch->empty()) { + in_fragmented_record = false; + } else { + ReportCorruption(scratch->size(), "partial record without end(2)"); + } + } + prospective_record_offset = physical_record_offset; + scratch->assign(fragment.data(), fragment.size()); + in_fragmented_record = true; + break; + + case kMiddleType: + if (!in_fragmented_record) { + ReportCorruption(fragment.size(), + "missing start of fragmented record(1)"); + } else { + scratch->append(fragment.data(), fragment.size()); + } + break; + + case kLastType: + if (!in_fragmented_record) { + ReportCorruption(fragment.size(), + "missing start of fragmented record(2)"); + } else { + scratch->append(fragment.data(), fragment.size()); + *record = Slice(*scratch); + last_record_offset_ = prospective_record_offset; + return true; + } + break; + + case kEof: + if (in_fragmented_record) { + // This can be caused by the writer dying immediately after + // writing a physical record but before completing the next; don't + // treat it as a corruption, just ignore the entire logical record. + scratch->clear(); + } + return false; + + case kBadRecord: + if (in_fragmented_record) { + ReportCorruption(scratch->size(), "error in middle of record"); + in_fragmented_record = false; + scratch->clear(); + } + break; + + default: { + char buf[40]; + snprintf(buf, sizeof(buf), "unknown record type %u", record_type); + ReportCorruption( + (fragment.size() + (in_fragmented_record ? scratch->size() : 0)), + buf); + in_fragmented_record = false; + scratch->clear(); + break; + } + } + } + return false; +} + +uint64_t Reader::LastRecordOffset() { + return last_record_offset_; +} + +void Reader::ReportCorruption(uint64_t bytes, const char* reason) { + ReportDrop(bytes, Status::Corruption(reason)); +} + +void Reader::ReportDrop(uint64_t bytes, const Status& reason) { + if (reporter_ != NULL && + end_of_buffer_offset_ - buffer_.size() - bytes >= initial_offset_) { + reporter_->Corruption(static_cast(bytes), reason); + } +} + +unsigned int Reader::ReadPhysicalRecord(Slice* result) { + while (true) { + if (buffer_.size() < kHeaderSize) { + if (!eof_) { + // Last read was a full read, so this is a trailer to skip + buffer_.clear(); + Status status = file_->Read(kBlockSize, &buffer_, backing_store_); + end_of_buffer_offset_ += buffer_.size(); + if (!status.ok()) { + buffer_.clear(); + ReportDrop(kBlockSize, status); + eof_ = true; + return kEof; + } else if (buffer_.size() < kBlockSize) { + eof_ = true; + } + continue; + } else { + // Note that if buffer_ is non-empty, we have a truncated header at the + // end of the file, which can be caused by the writer crashing in the + // middle of writing the header. Instead of considering this an error, + // just report EOF. + buffer_.clear(); + return kEof; + } + } + + // Parse the header + const char* header = buffer_.data(); + const uint32_t a = static_cast(header[4]) & 0xff; + const uint32_t b = static_cast(header[5]) & 0xff; + const unsigned int type = header[6]; + const uint32_t length = a | (b << 8); + if (kHeaderSize + length > buffer_.size()) { + size_t drop_size = buffer_.size(); + buffer_.clear(); + if (!eof_) { + ReportCorruption(drop_size, "bad record length"); + return kBadRecord; + } + // If the end of the file has been reached without reading |length| bytes + // of payload, assume the writer died in the middle of writing the record. + // Don't report a corruption. + return kEof; + } + + if (type == kZeroType && length == 0) { + // Skip zero length record without reporting any drops since + // such records are produced by the mmap based writing code in + // env_posix.cc that preallocates file regions. + buffer_.clear(); + return kBadRecord; + } + + // Check crc + if (checksum_) { + uint32_t expected_crc = crc32c::Unmask(DecodeFixed32(header)); + uint32_t actual_crc = crc32c::Value(header + 6, 1 + length); + if (actual_crc != expected_crc) { + // Drop the rest of the buffer since "length" itself may have + // been corrupted and if we trust it, we could find some + // fragment of a real log record that just happens to look + // like a valid log record. + size_t drop_size = buffer_.size(); + buffer_.clear(); + ReportCorruption(drop_size, "checksum mismatch"); + return kBadRecord; + } + } + + buffer_.remove_prefix(kHeaderSize + length); + + // Skip physical record that started before initial_offset_ + if (end_of_buffer_offset_ - buffer_.size() - kHeaderSize - length < + initial_offset_) { + result->clear(); + return kBadRecord; + } + + *result = Slice(header + kHeaderSize, length); + return type; + } +} + +} // namespace log +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/log_reader.h b/My Mind/Pods/leveldb-library/db/log_reader.h new file mode 100644 index 0000000..8389d61 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/log_reader.h @@ -0,0 +1,113 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_LOG_READER_H_ +#define STORAGE_LEVELDB_DB_LOG_READER_H_ + +#include + +#include "db/log_format.h" +#include "leveldb/slice.h" +#include "leveldb/status.h" + +namespace leveldb { + +class SequentialFile; + +namespace log { + +class Reader { + public: + // Interface for reporting errors. + class Reporter { + public: + virtual ~Reporter(); + + // Some corruption was detected. "size" is the approximate number + // of bytes dropped due to the corruption. + virtual void Corruption(size_t bytes, const Status& status) = 0; + }; + + // Create a reader that will return log records from "*file". + // "*file" must remain live while this Reader is in use. + // + // If "reporter" is non-NULL, it is notified whenever some data is + // dropped due to a detected corruption. "*reporter" must remain + // live while this Reader is in use. + // + // If "checksum" is true, verify checksums if available. + // + // The Reader will start reading at the first record located at physical + // position >= initial_offset within the file. + Reader(SequentialFile* file, Reporter* reporter, bool checksum, + uint64_t initial_offset); + + ~Reader(); + + // Read the next record into *record. Returns true if read + // successfully, false if we hit end of the input. May use + // "*scratch" as temporary storage. The contents filled in *record + // will only be valid until the next mutating operation on this + // reader or the next mutation to *scratch. + bool ReadRecord(Slice* record, std::string* scratch); + + // Returns the physical offset of the last record returned by ReadRecord. + // + // Undefined before the first call to ReadRecord. + uint64_t LastRecordOffset(); + + private: + SequentialFile* const file_; + Reporter* const reporter_; + bool const checksum_; + char* const backing_store_; + Slice buffer_; + bool eof_; // Last Read() indicated EOF by returning < kBlockSize + + // Offset of the last record returned by ReadRecord. + uint64_t last_record_offset_; + // Offset of the first location past the end of buffer_. + uint64_t end_of_buffer_offset_; + + // Offset at which to start looking for the first record to return + uint64_t const initial_offset_; + + // True if we are resynchronizing after a seek (initial_offset_ > 0). In + // particular, a run of kMiddleType and kLastType records can be silently + // skipped in this mode + bool resyncing_; + + // Extend record types with the following special values + enum { + kEof = kMaxRecordType + 1, + // Returned whenever we find an invalid physical record. + // Currently there are three situations in which this happens: + // * The record has an invalid CRC (ReadPhysicalRecord reports a drop) + // * The record is a 0-length record (No drop is reported) + // * The record is below constructor's initial_offset (No drop is reported) + kBadRecord = kMaxRecordType + 2 + }; + + // Skips all blocks that are completely before "initial_offset_". + // + // Returns true on success. Handles reporting. + bool SkipToInitialBlock(); + + // Return type, or one of the preceding special values + unsigned int ReadPhysicalRecord(Slice* result); + + // Reports dropped bytes to the reporter. + // buffer_ must be updated to remove the dropped bytes prior to invocation. + void ReportCorruption(uint64_t bytes, const char* reason); + void ReportDrop(uint64_t bytes, const Status& reason); + + // No copying allowed + Reader(const Reader&); + void operator=(const Reader&); +}; + +} // namespace log +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_LOG_READER_H_ diff --git a/My Mind/Pods/leveldb-library/db/log_writer.cc b/My Mind/Pods/leveldb-library/db/log_writer.cc new file mode 100644 index 0000000..74a0327 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/log_writer.cc @@ -0,0 +1,112 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/log_writer.h" + +#include +#include "leveldb/env.h" +#include "util/coding.h" +#include "util/crc32c.h" + +namespace leveldb { +namespace log { + +static void InitTypeCrc(uint32_t* type_crc) { + for (int i = 0; i <= kMaxRecordType; i++) { + char t = static_cast(i); + type_crc[i] = crc32c::Value(&t, 1); + } +} + +Writer::Writer(WritableFile* dest) + : dest_(dest), + block_offset_(0) { + InitTypeCrc(type_crc_); +} + +Writer::Writer(WritableFile* dest, uint64_t dest_length) + : dest_(dest), block_offset_(dest_length % kBlockSize) { + InitTypeCrc(type_crc_); +} + +Writer::~Writer() { +} + +Status Writer::AddRecord(const Slice& slice) { + const char* ptr = slice.data(); + size_t left = slice.size(); + + // Fragment the record if necessary and emit it. Note that if slice + // is empty, we still want to iterate once to emit a single + // zero-length record + Status s; + bool begin = true; + do { + const int leftover = kBlockSize - block_offset_; + assert(leftover >= 0); + if (leftover < kHeaderSize) { + // Switch to a new block + if (leftover > 0) { + // Fill the trailer (literal below relies on kHeaderSize being 7) + assert(kHeaderSize == 7); + dest_->Append(Slice("\x00\x00\x00\x00\x00\x00", leftover)); + } + block_offset_ = 0; + } + + // Invariant: we never leave < kHeaderSize bytes in a block. + assert(kBlockSize - block_offset_ - kHeaderSize >= 0); + + const size_t avail = kBlockSize - block_offset_ - kHeaderSize; + const size_t fragment_length = (left < avail) ? left : avail; + + RecordType type; + const bool end = (left == fragment_length); + if (begin && end) { + type = kFullType; + } else if (begin) { + type = kFirstType; + } else if (end) { + type = kLastType; + } else { + type = kMiddleType; + } + + s = EmitPhysicalRecord(type, ptr, fragment_length); + ptr += fragment_length; + left -= fragment_length; + begin = false; + } while (s.ok() && left > 0); + return s; +} + +Status Writer::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n) { + assert(n <= 0xffff); // Must fit in two bytes + assert(block_offset_ + kHeaderSize + n <= kBlockSize); + + // Format the header + char buf[kHeaderSize]; + buf[4] = static_cast(n & 0xff); + buf[5] = static_cast(n >> 8); + buf[6] = static_cast(t); + + // Compute the crc of the record type and the payload. + uint32_t crc = crc32c::Extend(type_crc_[t], ptr, n); + crc = crc32c::Mask(crc); // Adjust for storage + EncodeFixed32(buf, crc); + + // Write the header and the payload + Status s = dest_->Append(Slice(buf, kHeaderSize)); + if (s.ok()) { + s = dest_->Append(Slice(ptr, n)); + if (s.ok()) { + s = dest_->Flush(); + } + } + block_offset_ += kHeaderSize + n; + return s; +} + +} // namespace log +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/log_writer.h b/My Mind/Pods/leveldb-library/db/log_writer.h new file mode 100644 index 0000000..9e7cc47 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/log_writer.h @@ -0,0 +1,54 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_LOG_WRITER_H_ +#define STORAGE_LEVELDB_DB_LOG_WRITER_H_ + +#include +#include "db/log_format.h" +#include "leveldb/slice.h" +#include "leveldb/status.h" + +namespace leveldb { + +class WritableFile; + +namespace log { + +class Writer { + public: + // Create a writer that will append data to "*dest". + // "*dest" must be initially empty. + // "*dest" must remain live while this Writer is in use. + explicit Writer(WritableFile* dest); + + // Create a writer that will append data to "*dest". + // "*dest" must have initial length "dest_length". + // "*dest" must remain live while this Writer is in use. + Writer(WritableFile* dest, uint64_t dest_length); + + ~Writer(); + + Status AddRecord(const Slice& slice); + + private: + WritableFile* dest_; + int block_offset_; // Current offset in block + + // crc32c values for all supported record types. These are + // pre-computed to reduce the overhead of computing the crc of the + // record type stored in the header. + uint32_t type_crc_[kMaxRecordType + 1]; + + Status EmitPhysicalRecord(RecordType type, const char* ptr, size_t length); + + // No copying allowed + Writer(const Writer&); + void operator=(const Writer&); +}; + +} // namespace log +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_LOG_WRITER_H_ diff --git a/My Mind/Pods/leveldb-library/db/memtable.cc b/My Mind/Pods/leveldb-library/db/memtable.cc new file mode 100644 index 0000000..bfec0a7 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/memtable.cc @@ -0,0 +1,145 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/memtable.h" +#include "db/dbformat.h" +#include "leveldb/comparator.h" +#include "leveldb/env.h" +#include "leveldb/iterator.h" +#include "util/coding.h" + +namespace leveldb { + +static Slice GetLengthPrefixedSlice(const char* data) { + uint32_t len; + const char* p = data; + p = GetVarint32Ptr(p, p + 5, &len); // +5: we assume "p" is not corrupted + return Slice(p, len); +} + +MemTable::MemTable(const InternalKeyComparator& cmp) + : comparator_(cmp), + refs_(0), + table_(comparator_, &arena_) { +} + +MemTable::~MemTable() { + assert(refs_ == 0); +} + +size_t MemTable::ApproximateMemoryUsage() { return arena_.MemoryUsage(); } + +int MemTable::KeyComparator::operator()(const char* aptr, const char* bptr) + const { + // Internal keys are encoded as length-prefixed strings. + Slice a = GetLengthPrefixedSlice(aptr); + Slice b = GetLengthPrefixedSlice(bptr); + return comparator.Compare(a, b); +} + +// Encode a suitable internal key target for "target" and return it. +// Uses *scratch as scratch space, and the returned pointer will point +// into this scratch space. +static const char* EncodeKey(std::string* scratch, const Slice& target) { + scratch->clear(); + PutVarint32(scratch, target.size()); + scratch->append(target.data(), target.size()); + return scratch->data(); +} + +class MemTableIterator: public Iterator { + public: + explicit MemTableIterator(MemTable::Table* table) : iter_(table) { } + + virtual bool Valid() const { return iter_.Valid(); } + virtual void Seek(const Slice& k) { iter_.Seek(EncodeKey(&tmp_, k)); } + virtual void SeekToFirst() { iter_.SeekToFirst(); } + virtual void SeekToLast() { iter_.SeekToLast(); } + virtual void Next() { iter_.Next(); } + virtual void Prev() { iter_.Prev(); } + virtual Slice key() const { return GetLengthPrefixedSlice(iter_.key()); } + virtual Slice value() const { + Slice key_slice = GetLengthPrefixedSlice(iter_.key()); + return GetLengthPrefixedSlice(key_slice.data() + key_slice.size()); + } + + virtual Status status() const { return Status::OK(); } + + private: + MemTable::Table::Iterator iter_; + std::string tmp_; // For passing to EncodeKey + + // No copying allowed + MemTableIterator(const MemTableIterator&); + void operator=(const MemTableIterator&); +}; + +Iterator* MemTable::NewIterator() { + return new MemTableIterator(&table_); +} + +void MemTable::Add(SequenceNumber s, ValueType type, + const Slice& key, + const Slice& value) { + // Format of an entry is concatenation of: + // key_size : varint32 of internal_key.size() + // key bytes : char[internal_key.size()] + // value_size : varint32 of value.size() + // value bytes : char[value.size()] + size_t key_size = key.size(); + size_t val_size = value.size(); + size_t internal_key_size = key_size + 8; + const size_t encoded_len = + VarintLength(internal_key_size) + internal_key_size + + VarintLength(val_size) + val_size; + char* buf = arena_.Allocate(encoded_len); + char* p = EncodeVarint32(buf, internal_key_size); + memcpy(p, key.data(), key_size); + p += key_size; + EncodeFixed64(p, (s << 8) | type); + p += 8; + p = EncodeVarint32(p, val_size); + memcpy(p, value.data(), val_size); + assert((p + val_size) - buf == encoded_len); + table_.Insert(buf); +} + +bool MemTable::Get(const LookupKey& key, std::string* value, Status* s) { + Slice memkey = key.memtable_key(); + Table::Iterator iter(&table_); + iter.Seek(memkey.data()); + if (iter.Valid()) { + // entry format is: + // klength varint32 + // userkey char[klength] + // tag uint64 + // vlength varint32 + // value char[vlength] + // Check that it belongs to same user key. We do not check the + // sequence number since the Seek() call above should have skipped + // all entries with overly large sequence numbers. + const char* entry = iter.key(); + uint32_t key_length; + const char* key_ptr = GetVarint32Ptr(entry, entry+5, &key_length); + if (comparator_.comparator.user_comparator()->Compare( + Slice(key_ptr, key_length - 8), + key.user_key()) == 0) { + // Correct user key + const uint64_t tag = DecodeFixed64(key_ptr + key_length - 8); + switch (static_cast(tag & 0xff)) { + case kTypeValue: { + Slice v = GetLengthPrefixedSlice(key_ptr + key_length); + value->assign(v.data(), v.size()); + return true; + } + case kTypeDeletion: + *s = Status::NotFound(Slice()); + return true; + } + } + } + return false; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/memtable.h b/My Mind/Pods/leveldb-library/db/memtable.h new file mode 100644 index 0000000..9f41567 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/memtable.h @@ -0,0 +1,88 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_MEMTABLE_H_ +#define STORAGE_LEVELDB_DB_MEMTABLE_H_ + +#include +#include "leveldb/db.h" +#include "db/dbformat.h" +#include "db/skiplist.h" +#include "util/arena.h" + +namespace leveldb { + +class InternalKeyComparator; +class Mutex; +class MemTableIterator; + +class MemTable { + public: + // MemTables are reference counted. The initial reference count + // is zero and the caller must call Ref() at least once. + explicit MemTable(const InternalKeyComparator& comparator); + + // Increase reference count. + void Ref() { ++refs_; } + + // Drop reference count. Delete if no more references exist. + void Unref() { + --refs_; + assert(refs_ >= 0); + if (refs_ <= 0) { + delete this; + } + } + + // Returns an estimate of the number of bytes of data in use by this + // data structure. It is safe to call when MemTable is being modified. + size_t ApproximateMemoryUsage(); + + // Return an iterator that yields the contents of the memtable. + // + // The caller must ensure that the underlying MemTable remains live + // while the returned iterator is live. The keys returned by this + // iterator are internal keys encoded by AppendInternalKey in the + // db/format.{h,cc} module. + Iterator* NewIterator(); + + // Add an entry into memtable that maps key to value at the + // specified sequence number and with the specified type. + // Typically value will be empty if type==kTypeDeletion. + void Add(SequenceNumber seq, ValueType type, + const Slice& key, + const Slice& value); + + // If memtable contains a value for key, store it in *value and return true. + // If memtable contains a deletion for key, store a NotFound() error + // in *status and return true. + // Else, return false. + bool Get(const LookupKey& key, std::string* value, Status* s); + + private: + ~MemTable(); // Private since only Unref() should be used to delete it + + struct KeyComparator { + const InternalKeyComparator comparator; + explicit KeyComparator(const InternalKeyComparator& c) : comparator(c) { } + int operator()(const char* a, const char* b) const; + }; + friend class MemTableIterator; + friend class MemTableBackwardIterator; + + typedef SkipList Table; + + KeyComparator comparator_; + int refs_; + Arena arena_; + Table table_; + + // No copying allowed + MemTable(const MemTable&); + void operator=(const MemTable&); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_MEMTABLE_H_ diff --git a/My Mind/Pods/leveldb-library/db/repair.cc b/My Mind/Pods/leveldb-library/db/repair.cc new file mode 100644 index 0000000..4cd4bb0 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/repair.cc @@ -0,0 +1,461 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// We recover the contents of the descriptor from the other files we find. +// (1) Any log files are first converted to tables +// (2) We scan every table to compute +// (a) smallest/largest for the table +// (b) largest sequence number in the table +// (3) We generate descriptor contents: +// - log number is set to zero +// - next-file-number is set to 1 + largest file number we found +// - last-sequence-number is set to largest sequence# found across +// all tables (see 2c) +// - compaction pointers are cleared +// - every table file is added at level 0 +// +// Possible optimization 1: +// (a) Compute total size and use to pick appropriate max-level M +// (b) Sort tables by largest sequence# in the table +// (c) For each table: if it overlaps earlier table, place in level-0, +// else place in level-M. +// Possible optimization 2: +// Store per-table metadata (smallest, largest, largest-seq#, ...) +// in the table's meta section to speed up ScanTable. + +#include "db/builder.h" +#include "db/db_impl.h" +#include "db/dbformat.h" +#include "db/filename.h" +#include "db/log_reader.h" +#include "db/log_writer.h" +#include "db/memtable.h" +#include "db/table_cache.h" +#include "db/version_edit.h" +#include "db/write_batch_internal.h" +#include "leveldb/comparator.h" +#include "leveldb/db.h" +#include "leveldb/env.h" + +namespace leveldb { + +namespace { + +class Repairer { + public: + Repairer(const std::string& dbname, const Options& options) + : dbname_(dbname), + env_(options.env), + icmp_(options.comparator), + ipolicy_(options.filter_policy), + options_(SanitizeOptions(dbname, &icmp_, &ipolicy_, options)), + owns_info_log_(options_.info_log != options.info_log), + owns_cache_(options_.block_cache != options.block_cache), + next_file_number_(1) { + // TableCache can be small since we expect each table to be opened once. + table_cache_ = new TableCache(dbname_, &options_, 10); + } + + ~Repairer() { + delete table_cache_; + if (owns_info_log_) { + delete options_.info_log; + } + if (owns_cache_) { + delete options_.block_cache; + } + } + + Status Run() { + Status status = FindFiles(); + if (status.ok()) { + ConvertLogFilesToTables(); + ExtractMetaData(); + status = WriteDescriptor(); + } + if (status.ok()) { + unsigned long long bytes = 0; + for (size_t i = 0; i < tables_.size(); i++) { + bytes += tables_[i].meta.file_size; + } + Log(options_.info_log, + "**** Repaired leveldb %s; " + "recovered %d files; %llu bytes. " + "Some data may have been lost. " + "****", + dbname_.c_str(), + static_cast(tables_.size()), + bytes); + } + return status; + } + + private: + struct TableInfo { + FileMetaData meta; + SequenceNumber max_sequence; + }; + + std::string const dbname_; + Env* const env_; + InternalKeyComparator const icmp_; + InternalFilterPolicy const ipolicy_; + Options const options_; + bool owns_info_log_; + bool owns_cache_; + TableCache* table_cache_; + VersionEdit edit_; + + std::vector manifests_; + std::vector table_numbers_; + std::vector logs_; + std::vector tables_; + uint64_t next_file_number_; + + Status FindFiles() { + std::vector filenames; + Status status = env_->GetChildren(dbname_, &filenames); + if (!status.ok()) { + return status; + } + if (filenames.empty()) { + return Status::IOError(dbname_, "repair found no files"); + } + + uint64_t number; + FileType type; + for (size_t i = 0; i < filenames.size(); i++) { + if (ParseFileName(filenames[i], &number, &type)) { + if (type == kDescriptorFile) { + manifests_.push_back(filenames[i]); + } else { + if (number + 1 > next_file_number_) { + next_file_number_ = number + 1; + } + if (type == kLogFile) { + logs_.push_back(number); + } else if (type == kTableFile) { + table_numbers_.push_back(number); + } else { + // Ignore other files + } + } + } + } + return status; + } + + void ConvertLogFilesToTables() { + for (size_t i = 0; i < logs_.size(); i++) { + std::string logname = LogFileName(dbname_, logs_[i]); + Status status = ConvertLogToTable(logs_[i]); + if (!status.ok()) { + Log(options_.info_log, "Log #%llu: ignoring conversion error: %s", + (unsigned long long) logs_[i], + status.ToString().c_str()); + } + ArchiveFile(logname); + } + } + + Status ConvertLogToTable(uint64_t log) { + struct LogReporter : public log::Reader::Reporter { + Env* env; + Logger* info_log; + uint64_t lognum; + virtual void Corruption(size_t bytes, const Status& s) { + // We print error messages for corruption, but continue repairing. + Log(info_log, "Log #%llu: dropping %d bytes; %s", + (unsigned long long) lognum, + static_cast(bytes), + s.ToString().c_str()); + } + }; + + // Open the log file + std::string logname = LogFileName(dbname_, log); + SequentialFile* lfile; + Status status = env_->NewSequentialFile(logname, &lfile); + if (!status.ok()) { + return status; + } + + // Create the log reader. + LogReporter reporter; + reporter.env = env_; + reporter.info_log = options_.info_log; + reporter.lognum = log; + // We intentionally make log::Reader do checksumming so that + // corruptions cause entire commits to be skipped instead of + // propagating bad information (like overly large sequence + // numbers). + log::Reader reader(lfile, &reporter, false/*do not checksum*/, + 0/*initial_offset*/); + + // Read all the records and add to a memtable + std::string scratch; + Slice record; + WriteBatch batch; + MemTable* mem = new MemTable(icmp_); + mem->Ref(); + int counter = 0; + while (reader.ReadRecord(&record, &scratch)) { + if (record.size() < 12) { + reporter.Corruption( + record.size(), Status::Corruption("log record too small")); + continue; + } + WriteBatchInternal::SetContents(&batch, record); + status = WriteBatchInternal::InsertInto(&batch, mem); + if (status.ok()) { + counter += WriteBatchInternal::Count(&batch); + } else { + Log(options_.info_log, "Log #%llu: ignoring %s", + (unsigned long long) log, + status.ToString().c_str()); + status = Status::OK(); // Keep going with rest of file + } + } + delete lfile; + + // Do not record a version edit for this conversion to a Table + // since ExtractMetaData() will also generate edits. + FileMetaData meta; + meta.number = next_file_number_++; + Iterator* iter = mem->NewIterator(); + status = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta); + delete iter; + mem->Unref(); + mem = NULL; + if (status.ok()) { + if (meta.file_size > 0) { + table_numbers_.push_back(meta.number); + } + } + Log(options_.info_log, "Log #%llu: %d ops saved to Table #%llu %s", + (unsigned long long) log, + counter, + (unsigned long long) meta.number, + status.ToString().c_str()); + return status; + } + + void ExtractMetaData() { + for (size_t i = 0; i < table_numbers_.size(); i++) { + ScanTable(table_numbers_[i]); + } + } + + Iterator* NewTableIterator(const FileMetaData& meta) { + // Same as compaction iterators: if paranoid_checks are on, turn + // on checksum verification. + ReadOptions r; + r.verify_checksums = options_.paranoid_checks; + return table_cache_->NewIterator(r, meta.number, meta.file_size); + } + + void ScanTable(uint64_t number) { + TableInfo t; + t.meta.number = number; + std::string fname = TableFileName(dbname_, number); + Status status = env_->GetFileSize(fname, &t.meta.file_size); + if (!status.ok()) { + // Try alternate file name. + fname = SSTTableFileName(dbname_, number); + Status s2 = env_->GetFileSize(fname, &t.meta.file_size); + if (s2.ok()) { + status = Status::OK(); + } + } + if (!status.ok()) { + ArchiveFile(TableFileName(dbname_, number)); + ArchiveFile(SSTTableFileName(dbname_, number)); + Log(options_.info_log, "Table #%llu: dropped: %s", + (unsigned long long) t.meta.number, + status.ToString().c_str()); + return; + } + + // Extract metadata by scanning through table. + int counter = 0; + Iterator* iter = NewTableIterator(t.meta); + bool empty = true; + ParsedInternalKey parsed; + t.max_sequence = 0; + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { + Slice key = iter->key(); + if (!ParseInternalKey(key, &parsed)) { + Log(options_.info_log, "Table #%llu: unparsable key %s", + (unsigned long long) t.meta.number, + EscapeString(key).c_str()); + continue; + } + + counter++; + if (empty) { + empty = false; + t.meta.smallest.DecodeFrom(key); + } + t.meta.largest.DecodeFrom(key); + if (parsed.sequence > t.max_sequence) { + t.max_sequence = parsed.sequence; + } + } + if (!iter->status().ok()) { + status = iter->status(); + } + delete iter; + Log(options_.info_log, "Table #%llu: %d entries %s", + (unsigned long long) t.meta.number, + counter, + status.ToString().c_str()); + + if (status.ok()) { + tables_.push_back(t); + } else { + RepairTable(fname, t); // RepairTable archives input file. + } + } + + void RepairTable(const std::string& src, TableInfo t) { + // We will copy src contents to a new table and then rename the + // new table over the source. + + // Create builder. + std::string copy = TableFileName(dbname_, next_file_number_++); + WritableFile* file; + Status s = env_->NewWritableFile(copy, &file); + if (!s.ok()) { + return; + } + TableBuilder* builder = new TableBuilder(options_, file); + + // Copy data. + Iterator* iter = NewTableIterator(t.meta); + int counter = 0; + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { + builder->Add(iter->key(), iter->value()); + counter++; + } + delete iter; + + ArchiveFile(src); + if (counter == 0) { + builder->Abandon(); // Nothing to save + } else { + s = builder->Finish(); + if (s.ok()) { + t.meta.file_size = builder->FileSize(); + } + } + delete builder; + builder = NULL; + + if (s.ok()) { + s = file->Close(); + } + delete file; + file = NULL; + + if (counter > 0 && s.ok()) { + std::string orig = TableFileName(dbname_, t.meta.number); + s = env_->RenameFile(copy, orig); + if (s.ok()) { + Log(options_.info_log, "Table #%llu: %d entries repaired", + (unsigned long long) t.meta.number, counter); + tables_.push_back(t); + } + } + if (!s.ok()) { + env_->DeleteFile(copy); + } + } + + Status WriteDescriptor() { + std::string tmp = TempFileName(dbname_, 1); + WritableFile* file; + Status status = env_->NewWritableFile(tmp, &file); + if (!status.ok()) { + return status; + } + + SequenceNumber max_sequence = 0; + for (size_t i = 0; i < tables_.size(); i++) { + if (max_sequence < tables_[i].max_sequence) { + max_sequence = tables_[i].max_sequence; + } + } + + edit_.SetComparatorName(icmp_.user_comparator()->Name()); + edit_.SetLogNumber(0); + edit_.SetNextFile(next_file_number_); + edit_.SetLastSequence(max_sequence); + + for (size_t i = 0; i < tables_.size(); i++) { + // TODO(opt): separate out into multiple levels + const TableInfo& t = tables_[i]; + edit_.AddFile(0, t.meta.number, t.meta.file_size, + t.meta.smallest, t.meta.largest); + } + + //fprintf(stderr, "NewDescriptor:\n%s\n", edit_.DebugString().c_str()); + { + log::Writer log(file); + std::string record; + edit_.EncodeTo(&record); + status = log.AddRecord(record); + } + if (status.ok()) { + status = file->Close(); + } + delete file; + file = NULL; + + if (!status.ok()) { + env_->DeleteFile(tmp); + } else { + // Discard older manifests + for (size_t i = 0; i < manifests_.size(); i++) { + ArchiveFile(dbname_ + "/" + manifests_[i]); + } + + // Install new manifest + status = env_->RenameFile(tmp, DescriptorFileName(dbname_, 1)); + if (status.ok()) { + status = SetCurrentFile(env_, dbname_, 1); + } else { + env_->DeleteFile(tmp); + } + } + return status; + } + + void ArchiveFile(const std::string& fname) { + // Move into another directory. E.g., for + // dir/foo + // rename to + // dir/lost/foo + const char* slash = strrchr(fname.c_str(), '/'); + std::string new_dir; + if (slash != NULL) { + new_dir.assign(fname.data(), slash - fname.data()); + } + new_dir.append("/lost"); + env_->CreateDir(new_dir); // Ignore error + std::string new_file = new_dir; + new_file.append("/"); + new_file.append((slash == NULL) ? fname.c_str() : slash + 1); + Status s = env_->RenameFile(fname, new_file); + Log(options_.info_log, "Archiving %s: %s\n", + fname.c_str(), s.ToString().c_str()); + } +}; +} // namespace + +Status RepairDB(const std::string& dbname, const Options& options) { + Repairer repairer(dbname, options); + return repairer.Run(); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/skiplist.h b/My Mind/Pods/leveldb-library/db/skiplist.h new file mode 100644 index 0000000..8bd7776 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/skiplist.h @@ -0,0 +1,384 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_SKIPLIST_H_ +#define STORAGE_LEVELDB_DB_SKIPLIST_H_ + +// Thread safety +// ------------- +// +// Writes require external synchronization, most likely a mutex. +// Reads require a guarantee that the SkipList will not be destroyed +// while the read is in progress. Apart from that, reads progress +// without any internal locking or synchronization. +// +// Invariants: +// +// (1) Allocated nodes are never deleted until the SkipList is +// destroyed. This is trivially guaranteed by the code since we +// never delete any skip list nodes. +// +// (2) The contents of a Node except for the next/prev pointers are +// immutable after the Node has been linked into the SkipList. +// Only Insert() modifies the list, and it is careful to initialize +// a node and use release-stores to publish the nodes in one or +// more lists. +// +// ... prev vs. next pointer ordering ... + +#include +#include +#include "port/port.h" +#include "util/arena.h" +#include "util/random.h" + +namespace leveldb { + +class Arena; + +template +class SkipList { + private: + struct Node; + + public: + // Create a new SkipList object that will use "cmp" for comparing keys, + // and will allocate memory using "*arena". Objects allocated in the arena + // must remain allocated for the lifetime of the skiplist object. + explicit SkipList(Comparator cmp, Arena* arena); + + // Insert key into the list. + // REQUIRES: nothing that compares equal to key is currently in the list. + void Insert(const Key& key); + + // Returns true iff an entry that compares equal to key is in the list. + bool Contains(const Key& key) const; + + // Iteration over the contents of a skip list + class Iterator { + public: + // Initialize an iterator over the specified list. + // The returned iterator is not valid. + explicit Iterator(const SkipList* list); + + // Returns true iff the iterator is positioned at a valid node. + bool Valid() const; + + // Returns the key at the current position. + // REQUIRES: Valid() + const Key& key() const; + + // Advances to the next position. + // REQUIRES: Valid() + void Next(); + + // Advances to the previous position. + // REQUIRES: Valid() + void Prev(); + + // Advance to the first entry with a key >= target + void Seek(const Key& target); + + // Position at the first entry in list. + // Final state of iterator is Valid() iff list is not empty. + void SeekToFirst(); + + // Position at the last entry in list. + // Final state of iterator is Valid() iff list is not empty. + void SeekToLast(); + + private: + const SkipList* list_; + Node* node_; + // Intentionally copyable + }; + + private: + enum { kMaxHeight = 12 }; + + // Immutable after construction + Comparator const compare_; + Arena* const arena_; // Arena used for allocations of nodes + + Node* const head_; + + // Modified only by Insert(). Read racily by readers, but stale + // values are ok. + port::AtomicPointer max_height_; // Height of the entire list + + inline int GetMaxHeight() const { + return static_cast( + reinterpret_cast(max_height_.NoBarrier_Load())); + } + + // Read/written only by Insert(). + Random rnd_; + + Node* NewNode(const Key& key, int height); + int RandomHeight(); + bool Equal(const Key& a, const Key& b) const { return (compare_(a, b) == 0); } + + // Return true if key is greater than the data stored in "n" + bool KeyIsAfterNode(const Key& key, Node* n) const; + + // Return the earliest node that comes at or after key. + // Return NULL if there is no such node. + // + // If prev is non-NULL, fills prev[level] with pointer to previous + // node at "level" for every level in [0..max_height_-1]. + Node* FindGreaterOrEqual(const Key& key, Node** prev) const; + + // Return the latest node with a key < key. + // Return head_ if there is no such node. + Node* FindLessThan(const Key& key) const; + + // Return the last node in the list. + // Return head_ if list is empty. + Node* FindLast() const; + + // No copying allowed + SkipList(const SkipList&); + void operator=(const SkipList&); +}; + +// Implementation details follow +template +struct SkipList::Node { + explicit Node(const Key& k) : key(k) { } + + Key const key; + + // Accessors/mutators for links. Wrapped in methods so we can + // add the appropriate barriers as necessary. + Node* Next(int n) { + assert(n >= 0); + // Use an 'acquire load' so that we observe a fully initialized + // version of the returned Node. + return reinterpret_cast(next_[n].Acquire_Load()); + } + void SetNext(int n, Node* x) { + assert(n >= 0); + // Use a 'release store' so that anybody who reads through this + // pointer observes a fully initialized version of the inserted node. + next_[n].Release_Store(x); + } + + // No-barrier variants that can be safely used in a few locations. + Node* NoBarrier_Next(int n) { + assert(n >= 0); + return reinterpret_cast(next_[n].NoBarrier_Load()); + } + void NoBarrier_SetNext(int n, Node* x) { + assert(n >= 0); + next_[n].NoBarrier_Store(x); + } + + private: + // Array of length equal to the node height. next_[0] is lowest level link. + port::AtomicPointer next_[1]; +}; + +template +typename SkipList::Node* +SkipList::NewNode(const Key& key, int height) { + char* mem = arena_->AllocateAligned( + sizeof(Node) + sizeof(port::AtomicPointer) * (height - 1)); + return new (mem) Node(key); +} + +template +inline SkipList::Iterator::Iterator(const SkipList* list) { + list_ = list; + node_ = NULL; +} + +template +inline bool SkipList::Iterator::Valid() const { + return node_ != NULL; +} + +template +inline const Key& SkipList::Iterator::key() const { + assert(Valid()); + return node_->key; +} + +template +inline void SkipList::Iterator::Next() { + assert(Valid()); + node_ = node_->Next(0); +} + +template +inline void SkipList::Iterator::Prev() { + // Instead of using explicit "prev" links, we just search for the + // last node that falls before key. + assert(Valid()); + node_ = list_->FindLessThan(node_->key); + if (node_ == list_->head_) { + node_ = NULL; + } +} + +template +inline void SkipList::Iterator::Seek(const Key& target) { + node_ = list_->FindGreaterOrEqual(target, NULL); +} + +template +inline void SkipList::Iterator::SeekToFirst() { + node_ = list_->head_->Next(0); +} + +template +inline void SkipList::Iterator::SeekToLast() { + node_ = list_->FindLast(); + if (node_ == list_->head_) { + node_ = NULL; + } +} + +template +int SkipList::RandomHeight() { + // Increase height with probability 1 in kBranching + static const unsigned int kBranching = 4; + int height = 1; + while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) { + height++; + } + assert(height > 0); + assert(height <= kMaxHeight); + return height; +} + +template +bool SkipList::KeyIsAfterNode(const Key& key, Node* n) const { + // NULL n is considered infinite + return (n != NULL) && (compare_(n->key, key) < 0); +} + +template +typename SkipList::Node* SkipList::FindGreaterOrEqual(const Key& key, Node** prev) + const { + Node* x = head_; + int level = GetMaxHeight() - 1; + while (true) { + Node* next = x->Next(level); + if (KeyIsAfterNode(key, next)) { + // Keep searching in this list + x = next; + } else { + if (prev != NULL) prev[level] = x; + if (level == 0) { + return next; + } else { + // Switch to next list + level--; + } + } + } +} + +template +typename SkipList::Node* +SkipList::FindLessThan(const Key& key) const { + Node* x = head_; + int level = GetMaxHeight() - 1; + while (true) { + assert(x == head_ || compare_(x->key, key) < 0); + Node* next = x->Next(level); + if (next == NULL || compare_(next->key, key) >= 0) { + if (level == 0) { + return x; + } else { + // Switch to next list + level--; + } + } else { + x = next; + } + } +} + +template +typename SkipList::Node* SkipList::FindLast() + const { + Node* x = head_; + int level = GetMaxHeight() - 1; + while (true) { + Node* next = x->Next(level); + if (next == NULL) { + if (level == 0) { + return x; + } else { + // Switch to next list + level--; + } + } else { + x = next; + } + } +} + +template +SkipList::SkipList(Comparator cmp, Arena* arena) + : compare_(cmp), + arena_(arena), + head_(NewNode(0 /* any key will do */, kMaxHeight)), + max_height_(reinterpret_cast(1)), + rnd_(0xdeadbeef) { + for (int i = 0; i < kMaxHeight; i++) { + head_->SetNext(i, NULL); + } +} + +template +void SkipList::Insert(const Key& key) { + // TODO(opt): We can use a barrier-free variant of FindGreaterOrEqual() + // here since Insert() is externally synchronized. + Node* prev[kMaxHeight]; + Node* x = FindGreaterOrEqual(key, prev); + + // Our data structure does not allow duplicate insertion + assert(x == NULL || !Equal(key, x->key)); + + int height = RandomHeight(); + if (height > GetMaxHeight()) { + for (int i = GetMaxHeight(); i < height; i++) { + prev[i] = head_; + } + //fprintf(stderr, "Change height from %d to %d\n", max_height_, height); + + // It is ok to mutate max_height_ without any synchronization + // with concurrent readers. A concurrent reader that observes + // the new value of max_height_ will see either the old value of + // new level pointers from head_ (NULL), or a new value set in + // the loop below. In the former case the reader will + // immediately drop to the next level since NULL sorts after all + // keys. In the latter case the reader will use the new node. + max_height_.NoBarrier_Store(reinterpret_cast(height)); + } + + x = NewNode(key, height); + for (int i = 0; i < height; i++) { + // NoBarrier_SetNext() suffices since we will add a barrier when + // we publish a pointer to "x" in prev[i]. + x->NoBarrier_SetNext(i, prev[i]->NoBarrier_Next(i)); + prev[i]->SetNext(i, x); + } +} + +template +bool SkipList::Contains(const Key& key) const { + Node* x = FindGreaterOrEqual(key, NULL); + if (x != NULL && Equal(key, x->key)) { + return true; + } else { + return false; + } +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_SKIPLIST_H_ diff --git a/My Mind/Pods/leveldb-library/db/snapshot.h b/My Mind/Pods/leveldb-library/db/snapshot.h new file mode 100644 index 0000000..6ed413c --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/snapshot.h @@ -0,0 +1,67 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_SNAPSHOT_H_ +#define STORAGE_LEVELDB_DB_SNAPSHOT_H_ + +#include "db/dbformat.h" +#include "leveldb/db.h" + +namespace leveldb { + +class SnapshotList; + +// Snapshots are kept in a doubly-linked list in the DB. +// Each SnapshotImpl corresponds to a particular sequence number. +class SnapshotImpl : public Snapshot { + public: + SequenceNumber number_; // const after creation + + private: + friend class SnapshotList; + + // SnapshotImpl is kept in a doubly-linked circular list + SnapshotImpl* prev_; + SnapshotImpl* next_; + + SnapshotList* list_; // just for sanity checks +}; + +class SnapshotList { + public: + SnapshotList() { + list_.prev_ = &list_; + list_.next_ = &list_; + } + + bool empty() const { return list_.next_ == &list_; } + SnapshotImpl* oldest() const { assert(!empty()); return list_.next_; } + SnapshotImpl* newest() const { assert(!empty()); return list_.prev_; } + + const SnapshotImpl* New(SequenceNumber seq) { + SnapshotImpl* s = new SnapshotImpl; + s->number_ = seq; + s->list_ = this; + s->next_ = &list_; + s->prev_ = list_.prev_; + s->prev_->next_ = s; + s->next_->prev_ = s; + return s; + } + + void Delete(const SnapshotImpl* s) { + assert(s->list_ == this); + s->prev_->next_ = s->next_; + s->next_->prev_ = s->prev_; + delete s; + } + + private: + // Dummy head of doubly-linked list of snapshots + SnapshotImpl list_; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_SNAPSHOT_H_ diff --git a/My Mind/Pods/leveldb-library/db/table_cache.cc b/My Mind/Pods/leveldb-library/db/table_cache.cc new file mode 100644 index 0000000..e3d82cd --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/table_cache.cc @@ -0,0 +1,127 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/table_cache.h" + +#include "db/filename.h" +#include "leveldb/env.h" +#include "leveldb/table.h" +#include "util/coding.h" + +namespace leveldb { + +struct TableAndFile { + RandomAccessFile* file; + Table* table; +}; + +static void DeleteEntry(const Slice& key, void* value) { + TableAndFile* tf = reinterpret_cast(value); + delete tf->table; + delete tf->file; + delete tf; +} + +static void UnrefEntry(void* arg1, void* arg2) { + Cache* cache = reinterpret_cast(arg1); + Cache::Handle* h = reinterpret_cast(arg2); + cache->Release(h); +} + +TableCache::TableCache(const std::string& dbname, + const Options* options, + int entries) + : env_(options->env), + dbname_(dbname), + options_(options), + cache_(NewLRUCache(entries)) { +} + +TableCache::~TableCache() { + delete cache_; +} + +Status TableCache::FindTable(uint64_t file_number, uint64_t file_size, + Cache::Handle** handle) { + Status s; + char buf[sizeof(file_number)]; + EncodeFixed64(buf, file_number); + Slice key(buf, sizeof(buf)); + *handle = cache_->Lookup(key); + if (*handle == NULL) { + std::string fname = TableFileName(dbname_, file_number); + RandomAccessFile* file = NULL; + Table* table = NULL; + s = env_->NewRandomAccessFile(fname, &file); + if (!s.ok()) { + std::string old_fname = SSTTableFileName(dbname_, file_number); + if (env_->NewRandomAccessFile(old_fname, &file).ok()) { + s = Status::OK(); + } + } + if (s.ok()) { + s = Table::Open(*options_, file, file_size, &table); + } + + if (!s.ok()) { + assert(table == NULL); + delete file; + // We do not cache error results so that if the error is transient, + // or somebody repairs the file, we recover automatically. + } else { + TableAndFile* tf = new TableAndFile; + tf->file = file; + tf->table = table; + *handle = cache_->Insert(key, tf, 1, &DeleteEntry); + } + } + return s; +} + +Iterator* TableCache::NewIterator(const ReadOptions& options, + uint64_t file_number, + uint64_t file_size, + Table** tableptr) { + if (tableptr != NULL) { + *tableptr = NULL; + } + + Cache::Handle* handle = NULL; + Status s = FindTable(file_number, file_size, &handle); + if (!s.ok()) { + return NewErrorIterator(s); + } + + Table* table = reinterpret_cast(cache_->Value(handle))->table; + Iterator* result = table->NewIterator(options); + result->RegisterCleanup(&UnrefEntry, cache_, handle); + if (tableptr != NULL) { + *tableptr = table; + } + return result; +} + +Status TableCache::Get(const ReadOptions& options, + uint64_t file_number, + uint64_t file_size, + const Slice& k, + void* arg, + void (*saver)(void*, const Slice&, const Slice&)) { + Cache::Handle* handle = NULL; + Status s = FindTable(file_number, file_size, &handle); + if (s.ok()) { + Table* t = reinterpret_cast(cache_->Value(handle))->table; + s = t->InternalGet(options, k, arg, saver); + cache_->Release(handle); + } + return s; +} + +void TableCache::Evict(uint64_t file_number) { + char buf[sizeof(file_number)]; + EncodeFixed64(buf, file_number); + cache_->Erase(Slice(buf, sizeof(buf))); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/table_cache.h b/My Mind/Pods/leveldb-library/db/table_cache.h new file mode 100644 index 0000000..8cf4aaf --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/table_cache.h @@ -0,0 +1,61 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Thread-safe (provides internal synchronization) + +#ifndef STORAGE_LEVELDB_DB_TABLE_CACHE_H_ +#define STORAGE_LEVELDB_DB_TABLE_CACHE_H_ + +#include +#include +#include "db/dbformat.h" +#include "leveldb/cache.h" +#include "leveldb/table.h" +#include "port/port.h" + +namespace leveldb { + +class Env; + +class TableCache { + public: + TableCache(const std::string& dbname, const Options* options, int entries); + ~TableCache(); + + // Return an iterator for the specified file number (the corresponding + // file length must be exactly "file_size" bytes). If "tableptr" is + // non-NULL, also sets "*tableptr" to point to the Table object + // underlying the returned iterator, or NULL if no Table object underlies + // the returned iterator. The returned "*tableptr" object is owned by + // the cache and should not be deleted, and is valid for as long as the + // returned iterator is live. + Iterator* NewIterator(const ReadOptions& options, + uint64_t file_number, + uint64_t file_size, + Table** tableptr = NULL); + + // If a seek to internal key "k" in specified file finds an entry, + // call (*handle_result)(arg, found_key, found_value). + Status Get(const ReadOptions& options, + uint64_t file_number, + uint64_t file_size, + const Slice& k, + void* arg, + void (*handle_result)(void*, const Slice&, const Slice&)); + + // Evict any entry for the specified file number + void Evict(uint64_t file_number); + + private: + Env* const env_; + const std::string dbname_; + const Options* options_; + Cache* cache_; + + Status FindTable(uint64_t file_number, uint64_t file_size, Cache::Handle**); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_TABLE_CACHE_H_ diff --git a/My Mind/Pods/leveldb-library/db/version_edit.cc b/My Mind/Pods/leveldb-library/db/version_edit.cc new file mode 100644 index 0000000..f10a2d5 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/version_edit.cc @@ -0,0 +1,266 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/version_edit.h" + +#include "db/version_set.h" +#include "util/coding.h" + +namespace leveldb { + +// Tag numbers for serialized VersionEdit. These numbers are written to +// disk and should not be changed. +enum Tag { + kComparator = 1, + kLogNumber = 2, + kNextFileNumber = 3, + kLastSequence = 4, + kCompactPointer = 5, + kDeletedFile = 6, + kNewFile = 7, + // 8 was used for large value refs + kPrevLogNumber = 9 +}; + +void VersionEdit::Clear() { + comparator_.clear(); + log_number_ = 0; + prev_log_number_ = 0; + last_sequence_ = 0; + next_file_number_ = 0; + has_comparator_ = false; + has_log_number_ = false; + has_prev_log_number_ = false; + has_next_file_number_ = false; + has_last_sequence_ = false; + deleted_files_.clear(); + new_files_.clear(); +} + +void VersionEdit::EncodeTo(std::string* dst) const { + if (has_comparator_) { + PutVarint32(dst, kComparator); + PutLengthPrefixedSlice(dst, comparator_); + } + if (has_log_number_) { + PutVarint32(dst, kLogNumber); + PutVarint64(dst, log_number_); + } + if (has_prev_log_number_) { + PutVarint32(dst, kPrevLogNumber); + PutVarint64(dst, prev_log_number_); + } + if (has_next_file_number_) { + PutVarint32(dst, kNextFileNumber); + PutVarint64(dst, next_file_number_); + } + if (has_last_sequence_) { + PutVarint32(dst, kLastSequence); + PutVarint64(dst, last_sequence_); + } + + for (size_t i = 0; i < compact_pointers_.size(); i++) { + PutVarint32(dst, kCompactPointer); + PutVarint32(dst, compact_pointers_[i].first); // level + PutLengthPrefixedSlice(dst, compact_pointers_[i].second.Encode()); + } + + for (DeletedFileSet::const_iterator iter = deleted_files_.begin(); + iter != deleted_files_.end(); + ++iter) { + PutVarint32(dst, kDeletedFile); + PutVarint32(dst, iter->first); // level + PutVarint64(dst, iter->second); // file number + } + + for (size_t i = 0; i < new_files_.size(); i++) { + const FileMetaData& f = new_files_[i].second; + PutVarint32(dst, kNewFile); + PutVarint32(dst, new_files_[i].first); // level + PutVarint64(dst, f.number); + PutVarint64(dst, f.file_size); + PutLengthPrefixedSlice(dst, f.smallest.Encode()); + PutLengthPrefixedSlice(dst, f.largest.Encode()); + } +} + +static bool GetInternalKey(Slice* input, InternalKey* dst) { + Slice str; + if (GetLengthPrefixedSlice(input, &str)) { + dst->DecodeFrom(str); + return true; + } else { + return false; + } +} + +static bool GetLevel(Slice* input, int* level) { + uint32_t v; + if (GetVarint32(input, &v) && + v < config::kNumLevels) { + *level = v; + return true; + } else { + return false; + } +} + +Status VersionEdit::DecodeFrom(const Slice& src) { + Clear(); + Slice input = src; + const char* msg = NULL; + uint32_t tag; + + // Temporary storage for parsing + int level; + uint64_t number; + FileMetaData f; + Slice str; + InternalKey key; + + while (msg == NULL && GetVarint32(&input, &tag)) { + switch (tag) { + case kComparator: + if (GetLengthPrefixedSlice(&input, &str)) { + comparator_ = str.ToString(); + has_comparator_ = true; + } else { + msg = "comparator name"; + } + break; + + case kLogNumber: + if (GetVarint64(&input, &log_number_)) { + has_log_number_ = true; + } else { + msg = "log number"; + } + break; + + case kPrevLogNumber: + if (GetVarint64(&input, &prev_log_number_)) { + has_prev_log_number_ = true; + } else { + msg = "previous log number"; + } + break; + + case kNextFileNumber: + if (GetVarint64(&input, &next_file_number_)) { + has_next_file_number_ = true; + } else { + msg = "next file number"; + } + break; + + case kLastSequence: + if (GetVarint64(&input, &last_sequence_)) { + has_last_sequence_ = true; + } else { + msg = "last sequence number"; + } + break; + + case kCompactPointer: + if (GetLevel(&input, &level) && + GetInternalKey(&input, &key)) { + compact_pointers_.push_back(std::make_pair(level, key)); + } else { + msg = "compaction pointer"; + } + break; + + case kDeletedFile: + if (GetLevel(&input, &level) && + GetVarint64(&input, &number)) { + deleted_files_.insert(std::make_pair(level, number)); + } else { + msg = "deleted file"; + } + break; + + case kNewFile: + if (GetLevel(&input, &level) && + GetVarint64(&input, &f.number) && + GetVarint64(&input, &f.file_size) && + GetInternalKey(&input, &f.smallest) && + GetInternalKey(&input, &f.largest)) { + new_files_.push_back(std::make_pair(level, f)); + } else { + msg = "new-file entry"; + } + break; + + default: + msg = "unknown tag"; + break; + } + } + + if (msg == NULL && !input.empty()) { + msg = "invalid tag"; + } + + Status result; + if (msg != NULL) { + result = Status::Corruption("VersionEdit", msg); + } + return result; +} + +std::string VersionEdit::DebugString() const { + std::string r; + r.append("VersionEdit {"); + if (has_comparator_) { + r.append("\n Comparator: "); + r.append(comparator_); + } + if (has_log_number_) { + r.append("\n LogNumber: "); + AppendNumberTo(&r, log_number_); + } + if (has_prev_log_number_) { + r.append("\n PrevLogNumber: "); + AppendNumberTo(&r, prev_log_number_); + } + if (has_next_file_number_) { + r.append("\n NextFile: "); + AppendNumberTo(&r, next_file_number_); + } + if (has_last_sequence_) { + r.append("\n LastSeq: "); + AppendNumberTo(&r, last_sequence_); + } + for (size_t i = 0; i < compact_pointers_.size(); i++) { + r.append("\n CompactPointer: "); + AppendNumberTo(&r, compact_pointers_[i].first); + r.append(" "); + r.append(compact_pointers_[i].second.DebugString()); + } + for (DeletedFileSet::const_iterator iter = deleted_files_.begin(); + iter != deleted_files_.end(); + ++iter) { + r.append("\n DeleteFile: "); + AppendNumberTo(&r, iter->first); + r.append(" "); + AppendNumberTo(&r, iter->second); + } + for (size_t i = 0; i < new_files_.size(); i++) { + const FileMetaData& f = new_files_[i].second; + r.append("\n AddFile: "); + AppendNumberTo(&r, new_files_[i].first); + r.append(" "); + AppendNumberTo(&r, f.number); + r.append(" "); + AppendNumberTo(&r, f.file_size); + r.append(" "); + r.append(f.smallest.DebugString()); + r.append(" .. "); + r.append(f.largest.DebugString()); + } + r.append("\n}\n"); + return r; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/version_edit.h b/My Mind/Pods/leveldb-library/db/version_edit.h new file mode 100644 index 0000000..eaef77b --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/version_edit.h @@ -0,0 +1,107 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_VERSION_EDIT_H_ +#define STORAGE_LEVELDB_DB_VERSION_EDIT_H_ + +#include +#include +#include +#include "db/dbformat.h" + +namespace leveldb { + +class VersionSet; + +struct FileMetaData { + int refs; + int allowed_seeks; // Seeks allowed until compaction + uint64_t number; + uint64_t file_size; // File size in bytes + InternalKey smallest; // Smallest internal key served by table + InternalKey largest; // Largest internal key served by table + + FileMetaData() : refs(0), allowed_seeks(1 << 30), file_size(0) { } +}; + +class VersionEdit { + public: + VersionEdit() { Clear(); } + ~VersionEdit() { } + + void Clear(); + + void SetComparatorName(const Slice& name) { + has_comparator_ = true; + comparator_ = name.ToString(); + } + void SetLogNumber(uint64_t num) { + has_log_number_ = true; + log_number_ = num; + } + void SetPrevLogNumber(uint64_t num) { + has_prev_log_number_ = true; + prev_log_number_ = num; + } + void SetNextFile(uint64_t num) { + has_next_file_number_ = true; + next_file_number_ = num; + } + void SetLastSequence(SequenceNumber seq) { + has_last_sequence_ = true; + last_sequence_ = seq; + } + void SetCompactPointer(int level, const InternalKey& key) { + compact_pointers_.push_back(std::make_pair(level, key)); + } + + // Add the specified file at the specified number. + // REQUIRES: This version has not been saved (see VersionSet::SaveTo) + // REQUIRES: "smallest" and "largest" are smallest and largest keys in file + void AddFile(int level, uint64_t file, + uint64_t file_size, + const InternalKey& smallest, + const InternalKey& largest) { + FileMetaData f; + f.number = file; + f.file_size = file_size; + f.smallest = smallest; + f.largest = largest; + new_files_.push_back(std::make_pair(level, f)); + } + + // Delete the specified "file" from the specified "level". + void DeleteFile(int level, uint64_t file) { + deleted_files_.insert(std::make_pair(level, file)); + } + + void EncodeTo(std::string* dst) const; + Status DecodeFrom(const Slice& src); + + std::string DebugString() const; + + private: + friend class VersionSet; + + typedef std::set< std::pair > DeletedFileSet; + + std::string comparator_; + uint64_t log_number_; + uint64_t prev_log_number_; + uint64_t next_file_number_; + SequenceNumber last_sequence_; + bool has_comparator_; + bool has_log_number_; + bool has_prev_log_number_; + bool has_next_file_number_; + bool has_last_sequence_; + + std::vector< std::pair > compact_pointers_; + DeletedFileSet deleted_files_; + std::vector< std::pair > new_files_; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_VERSION_EDIT_H_ diff --git a/My Mind/Pods/leveldb-library/db/version_set.cc b/My Mind/Pods/leveldb-library/db/version_set.cc new file mode 100644 index 0000000..b1256f9 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/version_set.cc @@ -0,0 +1,1535 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "db/version_set.h" + +#include +#include +#include "db/filename.h" +#include "db/log_reader.h" +#include "db/log_writer.h" +#include "db/memtable.h" +#include "db/table_cache.h" +#include "leveldb/env.h" +#include "leveldb/table_builder.h" +#include "table/merger.h" +#include "table/two_level_iterator.h" +#include "util/coding.h" +#include "util/logging.h" + +namespace leveldb { + +static int TargetFileSize(const Options* options) { + return options->max_file_size; +} + +// Maximum bytes of overlaps in grandparent (i.e., level+2) before we +// stop building a single file in a level->level+1 compaction. +static int64_t MaxGrandParentOverlapBytes(const Options* options) { + return 10 * TargetFileSize(options); +} + +// Maximum number of bytes in all compacted files. We avoid expanding +// the lower level file set of a compaction if it would make the +// total compaction cover more than this many bytes. +static int64_t ExpandedCompactionByteSizeLimit(const Options* options) { + return 25 * TargetFileSize(options); +} + +static double MaxBytesForLevel(const Options* options, int level) { + // Note: the result for level zero is not really used since we set + // the level-0 compaction threshold based on number of files. + + // Result for both level-0 and level-1 + double result = 10. * 1048576.0; + while (level > 1) { + result *= 10; + level--; + } + return result; +} + +static uint64_t MaxFileSizeForLevel(const Options* options, int level) { + // We could vary per level to reduce number of files? + return TargetFileSize(options); +} + +static int64_t TotalFileSize(const std::vector& files) { + int64_t sum = 0; + for (size_t i = 0; i < files.size(); i++) { + sum += files[i]->file_size; + } + return sum; +} + +Version::~Version() { + assert(refs_ == 0); + + // Remove from linked list + prev_->next_ = next_; + next_->prev_ = prev_; + + // Drop references to files + for (int level = 0; level < config::kNumLevels; level++) { + for (size_t i = 0; i < files_[level].size(); i++) { + FileMetaData* f = files_[level][i]; + assert(f->refs > 0); + f->refs--; + if (f->refs <= 0) { + delete f; + } + } + } +} + +int FindFile(const InternalKeyComparator& icmp, + const std::vector& files, + const Slice& key) { + uint32_t left = 0; + uint32_t right = files.size(); + while (left < right) { + uint32_t mid = (left + right) / 2; + const FileMetaData* f = files[mid]; + if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) { + // Key at "mid.largest" is < "target". Therefore all + // files at or before "mid" are uninteresting. + left = mid + 1; + } else { + // Key at "mid.largest" is >= "target". Therefore all files + // after "mid" are uninteresting. + right = mid; + } + } + return right; +} + +static bool AfterFile(const Comparator* ucmp, + const Slice* user_key, const FileMetaData* f) { + // NULL user_key occurs before all keys and is therefore never after *f + return (user_key != NULL && + ucmp->Compare(*user_key, f->largest.user_key()) > 0); +} + +static bool BeforeFile(const Comparator* ucmp, + const Slice* user_key, const FileMetaData* f) { + // NULL user_key occurs after all keys and is therefore never before *f + return (user_key != NULL && + ucmp->Compare(*user_key, f->smallest.user_key()) < 0); +} + +bool SomeFileOverlapsRange( + const InternalKeyComparator& icmp, + bool disjoint_sorted_files, + const std::vector& files, + const Slice* smallest_user_key, + const Slice* largest_user_key) { + const Comparator* ucmp = icmp.user_comparator(); + if (!disjoint_sorted_files) { + // Need to check against all files + for (size_t i = 0; i < files.size(); i++) { + const FileMetaData* f = files[i]; + if (AfterFile(ucmp, smallest_user_key, f) || + BeforeFile(ucmp, largest_user_key, f)) { + // No overlap + } else { + return true; // Overlap + } + } + return false; + } + + // Binary search over file list + uint32_t index = 0; + if (smallest_user_key != NULL) { + // Find the earliest possible internal key for smallest_user_key + InternalKey small(*smallest_user_key, kMaxSequenceNumber,kValueTypeForSeek); + index = FindFile(icmp, files, small.Encode()); + } + + if (index >= files.size()) { + // beginning of range is after all files, so no overlap. + return false; + } + + return !BeforeFile(ucmp, largest_user_key, files[index]); +} + +// An internal iterator. For a given version/level pair, yields +// information about the files in the level. For a given entry, key() +// is the largest key that occurs in the file, and value() is an +// 16-byte value containing the file number and file size, both +// encoded using EncodeFixed64. +class Version::LevelFileNumIterator : public Iterator { + public: + LevelFileNumIterator(const InternalKeyComparator& icmp, + const std::vector* flist) + : icmp_(icmp), + flist_(flist), + index_(flist->size()) { // Marks as invalid + } + virtual bool Valid() const { + return index_ < flist_->size(); + } + virtual void Seek(const Slice& target) { + index_ = FindFile(icmp_, *flist_, target); + } + virtual void SeekToFirst() { index_ = 0; } + virtual void SeekToLast() { + index_ = flist_->empty() ? 0 : flist_->size() - 1; + } + virtual void Next() { + assert(Valid()); + index_++; + } + virtual void Prev() { + assert(Valid()); + if (index_ == 0) { + index_ = flist_->size(); // Marks as invalid + } else { + index_--; + } + } + Slice key() const { + assert(Valid()); + return (*flist_)[index_]->largest.Encode(); + } + Slice value() const { + assert(Valid()); + EncodeFixed64(value_buf_, (*flist_)[index_]->number); + EncodeFixed64(value_buf_+8, (*flist_)[index_]->file_size); + return Slice(value_buf_, sizeof(value_buf_)); + } + virtual Status status() const { return Status::OK(); } + private: + const InternalKeyComparator icmp_; + const std::vector* const flist_; + uint32_t index_; + + // Backing store for value(). Holds the file number and size. + mutable char value_buf_[16]; +}; + +static Iterator* GetFileIterator(void* arg, + const ReadOptions& options, + const Slice& file_value) { + TableCache* cache = reinterpret_cast(arg); + if (file_value.size() != 16) { + return NewErrorIterator( + Status::Corruption("FileReader invoked with unexpected value")); + } else { + return cache->NewIterator(options, + DecodeFixed64(file_value.data()), + DecodeFixed64(file_value.data() + 8)); + } +} + +Iterator* Version::NewConcatenatingIterator(const ReadOptions& options, + int level) const { + return NewTwoLevelIterator( + new LevelFileNumIterator(vset_->icmp_, &files_[level]), + &GetFileIterator, vset_->table_cache_, options); +} + +void Version::AddIterators(const ReadOptions& options, + std::vector* iters) { + // Merge all level zero files together since they may overlap + for (size_t i = 0; i < files_[0].size(); i++) { + iters->push_back( + vset_->table_cache_->NewIterator( + options, files_[0][i]->number, files_[0][i]->file_size)); + } + + // For levels > 0, we can use a concatenating iterator that sequentially + // walks through the non-overlapping files in the level, opening them + // lazily. + for (int level = 1; level < config::kNumLevels; level++) { + if (!files_[level].empty()) { + iters->push_back(NewConcatenatingIterator(options, level)); + } + } +} + +// Callback from TableCache::Get() +namespace { +enum SaverState { + kNotFound, + kFound, + kDeleted, + kCorrupt, +}; +struct Saver { + SaverState state; + const Comparator* ucmp; + Slice user_key; + std::string* value; +}; +} +static void SaveValue(void* arg, const Slice& ikey, const Slice& v) { + Saver* s = reinterpret_cast(arg); + ParsedInternalKey parsed_key; + if (!ParseInternalKey(ikey, &parsed_key)) { + s->state = kCorrupt; + } else { + if (s->ucmp->Compare(parsed_key.user_key, s->user_key) == 0) { + s->state = (parsed_key.type == kTypeValue) ? kFound : kDeleted; + if (s->state == kFound) { + s->value->assign(v.data(), v.size()); + } + } + } +} + +static bool NewestFirst(FileMetaData* a, FileMetaData* b) { + return a->number > b->number; +} + +void Version::ForEachOverlapping(Slice user_key, Slice internal_key, + void* arg, + bool (*func)(void*, int, FileMetaData*)) { + // TODO(sanjay): Change Version::Get() to use this function. + const Comparator* ucmp = vset_->icmp_.user_comparator(); + + // Search level-0 in order from newest to oldest. + std::vector tmp; + tmp.reserve(files_[0].size()); + for (uint32_t i = 0; i < files_[0].size(); i++) { + FileMetaData* f = files_[0][i]; + if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 && + ucmp->Compare(user_key, f->largest.user_key()) <= 0) { + tmp.push_back(f); + } + } + if (!tmp.empty()) { + std::sort(tmp.begin(), tmp.end(), NewestFirst); + for (uint32_t i = 0; i < tmp.size(); i++) { + if (!(*func)(arg, 0, tmp[i])) { + return; + } + } + } + + // Search other levels. + for (int level = 1; level < config::kNumLevels; level++) { + size_t num_files = files_[level].size(); + if (num_files == 0) continue; + + // Binary search to find earliest index whose largest key >= internal_key. + uint32_t index = FindFile(vset_->icmp_, files_[level], internal_key); + if (index < num_files) { + FileMetaData* f = files_[level][index]; + if (ucmp->Compare(user_key, f->smallest.user_key()) < 0) { + // All of "f" is past any data for user_key + } else { + if (!(*func)(arg, level, f)) { + return; + } + } + } + } +} + +Status Version::Get(const ReadOptions& options, + const LookupKey& k, + std::string* value, + GetStats* stats) { + Slice ikey = k.internal_key(); + Slice user_key = k.user_key(); + const Comparator* ucmp = vset_->icmp_.user_comparator(); + Status s; + + stats->seek_file = NULL; + stats->seek_file_level = -1; + FileMetaData* last_file_read = NULL; + int last_file_read_level = -1; + + // We can search level-by-level since entries never hop across + // levels. Therefore we are guaranteed that if we find data + // in an smaller level, later levels are irrelevant. + std::vector tmp; + FileMetaData* tmp2; + for (int level = 0; level < config::kNumLevels; level++) { + size_t num_files = files_[level].size(); + if (num_files == 0) continue; + + // Get the list of files to search in this level + FileMetaData* const* files = &files_[level][0]; + if (level == 0) { + // Level-0 files may overlap each other. Find all files that + // overlap user_key and process them in order from newest to oldest. + tmp.reserve(num_files); + for (uint32_t i = 0; i < num_files; i++) { + FileMetaData* f = files[i]; + if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 && + ucmp->Compare(user_key, f->largest.user_key()) <= 0) { + tmp.push_back(f); + } + } + if (tmp.empty()) continue; + + std::sort(tmp.begin(), tmp.end(), NewestFirst); + files = &tmp[0]; + num_files = tmp.size(); + } else { + // Binary search to find earliest index whose largest key >= ikey. + uint32_t index = FindFile(vset_->icmp_, files_[level], ikey); + if (index >= num_files) { + files = NULL; + num_files = 0; + } else { + tmp2 = files[index]; + if (ucmp->Compare(user_key, tmp2->smallest.user_key()) < 0) { + // All of "tmp2" is past any data for user_key + files = NULL; + num_files = 0; + } else { + files = &tmp2; + num_files = 1; + } + } + } + + for (uint32_t i = 0; i < num_files; ++i) { + if (last_file_read != NULL && stats->seek_file == NULL) { + // We have had more than one seek for this read. Charge the 1st file. + stats->seek_file = last_file_read; + stats->seek_file_level = last_file_read_level; + } + + FileMetaData* f = files[i]; + last_file_read = f; + last_file_read_level = level; + + Saver saver; + saver.state = kNotFound; + saver.ucmp = ucmp; + saver.user_key = user_key; + saver.value = value; + s = vset_->table_cache_->Get(options, f->number, f->file_size, + ikey, &saver, SaveValue); + if (!s.ok()) { + return s; + } + switch (saver.state) { + case kNotFound: + break; // Keep searching in other files + case kFound: + return s; + case kDeleted: + s = Status::NotFound(Slice()); // Use empty error message for speed + return s; + case kCorrupt: + s = Status::Corruption("corrupted key for ", user_key); + return s; + } + } + } + + return Status::NotFound(Slice()); // Use an empty error message for speed +} + +bool Version::UpdateStats(const GetStats& stats) { + FileMetaData* f = stats.seek_file; + if (f != NULL) { + f->allowed_seeks--; + if (f->allowed_seeks <= 0 && file_to_compact_ == NULL) { + file_to_compact_ = f; + file_to_compact_level_ = stats.seek_file_level; + return true; + } + } + return false; +} + +bool Version::RecordReadSample(Slice internal_key) { + ParsedInternalKey ikey; + if (!ParseInternalKey(internal_key, &ikey)) { + return false; + } + + struct State { + GetStats stats; // Holds first matching file + int matches; + + static bool Match(void* arg, int level, FileMetaData* f) { + State* state = reinterpret_cast(arg); + state->matches++; + if (state->matches == 1) { + // Remember first match. + state->stats.seek_file = f; + state->stats.seek_file_level = level; + } + // We can stop iterating once we have a second match. + return state->matches < 2; + } + }; + + State state; + state.matches = 0; + ForEachOverlapping(ikey.user_key, internal_key, &state, &State::Match); + + // Must have at least two matches since we want to merge across + // files. But what if we have a single file that contains many + // overwrites and deletions? Should we have another mechanism for + // finding such files? + if (state.matches >= 2) { + // 1MB cost is about 1 seek (see comment in Builder::Apply). + return UpdateStats(state.stats); + } + return false; +} + +void Version::Ref() { + ++refs_; +} + +void Version::Unref() { + assert(this != &vset_->dummy_versions_); + assert(refs_ >= 1); + --refs_; + if (refs_ == 0) { + delete this; + } +} + +bool Version::OverlapInLevel(int level, + const Slice* smallest_user_key, + const Slice* largest_user_key) { + return SomeFileOverlapsRange(vset_->icmp_, (level > 0), files_[level], + smallest_user_key, largest_user_key); +} + +int Version::PickLevelForMemTableOutput( + const Slice& smallest_user_key, + const Slice& largest_user_key) { + int level = 0; + if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) { + // Push to next level if there is no overlap in next level, + // and the #bytes overlapping in the level after that are limited. + InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek); + InternalKey limit(largest_user_key, 0, static_cast(0)); + std::vector overlaps; + while (level < config::kMaxMemCompactLevel) { + if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) { + break; + } + if (level + 2 < config::kNumLevels) { + // Check that file does not overlap too many grandparent bytes. + GetOverlappingInputs(level + 2, &start, &limit, &overlaps); + const int64_t sum = TotalFileSize(overlaps); + if (sum > MaxGrandParentOverlapBytes(vset_->options_)) { + break; + } + } + level++; + } + } + return level; +} + +// Store in "*inputs" all files in "level" that overlap [begin,end] +void Version::GetOverlappingInputs( + int level, + const InternalKey* begin, + const InternalKey* end, + std::vector* inputs) { + assert(level >= 0); + assert(level < config::kNumLevels); + inputs->clear(); + Slice user_begin, user_end; + if (begin != NULL) { + user_begin = begin->user_key(); + } + if (end != NULL) { + user_end = end->user_key(); + } + const Comparator* user_cmp = vset_->icmp_.user_comparator(); + for (size_t i = 0; i < files_[level].size(); ) { + FileMetaData* f = files_[level][i++]; + const Slice file_start = f->smallest.user_key(); + const Slice file_limit = f->largest.user_key(); + if (begin != NULL && user_cmp->Compare(file_limit, user_begin) < 0) { + // "f" is completely before specified range; skip it + } else if (end != NULL && user_cmp->Compare(file_start, user_end) > 0) { + // "f" is completely after specified range; skip it + } else { + inputs->push_back(f); + if (level == 0) { + // Level-0 files may overlap each other. So check if the newly + // added file has expanded the range. If so, restart search. + if (begin != NULL && user_cmp->Compare(file_start, user_begin) < 0) { + user_begin = file_start; + inputs->clear(); + i = 0; + } else if (end != NULL && user_cmp->Compare(file_limit, user_end) > 0) { + user_end = file_limit; + inputs->clear(); + i = 0; + } + } + } + } +} + +std::string Version::DebugString() const { + std::string r; + for (int level = 0; level < config::kNumLevels; level++) { + // E.g., + // --- level 1 --- + // 17:123['a' .. 'd'] + // 20:43['e' .. 'g'] + r.append("--- level "); + AppendNumberTo(&r, level); + r.append(" ---\n"); + const std::vector& files = files_[level]; + for (size_t i = 0; i < files.size(); i++) { + r.push_back(' '); + AppendNumberTo(&r, files[i]->number); + r.push_back(':'); + AppendNumberTo(&r, files[i]->file_size); + r.append("["); + r.append(files[i]->smallest.DebugString()); + r.append(" .. "); + r.append(files[i]->largest.DebugString()); + r.append("]\n"); + } + } + return r; +} + +// A helper class so we can efficiently apply a whole sequence +// of edits to a particular state without creating intermediate +// Versions that contain full copies of the intermediate state. +class VersionSet::Builder { + private: + // Helper to sort by v->files_[file_number].smallest + struct BySmallestKey { + const InternalKeyComparator* internal_comparator; + + bool operator()(FileMetaData* f1, FileMetaData* f2) const { + int r = internal_comparator->Compare(f1->smallest, f2->smallest); + if (r != 0) { + return (r < 0); + } else { + // Break ties by file number + return (f1->number < f2->number); + } + } + }; + + typedef std::set FileSet; + struct LevelState { + std::set deleted_files; + FileSet* added_files; + }; + + VersionSet* vset_; + Version* base_; + LevelState levels_[config::kNumLevels]; + + public: + // Initialize a builder with the files from *base and other info from *vset + Builder(VersionSet* vset, Version* base) + : vset_(vset), + base_(base) { + base_->Ref(); + BySmallestKey cmp; + cmp.internal_comparator = &vset_->icmp_; + for (int level = 0; level < config::kNumLevels; level++) { + levels_[level].added_files = new FileSet(cmp); + } + } + + ~Builder() { + for (int level = 0; level < config::kNumLevels; level++) { + const FileSet* added = levels_[level].added_files; + std::vector to_unref; + to_unref.reserve(added->size()); + for (FileSet::const_iterator it = added->begin(); + it != added->end(); ++it) { + to_unref.push_back(*it); + } + delete added; + for (uint32_t i = 0; i < to_unref.size(); i++) { + FileMetaData* f = to_unref[i]; + f->refs--; + if (f->refs <= 0) { + delete f; + } + } + } + base_->Unref(); + } + + // Apply all of the edits in *edit to the current state. + void Apply(VersionEdit* edit) { + // Update compaction pointers + for (size_t i = 0; i < edit->compact_pointers_.size(); i++) { + const int level = edit->compact_pointers_[i].first; + vset_->compact_pointer_[level] = + edit->compact_pointers_[i].second.Encode().ToString(); + } + + // Delete files + const VersionEdit::DeletedFileSet& del = edit->deleted_files_; + for (VersionEdit::DeletedFileSet::const_iterator iter = del.begin(); + iter != del.end(); + ++iter) { + const int level = iter->first; + const uint64_t number = iter->second; + levels_[level].deleted_files.insert(number); + } + + // Add new files + for (size_t i = 0; i < edit->new_files_.size(); i++) { + const int level = edit->new_files_[i].first; + FileMetaData* f = new FileMetaData(edit->new_files_[i].second); + f->refs = 1; + + // We arrange to automatically compact this file after + // a certain number of seeks. Let's assume: + // (1) One seek costs 10ms + // (2) Writing or reading 1MB costs 10ms (100MB/s) + // (3) A compaction of 1MB does 25MB of IO: + // 1MB read from this level + // 10-12MB read from next level (boundaries may be misaligned) + // 10-12MB written to next level + // This implies that 25 seeks cost the same as the compaction + // of 1MB of data. I.e., one seek costs approximately the + // same as the compaction of 40KB of data. We are a little + // conservative and allow approximately one seek for every 16KB + // of data before triggering a compaction. + f->allowed_seeks = (f->file_size / 16384); + if (f->allowed_seeks < 100) f->allowed_seeks = 100; + + levels_[level].deleted_files.erase(f->number); + levels_[level].added_files->insert(f); + } + } + + // Save the current state in *v. + void SaveTo(Version* v) { + BySmallestKey cmp; + cmp.internal_comparator = &vset_->icmp_; + for (int level = 0; level < config::kNumLevels; level++) { + // Merge the set of added files with the set of pre-existing files. + // Drop any deleted files. Store the result in *v. + const std::vector& base_files = base_->files_[level]; + std::vector::const_iterator base_iter = base_files.begin(); + std::vector::const_iterator base_end = base_files.end(); + const FileSet* added = levels_[level].added_files; + v->files_[level].reserve(base_files.size() + added->size()); + for (FileSet::const_iterator added_iter = added->begin(); + added_iter != added->end(); + ++added_iter) { + // Add all smaller files listed in base_ + for (std::vector::const_iterator bpos + = std::upper_bound(base_iter, base_end, *added_iter, cmp); + base_iter != bpos; + ++base_iter) { + MaybeAddFile(v, level, *base_iter); + } + + MaybeAddFile(v, level, *added_iter); + } + + // Add remaining base files + for (; base_iter != base_end; ++base_iter) { + MaybeAddFile(v, level, *base_iter); + } + +#ifndef NDEBUG + // Make sure there is no overlap in levels > 0 + if (level > 0) { + for (uint32_t i = 1; i < v->files_[level].size(); i++) { + const InternalKey& prev_end = v->files_[level][i-1]->largest; + const InternalKey& this_begin = v->files_[level][i]->smallest; + if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) { + fprintf(stderr, "overlapping ranges in same level %s vs. %s\n", + prev_end.DebugString().c_str(), + this_begin.DebugString().c_str()); + abort(); + } + } + } +#endif + } + } + + void MaybeAddFile(Version* v, int level, FileMetaData* f) { + if (levels_[level].deleted_files.count(f->number) > 0) { + // File is deleted: do nothing + } else { + std::vector* files = &v->files_[level]; + if (level > 0 && !files->empty()) { + // Must not overlap + assert(vset_->icmp_.Compare((*files)[files->size()-1]->largest, + f->smallest) < 0); + } + f->refs++; + files->push_back(f); + } + } +}; + +VersionSet::VersionSet(const std::string& dbname, + const Options* options, + TableCache* table_cache, + const InternalKeyComparator* cmp) + : env_(options->env), + dbname_(dbname), + options_(options), + table_cache_(table_cache), + icmp_(*cmp), + next_file_number_(2), + manifest_file_number_(0), // Filled by Recover() + last_sequence_(0), + log_number_(0), + prev_log_number_(0), + descriptor_file_(NULL), + descriptor_log_(NULL), + dummy_versions_(this), + current_(NULL) { + AppendVersion(new Version(this)); +} + +VersionSet::~VersionSet() { + current_->Unref(); + assert(dummy_versions_.next_ == &dummy_versions_); // List must be empty + delete descriptor_log_; + delete descriptor_file_; +} + +void VersionSet::AppendVersion(Version* v) { + // Make "v" current + assert(v->refs_ == 0); + assert(v != current_); + if (current_ != NULL) { + current_->Unref(); + } + current_ = v; + v->Ref(); + + // Append to linked list + v->prev_ = dummy_versions_.prev_; + v->next_ = &dummy_versions_; + v->prev_->next_ = v; + v->next_->prev_ = v; +} + +Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) { + if (edit->has_log_number_) { + assert(edit->log_number_ >= log_number_); + assert(edit->log_number_ < next_file_number_); + } else { + edit->SetLogNumber(log_number_); + } + + if (!edit->has_prev_log_number_) { + edit->SetPrevLogNumber(prev_log_number_); + } + + edit->SetNextFile(next_file_number_); + edit->SetLastSequence(last_sequence_); + + Version* v = new Version(this); + { + Builder builder(this, current_); + builder.Apply(edit); + builder.SaveTo(v); + } + Finalize(v); + + // Initialize new descriptor log file if necessary by creating + // a temporary file that contains a snapshot of the current version. + std::string new_manifest_file; + Status s; + if (descriptor_log_ == NULL) { + // No reason to unlock *mu here since we only hit this path in the + // first call to LogAndApply (when opening the database). + assert(descriptor_file_ == NULL); + new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_); + edit->SetNextFile(next_file_number_); + s = env_->NewWritableFile(new_manifest_file, &descriptor_file_); + if (s.ok()) { + descriptor_log_ = new log::Writer(descriptor_file_); + s = WriteSnapshot(descriptor_log_); + } + } + + // Unlock during expensive MANIFEST log write + { + mu->Unlock(); + + // Write new record to MANIFEST log + if (s.ok()) { + std::string record; + edit->EncodeTo(&record); + s = descriptor_log_->AddRecord(record); + if (s.ok()) { + s = descriptor_file_->Sync(); + } + if (!s.ok()) { + Log(options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str()); + } + } + + // If we just created a new descriptor file, install it by writing a + // new CURRENT file that points to it. + if (s.ok() && !new_manifest_file.empty()) { + s = SetCurrentFile(env_, dbname_, manifest_file_number_); + } + + mu->Lock(); + } + + // Install the new version + if (s.ok()) { + AppendVersion(v); + log_number_ = edit->log_number_; + prev_log_number_ = edit->prev_log_number_; + } else { + delete v; + if (!new_manifest_file.empty()) { + delete descriptor_log_; + delete descriptor_file_; + descriptor_log_ = NULL; + descriptor_file_ = NULL; + env_->DeleteFile(new_manifest_file); + } + } + + return s; +} + +Status VersionSet::Recover(bool *save_manifest) { + struct LogReporter : public log::Reader::Reporter { + Status* status; + virtual void Corruption(size_t bytes, const Status& s) { + if (this->status->ok()) *this->status = s; + } + }; + + // Read "CURRENT" file, which contains a pointer to the current manifest file + std::string current; + Status s = ReadFileToString(env_, CurrentFileName(dbname_), ¤t); + if (!s.ok()) { + return s; + } + if (current.empty() || current[current.size()-1] != '\n') { + return Status::Corruption("CURRENT file does not end with newline"); + } + current.resize(current.size() - 1); + + std::string dscname = dbname_ + "/" + current; + SequentialFile* file; + s = env_->NewSequentialFile(dscname, &file); + if (!s.ok()) { + return s; + } + + bool have_log_number = false; + bool have_prev_log_number = false; + bool have_next_file = false; + bool have_last_sequence = false; + uint64_t next_file = 0; + uint64_t last_sequence = 0; + uint64_t log_number = 0; + uint64_t prev_log_number = 0; + Builder builder(this, current_); + + { + LogReporter reporter; + reporter.status = &s; + log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/); + Slice record; + std::string scratch; + while (reader.ReadRecord(&record, &scratch) && s.ok()) { + VersionEdit edit; + s = edit.DecodeFrom(record); + if (s.ok()) { + if (edit.has_comparator_ && + edit.comparator_ != icmp_.user_comparator()->Name()) { + s = Status::InvalidArgument( + edit.comparator_ + " does not match existing comparator ", + icmp_.user_comparator()->Name()); + } + } + + if (s.ok()) { + builder.Apply(&edit); + } + + if (edit.has_log_number_) { + log_number = edit.log_number_; + have_log_number = true; + } + + if (edit.has_prev_log_number_) { + prev_log_number = edit.prev_log_number_; + have_prev_log_number = true; + } + + if (edit.has_next_file_number_) { + next_file = edit.next_file_number_; + have_next_file = true; + } + + if (edit.has_last_sequence_) { + last_sequence = edit.last_sequence_; + have_last_sequence = true; + } + } + } + delete file; + file = NULL; + + if (s.ok()) { + if (!have_next_file) { + s = Status::Corruption("no meta-nextfile entry in descriptor"); + } else if (!have_log_number) { + s = Status::Corruption("no meta-lognumber entry in descriptor"); + } else if (!have_last_sequence) { + s = Status::Corruption("no last-sequence-number entry in descriptor"); + } + + if (!have_prev_log_number) { + prev_log_number = 0; + } + + MarkFileNumberUsed(prev_log_number); + MarkFileNumberUsed(log_number); + } + + if (s.ok()) { + Version* v = new Version(this); + builder.SaveTo(v); + // Install recovered version + Finalize(v); + AppendVersion(v); + manifest_file_number_ = next_file; + next_file_number_ = next_file + 1; + last_sequence_ = last_sequence; + log_number_ = log_number; + prev_log_number_ = prev_log_number; + + // See if we can reuse the existing MANIFEST file. + if (ReuseManifest(dscname, current)) { + // No need to save new manifest + } else { + *save_manifest = true; + } + } + + return s; +} + +bool VersionSet::ReuseManifest(const std::string& dscname, + const std::string& dscbase) { + if (!options_->reuse_logs) { + return false; + } + FileType manifest_type; + uint64_t manifest_number; + uint64_t manifest_size; + if (!ParseFileName(dscbase, &manifest_number, &manifest_type) || + manifest_type != kDescriptorFile || + !env_->GetFileSize(dscname, &manifest_size).ok() || + // Make new compacted MANIFEST if old one is too big + manifest_size >= TargetFileSize(options_)) { + return false; + } + + assert(descriptor_file_ == NULL); + assert(descriptor_log_ == NULL); + Status r = env_->NewAppendableFile(dscname, &descriptor_file_); + if (!r.ok()) { + Log(options_->info_log, "Reuse MANIFEST: %s\n", r.ToString().c_str()); + assert(descriptor_file_ == NULL); + return false; + } + + Log(options_->info_log, "Reusing MANIFEST %s\n", dscname.c_str()); + descriptor_log_ = new log::Writer(descriptor_file_, manifest_size); + manifest_file_number_ = manifest_number; + return true; +} + +void VersionSet::MarkFileNumberUsed(uint64_t number) { + if (next_file_number_ <= number) { + next_file_number_ = number + 1; + } +} + +void VersionSet::Finalize(Version* v) { + // Precomputed best level for next compaction + int best_level = -1; + double best_score = -1; + + for (int level = 0; level < config::kNumLevels-1; level++) { + double score; + if (level == 0) { + // We treat level-0 specially by bounding the number of files + // instead of number of bytes for two reasons: + // + // (1) With larger write-buffer sizes, it is nice not to do too + // many level-0 compactions. + // + // (2) The files in level-0 are merged on every read and + // therefore we wish to avoid too many files when the individual + // file size is small (perhaps because of a small write-buffer + // setting, or very high compression ratios, or lots of + // overwrites/deletions). + score = v->files_[level].size() / + static_cast(config::kL0_CompactionTrigger); + } else { + // Compute the ratio of current size to size limit. + const uint64_t level_bytes = TotalFileSize(v->files_[level]); + score = + static_cast(level_bytes) / MaxBytesForLevel(options_, level); + } + + if (score > best_score) { + best_level = level; + best_score = score; + } + } + + v->compaction_level_ = best_level; + v->compaction_score_ = best_score; +} + +Status VersionSet::WriteSnapshot(log::Writer* log) { + // TODO: Break up into multiple records to reduce memory usage on recovery? + + // Save metadata + VersionEdit edit; + edit.SetComparatorName(icmp_.user_comparator()->Name()); + + // Save compaction pointers + for (int level = 0; level < config::kNumLevels; level++) { + if (!compact_pointer_[level].empty()) { + InternalKey key; + key.DecodeFrom(compact_pointer_[level]); + edit.SetCompactPointer(level, key); + } + } + + // Save files + for (int level = 0; level < config::kNumLevels; level++) { + const std::vector& files = current_->files_[level]; + for (size_t i = 0; i < files.size(); i++) { + const FileMetaData* f = files[i]; + edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest); + } + } + + std::string record; + edit.EncodeTo(&record); + return log->AddRecord(record); +} + +int VersionSet::NumLevelFiles(int level) const { + assert(level >= 0); + assert(level < config::kNumLevels); + return current_->files_[level].size(); +} + +const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const { + // Update code if kNumLevels changes + assert(config::kNumLevels == 7); + snprintf(scratch->buffer, sizeof(scratch->buffer), + "files[ %d %d %d %d %d %d %d ]", + int(current_->files_[0].size()), + int(current_->files_[1].size()), + int(current_->files_[2].size()), + int(current_->files_[3].size()), + int(current_->files_[4].size()), + int(current_->files_[5].size()), + int(current_->files_[6].size())); + return scratch->buffer; +} + +uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) { + uint64_t result = 0; + for (int level = 0; level < config::kNumLevels; level++) { + const std::vector& files = v->files_[level]; + for (size_t i = 0; i < files.size(); i++) { + if (icmp_.Compare(files[i]->largest, ikey) <= 0) { + // Entire file is before "ikey", so just add the file size + result += files[i]->file_size; + } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) { + // Entire file is after "ikey", so ignore + if (level > 0) { + // Files other than level 0 are sorted by meta->smallest, so + // no further files in this level will contain data for + // "ikey". + break; + } + } else { + // "ikey" falls in the range for this table. Add the + // approximate offset of "ikey" within the table. + Table* tableptr; + Iterator* iter = table_cache_->NewIterator( + ReadOptions(), files[i]->number, files[i]->file_size, &tableptr); + if (tableptr != NULL) { + result += tableptr->ApproximateOffsetOf(ikey.Encode()); + } + delete iter; + } + } + } + return result; +} + +void VersionSet::AddLiveFiles(std::set* live) { + for (Version* v = dummy_versions_.next_; + v != &dummy_versions_; + v = v->next_) { + for (int level = 0; level < config::kNumLevels; level++) { + const std::vector& files = v->files_[level]; + for (size_t i = 0; i < files.size(); i++) { + live->insert(files[i]->number); + } + } + } +} + +int64_t VersionSet::NumLevelBytes(int level) const { + assert(level >= 0); + assert(level < config::kNumLevels); + return TotalFileSize(current_->files_[level]); +} + +int64_t VersionSet::MaxNextLevelOverlappingBytes() { + int64_t result = 0; + std::vector overlaps; + for (int level = 1; level < config::kNumLevels - 1; level++) { + for (size_t i = 0; i < current_->files_[level].size(); i++) { + const FileMetaData* f = current_->files_[level][i]; + current_->GetOverlappingInputs(level+1, &f->smallest, &f->largest, + &overlaps); + const int64_t sum = TotalFileSize(overlaps); + if (sum > result) { + result = sum; + } + } + } + return result; +} + +// Stores the minimal range that covers all entries in inputs in +// *smallest, *largest. +// REQUIRES: inputs is not empty +void VersionSet::GetRange(const std::vector& inputs, + InternalKey* smallest, + InternalKey* largest) { + assert(!inputs.empty()); + smallest->Clear(); + largest->Clear(); + for (size_t i = 0; i < inputs.size(); i++) { + FileMetaData* f = inputs[i]; + if (i == 0) { + *smallest = f->smallest; + *largest = f->largest; + } else { + if (icmp_.Compare(f->smallest, *smallest) < 0) { + *smallest = f->smallest; + } + if (icmp_.Compare(f->largest, *largest) > 0) { + *largest = f->largest; + } + } + } +} + +// Stores the minimal range that covers all entries in inputs1 and inputs2 +// in *smallest, *largest. +// REQUIRES: inputs is not empty +void VersionSet::GetRange2(const std::vector& inputs1, + const std::vector& inputs2, + InternalKey* smallest, + InternalKey* largest) { + std::vector all = inputs1; + all.insert(all.end(), inputs2.begin(), inputs2.end()); + GetRange(all, smallest, largest); +} + +Iterator* VersionSet::MakeInputIterator(Compaction* c) { + ReadOptions options; + options.verify_checksums = options_->paranoid_checks; + options.fill_cache = false; + + // Level-0 files have to be merged together. For other levels, + // we will make a concatenating iterator per level. + // TODO(opt): use concatenating iterator for level-0 if there is no overlap + const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2); + Iterator** list = new Iterator*[space]; + int num = 0; + for (int which = 0; which < 2; which++) { + if (!c->inputs_[which].empty()) { + if (c->level() + which == 0) { + const std::vector& files = c->inputs_[which]; + for (size_t i = 0; i < files.size(); i++) { + list[num++] = table_cache_->NewIterator( + options, files[i]->number, files[i]->file_size); + } + } else { + // Create concatenating iterator for the files from this level + list[num++] = NewTwoLevelIterator( + new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]), + &GetFileIterator, table_cache_, options); + } + } + } + assert(num <= space); + Iterator* result = NewMergingIterator(&icmp_, list, num); + delete[] list; + return result; +} + +Compaction* VersionSet::PickCompaction() { + Compaction* c; + int level; + + // We prefer compactions triggered by too much data in a level over + // the compactions triggered by seeks. + const bool size_compaction = (current_->compaction_score_ >= 1); + const bool seek_compaction = (current_->file_to_compact_ != NULL); + if (size_compaction) { + level = current_->compaction_level_; + assert(level >= 0); + assert(level+1 < config::kNumLevels); + c = new Compaction(options_, level); + + // Pick the first file that comes after compact_pointer_[level] + for (size_t i = 0; i < current_->files_[level].size(); i++) { + FileMetaData* f = current_->files_[level][i]; + if (compact_pointer_[level].empty() || + icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) { + c->inputs_[0].push_back(f); + break; + } + } + if (c->inputs_[0].empty()) { + // Wrap-around to the beginning of the key space + c->inputs_[0].push_back(current_->files_[level][0]); + } + } else if (seek_compaction) { + level = current_->file_to_compact_level_; + c = new Compaction(options_, level); + c->inputs_[0].push_back(current_->file_to_compact_); + } else { + return NULL; + } + + c->input_version_ = current_; + c->input_version_->Ref(); + + // Files in level 0 may overlap each other, so pick up all overlapping ones + if (level == 0) { + InternalKey smallest, largest; + GetRange(c->inputs_[0], &smallest, &largest); + // Note that the next call will discard the file we placed in + // c->inputs_[0] earlier and replace it with an overlapping set + // which will include the picked file. + current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]); + assert(!c->inputs_[0].empty()); + } + + SetupOtherInputs(c); + + return c; +} + +void VersionSet::SetupOtherInputs(Compaction* c) { + const int level = c->level(); + InternalKey smallest, largest; + GetRange(c->inputs_[0], &smallest, &largest); + + current_->GetOverlappingInputs(level+1, &smallest, &largest, &c->inputs_[1]); + + // Get entire range covered by compaction + InternalKey all_start, all_limit; + GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit); + + // See if we can grow the number of inputs in "level" without + // changing the number of "level+1" files we pick up. + if (!c->inputs_[1].empty()) { + std::vector expanded0; + current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0); + const int64_t inputs0_size = TotalFileSize(c->inputs_[0]); + const int64_t inputs1_size = TotalFileSize(c->inputs_[1]); + const int64_t expanded0_size = TotalFileSize(expanded0); + if (expanded0.size() > c->inputs_[0].size() && + inputs1_size + expanded0_size < + ExpandedCompactionByteSizeLimit(options_)) { + InternalKey new_start, new_limit; + GetRange(expanded0, &new_start, &new_limit); + std::vector expanded1; + current_->GetOverlappingInputs(level+1, &new_start, &new_limit, + &expanded1); + if (expanded1.size() == c->inputs_[1].size()) { + Log(options_->info_log, + "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n", + level, + int(c->inputs_[0].size()), + int(c->inputs_[1].size()), + long(inputs0_size), long(inputs1_size), + int(expanded0.size()), + int(expanded1.size()), + long(expanded0_size), long(inputs1_size)); + smallest = new_start; + largest = new_limit; + c->inputs_[0] = expanded0; + c->inputs_[1] = expanded1; + GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit); + } + } + } + + // Compute the set of grandparent files that overlap this compaction + // (parent == level+1; grandparent == level+2) + if (level + 2 < config::kNumLevels) { + current_->GetOverlappingInputs(level + 2, &all_start, &all_limit, + &c->grandparents_); + } + + if (false) { + Log(options_->info_log, "Compacting %d '%s' .. '%s'", + level, + smallest.DebugString().c_str(), + largest.DebugString().c_str()); + } + + // Update the place where we will do the next compaction for this level. + // We update this immediately instead of waiting for the VersionEdit + // to be applied so that if the compaction fails, we will try a different + // key range next time. + compact_pointer_[level] = largest.Encode().ToString(); + c->edit_.SetCompactPointer(level, largest); +} + +Compaction* VersionSet::CompactRange( + int level, + const InternalKey* begin, + const InternalKey* end) { + std::vector inputs; + current_->GetOverlappingInputs(level, begin, end, &inputs); + if (inputs.empty()) { + return NULL; + } + + // Avoid compacting too much in one shot in case the range is large. + // But we cannot do this for level-0 since level-0 files can overlap + // and we must not pick one file and drop another older file if the + // two files overlap. + if (level > 0) { + const uint64_t limit = MaxFileSizeForLevel(options_, level); + uint64_t total = 0; + for (size_t i = 0; i < inputs.size(); i++) { + uint64_t s = inputs[i]->file_size; + total += s; + if (total >= limit) { + inputs.resize(i + 1); + break; + } + } + } + + Compaction* c = new Compaction(options_, level); + c->input_version_ = current_; + c->input_version_->Ref(); + c->inputs_[0] = inputs; + SetupOtherInputs(c); + return c; +} + +Compaction::Compaction(const Options* options, int level) + : level_(level), + max_output_file_size_(MaxFileSizeForLevel(options, level)), + input_version_(NULL), + grandparent_index_(0), + seen_key_(false), + overlapped_bytes_(0) { + for (int i = 0; i < config::kNumLevels; i++) { + level_ptrs_[i] = 0; + } +} + +Compaction::~Compaction() { + if (input_version_ != NULL) { + input_version_->Unref(); + } +} + +bool Compaction::IsTrivialMove() const { + const VersionSet* vset = input_version_->vset_; + // Avoid a move if there is lots of overlapping grandparent data. + // Otherwise, the move could create a parent file that will require + // a very expensive merge later on. + return (num_input_files(0) == 1 && num_input_files(1) == 0 && + TotalFileSize(grandparents_) <= + MaxGrandParentOverlapBytes(vset->options_)); +} + +void Compaction::AddInputDeletions(VersionEdit* edit) { + for (int which = 0; which < 2; which++) { + for (size_t i = 0; i < inputs_[which].size(); i++) { + edit->DeleteFile(level_ + which, inputs_[which][i]->number); + } + } +} + +bool Compaction::IsBaseLevelForKey(const Slice& user_key) { + // Maybe use binary search to find right entry instead of linear search? + const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator(); + for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) { + const std::vector& files = input_version_->files_[lvl]; + for (; level_ptrs_[lvl] < files.size(); ) { + FileMetaData* f = files[level_ptrs_[lvl]]; + if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) { + // We've advanced far enough + if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) { + // Key falls in this file's range, so definitely not base level + return false; + } + break; + } + level_ptrs_[lvl]++; + } + } + return true; +} + +bool Compaction::ShouldStopBefore(const Slice& internal_key) { + const VersionSet* vset = input_version_->vset_; + // Scan to find earliest grandparent file that contains key. + const InternalKeyComparator* icmp = &vset->icmp_; + while (grandparent_index_ < grandparents_.size() && + icmp->Compare(internal_key, + grandparents_[grandparent_index_]->largest.Encode()) > 0) { + if (seen_key_) { + overlapped_bytes_ += grandparents_[grandparent_index_]->file_size; + } + grandparent_index_++; + } + seen_key_ = true; + + if (overlapped_bytes_ > MaxGrandParentOverlapBytes(vset->options_)) { + // Too much overlap for current output; start new output + overlapped_bytes_ = 0; + return true; + } else { + return false; + } +} + +void Compaction::ReleaseInputs() { + if (input_version_ != NULL) { + input_version_->Unref(); + input_version_ = NULL; + } +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/version_set.h b/My Mind/Pods/leveldb-library/db/version_set.h new file mode 100644 index 0000000..c4e7ac3 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/version_set.h @@ -0,0 +1,398 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// The representation of a DBImpl consists of a set of Versions. The +// newest version is called "current". Older versions may be kept +// around to provide a consistent view to live iterators. +// +// Each Version keeps track of a set of Table files per level. The +// entire set of versions is maintained in a VersionSet. +// +// Version,VersionSet are thread-compatible, but require external +// synchronization on all accesses. + +#ifndef STORAGE_LEVELDB_DB_VERSION_SET_H_ +#define STORAGE_LEVELDB_DB_VERSION_SET_H_ + +#include +#include +#include +#include "db/dbformat.h" +#include "db/version_edit.h" +#include "port/port.h" +#include "port/thread_annotations.h" + +namespace leveldb { + +namespace log { class Writer; } + +class Compaction; +class Iterator; +class MemTable; +class TableBuilder; +class TableCache; +class Version; +class VersionSet; +class WritableFile; + +// Return the smallest index i such that files[i]->largest >= key. +// Return files.size() if there is no such file. +// REQUIRES: "files" contains a sorted list of non-overlapping files. +extern int FindFile(const InternalKeyComparator& icmp, + const std::vector& files, + const Slice& key); + +// Returns true iff some file in "files" overlaps the user key range +// [*smallest,*largest]. +// smallest==NULL represents a key smaller than all keys in the DB. +// largest==NULL represents a key largest than all keys in the DB. +// REQUIRES: If disjoint_sorted_files, files[] contains disjoint ranges +// in sorted order. +extern bool SomeFileOverlapsRange( + const InternalKeyComparator& icmp, + bool disjoint_sorted_files, + const std::vector& files, + const Slice* smallest_user_key, + const Slice* largest_user_key); + +class Version { + public: + // Append to *iters a sequence of iterators that will + // yield the contents of this Version when merged together. + // REQUIRES: This version has been saved (see VersionSet::SaveTo) + void AddIterators(const ReadOptions&, std::vector* iters); + + // Lookup the value for key. If found, store it in *val and + // return OK. Else return a non-OK status. Fills *stats. + // REQUIRES: lock is not held + struct GetStats { + FileMetaData* seek_file; + int seek_file_level; + }; + Status Get(const ReadOptions&, const LookupKey& key, std::string* val, + GetStats* stats); + + // Adds "stats" into the current state. Returns true if a new + // compaction may need to be triggered, false otherwise. + // REQUIRES: lock is held + bool UpdateStats(const GetStats& stats); + + // Record a sample of bytes read at the specified internal key. + // Samples are taken approximately once every config::kReadBytesPeriod + // bytes. Returns true if a new compaction may need to be triggered. + // REQUIRES: lock is held + bool RecordReadSample(Slice key); + + // Reference count management (so Versions do not disappear out from + // under live iterators) + void Ref(); + void Unref(); + + void GetOverlappingInputs( + int level, + const InternalKey* begin, // NULL means before all keys + const InternalKey* end, // NULL means after all keys + std::vector* inputs); + + // Returns true iff some file in the specified level overlaps + // some part of [*smallest_user_key,*largest_user_key]. + // smallest_user_key==NULL represents a key smaller than all keys in the DB. + // largest_user_key==NULL represents a key largest than all keys in the DB. + bool OverlapInLevel(int level, + const Slice* smallest_user_key, + const Slice* largest_user_key); + + // Return the level at which we should place a new memtable compaction + // result that covers the range [smallest_user_key,largest_user_key]. + int PickLevelForMemTableOutput(const Slice& smallest_user_key, + const Slice& largest_user_key); + + int NumFiles(int level) const { return files_[level].size(); } + + // Return a human readable string that describes this version's contents. + std::string DebugString() const; + + private: + friend class Compaction; + friend class VersionSet; + + class LevelFileNumIterator; + Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const; + + // Call func(arg, level, f) for every file that overlaps user_key in + // order from newest to oldest. If an invocation of func returns + // false, makes no more calls. + // + // REQUIRES: user portion of internal_key == user_key. + void ForEachOverlapping(Slice user_key, Slice internal_key, + void* arg, + bool (*func)(void*, int, FileMetaData*)); + + VersionSet* vset_; // VersionSet to which this Version belongs + Version* next_; // Next version in linked list + Version* prev_; // Previous version in linked list + int refs_; // Number of live refs to this version + + // List of files per level + std::vector files_[config::kNumLevels]; + + // Next file to compact based on seek stats. + FileMetaData* file_to_compact_; + int file_to_compact_level_; + + // Level that should be compacted next and its compaction score. + // Score < 1 means compaction is not strictly needed. These fields + // are initialized by Finalize(). + double compaction_score_; + int compaction_level_; + + explicit Version(VersionSet* vset) + : vset_(vset), next_(this), prev_(this), refs_(0), + file_to_compact_(NULL), + file_to_compact_level_(-1), + compaction_score_(-1), + compaction_level_(-1) { + } + + ~Version(); + + // No copying allowed + Version(const Version&); + void operator=(const Version&); +}; + +class VersionSet { + public: + VersionSet(const std::string& dbname, + const Options* options, + TableCache* table_cache, + const InternalKeyComparator*); + ~VersionSet(); + + // Apply *edit to the current version to form a new descriptor that + // is both saved to persistent state and installed as the new + // current version. Will release *mu while actually writing to the file. + // REQUIRES: *mu is held on entry. + // REQUIRES: no other thread concurrently calls LogAndApply() + Status LogAndApply(VersionEdit* edit, port::Mutex* mu) + EXCLUSIVE_LOCKS_REQUIRED(mu); + + // Recover the last saved descriptor from persistent storage. + Status Recover(bool *save_manifest); + + // Return the current version. + Version* current() const { return current_; } + + // Return the current manifest file number + uint64_t ManifestFileNumber() const { return manifest_file_number_; } + + // Allocate and return a new file number + uint64_t NewFileNumber() { return next_file_number_++; } + + // Arrange to reuse "file_number" unless a newer file number has + // already been allocated. + // REQUIRES: "file_number" was returned by a call to NewFileNumber(). + void ReuseFileNumber(uint64_t file_number) { + if (next_file_number_ == file_number + 1) { + next_file_number_ = file_number; + } + } + + // Return the number of Table files at the specified level. + int NumLevelFiles(int level) const; + + // Return the combined file size of all files at the specified level. + int64_t NumLevelBytes(int level) const; + + // Return the last sequence number. + uint64_t LastSequence() const { return last_sequence_; } + + // Set the last sequence number to s. + void SetLastSequence(uint64_t s) { + assert(s >= last_sequence_); + last_sequence_ = s; + } + + // Mark the specified file number as used. + void MarkFileNumberUsed(uint64_t number); + + // Return the current log file number. + uint64_t LogNumber() const { return log_number_; } + + // Return the log file number for the log file that is currently + // being compacted, or zero if there is no such log file. + uint64_t PrevLogNumber() const { return prev_log_number_; } + + // Pick level and inputs for a new compaction. + // Returns NULL if there is no compaction to be done. + // Otherwise returns a pointer to a heap-allocated object that + // describes the compaction. Caller should delete the result. + Compaction* PickCompaction(); + + // Return a compaction object for compacting the range [begin,end] in + // the specified level. Returns NULL if there is nothing in that + // level that overlaps the specified range. Caller should delete + // the result. + Compaction* CompactRange( + int level, + const InternalKey* begin, + const InternalKey* end); + + // Return the maximum overlapping data (in bytes) at next level for any + // file at a level >= 1. + int64_t MaxNextLevelOverlappingBytes(); + + // Create an iterator that reads over the compaction inputs for "*c". + // The caller should delete the iterator when no longer needed. + Iterator* MakeInputIterator(Compaction* c); + + // Returns true iff some level needs a compaction. + bool NeedsCompaction() const { + Version* v = current_; + return (v->compaction_score_ >= 1) || (v->file_to_compact_ != NULL); + } + + // Add all files listed in any live version to *live. + // May also mutate some internal state. + void AddLiveFiles(std::set* live); + + // Return the approximate offset in the database of the data for + // "key" as of version "v". + uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key); + + // Return a human-readable short (single-line) summary of the number + // of files per level. Uses *scratch as backing store. + struct LevelSummaryStorage { + char buffer[100]; + }; + const char* LevelSummary(LevelSummaryStorage* scratch) const; + + private: + class Builder; + + friend class Compaction; + friend class Version; + + bool ReuseManifest(const std::string& dscname, const std::string& dscbase); + + void Finalize(Version* v); + + void GetRange(const std::vector& inputs, + InternalKey* smallest, + InternalKey* largest); + + void GetRange2(const std::vector& inputs1, + const std::vector& inputs2, + InternalKey* smallest, + InternalKey* largest); + + void SetupOtherInputs(Compaction* c); + + // Save current contents to *log + Status WriteSnapshot(log::Writer* log); + + void AppendVersion(Version* v); + + Env* const env_; + const std::string dbname_; + const Options* const options_; + TableCache* const table_cache_; + const InternalKeyComparator icmp_; + uint64_t next_file_number_; + uint64_t manifest_file_number_; + uint64_t last_sequence_; + uint64_t log_number_; + uint64_t prev_log_number_; // 0 or backing store for memtable being compacted + + // Opened lazily + WritableFile* descriptor_file_; + log::Writer* descriptor_log_; + Version dummy_versions_; // Head of circular doubly-linked list of versions. + Version* current_; // == dummy_versions_.prev_ + + // Per-level key at which the next compaction at that level should start. + // Either an empty string, or a valid InternalKey. + std::string compact_pointer_[config::kNumLevels]; + + // No copying allowed + VersionSet(const VersionSet&); + void operator=(const VersionSet&); +}; + +// A Compaction encapsulates information about a compaction. +class Compaction { + public: + ~Compaction(); + + // Return the level that is being compacted. Inputs from "level" + // and "level+1" will be merged to produce a set of "level+1" files. + int level() const { return level_; } + + // Return the object that holds the edits to the descriptor done + // by this compaction. + VersionEdit* edit() { return &edit_; } + + // "which" must be either 0 or 1 + int num_input_files(int which) const { return inputs_[which].size(); } + + // Return the ith input file at "level()+which" ("which" must be 0 or 1). + FileMetaData* input(int which, int i) const { return inputs_[which][i]; } + + // Maximum size of files to build during this compaction. + uint64_t MaxOutputFileSize() const { return max_output_file_size_; } + + // Is this a trivial compaction that can be implemented by just + // moving a single input file to the next level (no merging or splitting) + bool IsTrivialMove() const; + + // Add all inputs to this compaction as delete operations to *edit. + void AddInputDeletions(VersionEdit* edit); + + // Returns true if the information we have available guarantees that + // the compaction is producing data in "level+1" for which no data exists + // in levels greater than "level+1". + bool IsBaseLevelForKey(const Slice& user_key); + + // Returns true iff we should stop building the current output + // before processing "internal_key". + bool ShouldStopBefore(const Slice& internal_key); + + // Release the input version for the compaction, once the compaction + // is successful. + void ReleaseInputs(); + + private: + friend class Version; + friend class VersionSet; + + Compaction(const Options* options, int level); + + int level_; + uint64_t max_output_file_size_; + Version* input_version_; + VersionEdit edit_; + + // Each compaction reads inputs from "level_" and "level_+1" + std::vector inputs_[2]; // The two sets of inputs + + // State used to check for number of of overlapping grandparent files + // (parent == level_ + 1, grandparent == level_ + 2) + std::vector grandparents_; + size_t grandparent_index_; // Index in grandparent_starts_ + bool seen_key_; // Some output key has been seen + int64_t overlapped_bytes_; // Bytes of overlap between current output + // and grandparent files + + // State for implementing IsBaseLevelForKey + + // level_ptrs_ holds indices into input_version_->levels_: our state + // is that we are positioned at one of the file ranges for each + // higher level than the ones involved in this compaction (i.e. for + // all L >= level_ + 2). + size_t level_ptrs_[config::kNumLevels]; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_DB_VERSION_SET_H_ diff --git a/My Mind/Pods/leveldb-library/db/write_batch.cc b/My Mind/Pods/leveldb-library/db/write_batch.cc new file mode 100644 index 0000000..33f4a42 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/write_batch.cc @@ -0,0 +1,147 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// WriteBatch::rep_ := +// sequence: fixed64 +// count: fixed32 +// data: record[count] +// record := +// kTypeValue varstring varstring | +// kTypeDeletion varstring +// varstring := +// len: varint32 +// data: uint8[len] + +#include "leveldb/write_batch.h" + +#include "leveldb/db.h" +#include "db/dbformat.h" +#include "db/memtable.h" +#include "db/write_batch_internal.h" +#include "util/coding.h" + +namespace leveldb { + +// WriteBatch header has an 8-byte sequence number followed by a 4-byte count. +static const size_t kHeader = 12; + +WriteBatch::WriteBatch() { + Clear(); +} + +WriteBatch::~WriteBatch() { } + +WriteBatch::Handler::~Handler() { } + +void WriteBatch::Clear() { + rep_.clear(); + rep_.resize(kHeader); +} + +Status WriteBatch::Iterate(Handler* handler) const { + Slice input(rep_); + if (input.size() < kHeader) { + return Status::Corruption("malformed WriteBatch (too small)"); + } + + input.remove_prefix(kHeader); + Slice key, value; + int found = 0; + while (!input.empty()) { + found++; + char tag = input[0]; + input.remove_prefix(1); + switch (tag) { + case kTypeValue: + if (GetLengthPrefixedSlice(&input, &key) && + GetLengthPrefixedSlice(&input, &value)) { + handler->Put(key, value); + } else { + return Status::Corruption("bad WriteBatch Put"); + } + break; + case kTypeDeletion: + if (GetLengthPrefixedSlice(&input, &key)) { + handler->Delete(key); + } else { + return Status::Corruption("bad WriteBatch Delete"); + } + break; + default: + return Status::Corruption("unknown WriteBatch tag"); + } + } + if (found != WriteBatchInternal::Count(this)) { + return Status::Corruption("WriteBatch has wrong count"); + } else { + return Status::OK(); + } +} + +int WriteBatchInternal::Count(const WriteBatch* b) { + return DecodeFixed32(b->rep_.data() + 8); +} + +void WriteBatchInternal::SetCount(WriteBatch* b, int n) { + EncodeFixed32(&b->rep_[8], n); +} + +SequenceNumber WriteBatchInternal::Sequence(const WriteBatch* b) { + return SequenceNumber(DecodeFixed64(b->rep_.data())); +} + +void WriteBatchInternal::SetSequence(WriteBatch* b, SequenceNumber seq) { + EncodeFixed64(&b->rep_[0], seq); +} + +void WriteBatch::Put(const Slice& key, const Slice& value) { + WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1); + rep_.push_back(static_cast(kTypeValue)); + PutLengthPrefixedSlice(&rep_, key); + PutLengthPrefixedSlice(&rep_, value); +} + +void WriteBatch::Delete(const Slice& key) { + WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1); + rep_.push_back(static_cast(kTypeDeletion)); + PutLengthPrefixedSlice(&rep_, key); +} + +namespace { +class MemTableInserter : public WriteBatch::Handler { + public: + SequenceNumber sequence_; + MemTable* mem_; + + virtual void Put(const Slice& key, const Slice& value) { + mem_->Add(sequence_, kTypeValue, key, value); + sequence_++; + } + virtual void Delete(const Slice& key) { + mem_->Add(sequence_, kTypeDeletion, key, Slice()); + sequence_++; + } +}; +} // namespace + +Status WriteBatchInternal::InsertInto(const WriteBatch* b, + MemTable* memtable) { + MemTableInserter inserter; + inserter.sequence_ = WriteBatchInternal::Sequence(b); + inserter.mem_ = memtable; + return b->Iterate(&inserter); +} + +void WriteBatchInternal::SetContents(WriteBatch* b, const Slice& contents) { + assert(contents.size() >= kHeader); + b->rep_.assign(contents.data(), contents.size()); +} + +void WriteBatchInternal::Append(WriteBatch* dst, const WriteBatch* src) { + SetCount(dst, Count(dst) + Count(src)); + assert(src->rep_.size() >= kHeader); + dst->rep_.append(src->rep_.data() + kHeader, src->rep_.size() - kHeader); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/db/write_batch_internal.h b/My Mind/Pods/leveldb-library/db/write_batch_internal.h new file mode 100644 index 0000000..9448ef7 --- /dev/null +++ b/My Mind/Pods/leveldb-library/db/write_batch_internal.h @@ -0,0 +1,50 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_DB_WRITE_BATCH_INTERNAL_H_ +#define STORAGE_LEVELDB_DB_WRITE_BATCH_INTERNAL_H_ + +#include "db/dbformat.h" +#include "leveldb/write_batch.h" + +namespace leveldb { + +class MemTable; + +// WriteBatchInternal provides static methods for manipulating a +// WriteBatch that we don't want in the public WriteBatch interface. +class WriteBatchInternal { + public: + // Return the number of entries in the batch. + static int Count(const WriteBatch* batch); + + // Set the count for the number of entries in the batch. + static void SetCount(WriteBatch* batch, int n); + + // Return the sequence number for the start of this batch. + static SequenceNumber Sequence(const WriteBatch* batch); + + // Store the specified number as the sequence number for the start of + // this batch. + static void SetSequence(WriteBatch* batch, SequenceNumber seq); + + static Slice Contents(const WriteBatch* batch) { + return Slice(batch->rep_); + } + + static size_t ByteSize(const WriteBatch* batch) { + return batch->rep_.size(); + } + + static void SetContents(WriteBatch* batch, const Slice& contents); + + static Status InsertInto(const WriteBatch* batch, MemTable* memtable); + + static void Append(WriteBatch* dst, const WriteBatch* src); +}; + +} // namespace leveldb + + +#endif // STORAGE_LEVELDB_DB_WRITE_BATCH_INTERNAL_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/c.h b/My Mind/Pods/leveldb-library/include/leveldb/c.h new file mode 100644 index 0000000..1048fe3 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/c.h @@ -0,0 +1,290 @@ +/* Copyright (c) 2011 The LevelDB Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. See the AUTHORS file for names of contributors. + + C bindings for leveldb. May be useful as a stable ABI that can be + used by programs that keep leveldb in a shared library, or for + a JNI api. + + Does not support: + . getters for the option types + . custom comparators that implement key shortening + . custom iter, db, env, cache implementations using just the C bindings + + Some conventions: + + (1) We expose just opaque struct pointers and functions to clients. + This allows us to change internal representations without having to + recompile clients. + + (2) For simplicity, there is no equivalent to the Slice type. Instead, + the caller has to pass the pointer and length as separate + arguments. + + (3) Errors are represented by a null-terminated c string. NULL + means no error. All operations that can raise an error are passed + a "char** errptr" as the last argument. One of the following must + be true on entry: + *errptr == NULL + *errptr points to a malloc()ed null-terminated error message + (On Windows, *errptr must have been malloc()-ed by this library.) + On success, a leveldb routine leaves *errptr unchanged. + On failure, leveldb frees the old value of *errptr and + set *errptr to a malloc()ed error message. + + (4) Bools have the type unsigned char (0 == false; rest == true) + + (5) All of the pointer arguments must be non-NULL. +*/ + +#ifndef STORAGE_LEVELDB_INCLUDE_C_H_ +#define STORAGE_LEVELDB_INCLUDE_C_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +/* Exported types */ + +typedef struct leveldb_t leveldb_t; +typedef struct leveldb_cache_t leveldb_cache_t; +typedef struct leveldb_comparator_t leveldb_comparator_t; +typedef struct leveldb_env_t leveldb_env_t; +typedef struct leveldb_filelock_t leveldb_filelock_t; +typedef struct leveldb_filterpolicy_t leveldb_filterpolicy_t; +typedef struct leveldb_iterator_t leveldb_iterator_t; +typedef struct leveldb_logger_t leveldb_logger_t; +typedef struct leveldb_options_t leveldb_options_t; +typedef struct leveldb_randomfile_t leveldb_randomfile_t; +typedef struct leveldb_readoptions_t leveldb_readoptions_t; +typedef struct leveldb_seqfile_t leveldb_seqfile_t; +typedef struct leveldb_snapshot_t leveldb_snapshot_t; +typedef struct leveldb_writablefile_t leveldb_writablefile_t; +typedef struct leveldb_writebatch_t leveldb_writebatch_t; +typedef struct leveldb_writeoptions_t leveldb_writeoptions_t; + +/* DB operations */ + +extern leveldb_t* leveldb_open( + const leveldb_options_t* options, + const char* name, + char** errptr); + +extern void leveldb_close(leveldb_t* db); + +extern void leveldb_put( + leveldb_t* db, + const leveldb_writeoptions_t* options, + const char* key, size_t keylen, + const char* val, size_t vallen, + char** errptr); + +extern void leveldb_delete( + leveldb_t* db, + const leveldb_writeoptions_t* options, + const char* key, size_t keylen, + char** errptr); + +extern void leveldb_write( + leveldb_t* db, + const leveldb_writeoptions_t* options, + leveldb_writebatch_t* batch, + char** errptr); + +/* Returns NULL if not found. A malloc()ed array otherwise. + Stores the length of the array in *vallen. */ +extern char* leveldb_get( + leveldb_t* db, + const leveldb_readoptions_t* options, + const char* key, size_t keylen, + size_t* vallen, + char** errptr); + +extern leveldb_iterator_t* leveldb_create_iterator( + leveldb_t* db, + const leveldb_readoptions_t* options); + +extern const leveldb_snapshot_t* leveldb_create_snapshot( + leveldb_t* db); + +extern void leveldb_release_snapshot( + leveldb_t* db, + const leveldb_snapshot_t* snapshot); + +/* Returns NULL if property name is unknown. + Else returns a pointer to a malloc()-ed null-terminated value. */ +extern char* leveldb_property_value( + leveldb_t* db, + const char* propname); + +extern void leveldb_approximate_sizes( + leveldb_t* db, + int num_ranges, + const char* const* range_start_key, const size_t* range_start_key_len, + const char* const* range_limit_key, const size_t* range_limit_key_len, + uint64_t* sizes); + +extern void leveldb_compact_range( + leveldb_t* db, + const char* start_key, size_t start_key_len, + const char* limit_key, size_t limit_key_len); + +/* Management operations */ + +extern void leveldb_destroy_db( + const leveldb_options_t* options, + const char* name, + char** errptr); + +extern void leveldb_repair_db( + const leveldb_options_t* options, + const char* name, + char** errptr); + +/* Iterator */ + +extern void leveldb_iter_destroy(leveldb_iterator_t*); +extern unsigned char leveldb_iter_valid(const leveldb_iterator_t*); +extern void leveldb_iter_seek_to_first(leveldb_iterator_t*); +extern void leveldb_iter_seek_to_last(leveldb_iterator_t*); +extern void leveldb_iter_seek(leveldb_iterator_t*, const char* k, size_t klen); +extern void leveldb_iter_next(leveldb_iterator_t*); +extern void leveldb_iter_prev(leveldb_iterator_t*); +extern const char* leveldb_iter_key(const leveldb_iterator_t*, size_t* klen); +extern const char* leveldb_iter_value(const leveldb_iterator_t*, size_t* vlen); +extern void leveldb_iter_get_error(const leveldb_iterator_t*, char** errptr); + +/* Write batch */ + +extern leveldb_writebatch_t* leveldb_writebatch_create(); +extern void leveldb_writebatch_destroy(leveldb_writebatch_t*); +extern void leveldb_writebatch_clear(leveldb_writebatch_t*); +extern void leveldb_writebatch_put( + leveldb_writebatch_t*, + const char* key, size_t klen, + const char* val, size_t vlen); +extern void leveldb_writebatch_delete( + leveldb_writebatch_t*, + const char* key, size_t klen); +extern void leveldb_writebatch_iterate( + leveldb_writebatch_t*, + void* state, + void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), + void (*deleted)(void*, const char* k, size_t klen)); + +/* Options */ + +extern leveldb_options_t* leveldb_options_create(); +extern void leveldb_options_destroy(leveldb_options_t*); +extern void leveldb_options_set_comparator( + leveldb_options_t*, + leveldb_comparator_t*); +extern void leveldb_options_set_filter_policy( + leveldb_options_t*, + leveldb_filterpolicy_t*); +extern void leveldb_options_set_create_if_missing( + leveldb_options_t*, unsigned char); +extern void leveldb_options_set_error_if_exists( + leveldb_options_t*, unsigned char); +extern void leveldb_options_set_paranoid_checks( + leveldb_options_t*, unsigned char); +extern void leveldb_options_set_env(leveldb_options_t*, leveldb_env_t*); +extern void leveldb_options_set_info_log(leveldb_options_t*, leveldb_logger_t*); +extern void leveldb_options_set_write_buffer_size(leveldb_options_t*, size_t); +extern void leveldb_options_set_max_open_files(leveldb_options_t*, int); +extern void leveldb_options_set_cache(leveldb_options_t*, leveldb_cache_t*); +extern void leveldb_options_set_block_size(leveldb_options_t*, size_t); +extern void leveldb_options_set_block_restart_interval(leveldb_options_t*, int); + +enum { + leveldb_no_compression = 0, + leveldb_snappy_compression = 1 +}; +extern void leveldb_options_set_compression(leveldb_options_t*, int); + +/* Comparator */ + +extern leveldb_comparator_t* leveldb_comparator_create( + void* state, + void (*destructor)(void*), + int (*compare)( + void*, + const char* a, size_t alen, + const char* b, size_t blen), + const char* (*name)(void*)); +extern void leveldb_comparator_destroy(leveldb_comparator_t*); + +/* Filter policy */ + +extern leveldb_filterpolicy_t* leveldb_filterpolicy_create( + void* state, + void (*destructor)(void*), + char* (*create_filter)( + void*, + const char* const* key_array, const size_t* key_length_array, + int num_keys, + size_t* filter_length), + unsigned char (*key_may_match)( + void*, + const char* key, size_t length, + const char* filter, size_t filter_length), + const char* (*name)(void*)); +extern void leveldb_filterpolicy_destroy(leveldb_filterpolicy_t*); + +extern leveldb_filterpolicy_t* leveldb_filterpolicy_create_bloom( + int bits_per_key); + +/* Read options */ + +extern leveldb_readoptions_t* leveldb_readoptions_create(); +extern void leveldb_readoptions_destroy(leveldb_readoptions_t*); +extern void leveldb_readoptions_set_verify_checksums( + leveldb_readoptions_t*, + unsigned char); +extern void leveldb_readoptions_set_fill_cache( + leveldb_readoptions_t*, unsigned char); +extern void leveldb_readoptions_set_snapshot( + leveldb_readoptions_t*, + const leveldb_snapshot_t*); + +/* Write options */ + +extern leveldb_writeoptions_t* leveldb_writeoptions_create(); +extern void leveldb_writeoptions_destroy(leveldb_writeoptions_t*); +extern void leveldb_writeoptions_set_sync( + leveldb_writeoptions_t*, unsigned char); + +/* Cache */ + +extern leveldb_cache_t* leveldb_cache_create_lru(size_t capacity); +extern void leveldb_cache_destroy(leveldb_cache_t* cache); + +/* Env */ + +extern leveldb_env_t* leveldb_create_default_env(); +extern void leveldb_env_destroy(leveldb_env_t*); + +/* Utility */ + +/* Calls free(ptr). + REQUIRES: ptr was malloc()-ed and returned by one of the routines + in this file. Note that in certain cases (typically on Windows), you + may need to call this routine instead of free(ptr) to dispose of + malloc()-ed memory returned by this library. */ +extern void leveldb_free(void* ptr); + +/* Return the major version number for this release. */ +extern int leveldb_major_version(); + +/* Return the minor version number for this release. */ +extern int leveldb_minor_version(); + +#ifdef __cplusplus +} /* end extern "C" */ +#endif + +#endif /* STORAGE_LEVELDB_INCLUDE_C_H_ */ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/cache.h b/My Mind/Pods/leveldb-library/include/leveldb/cache.h new file mode 100644 index 0000000..6819d5b --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/cache.h @@ -0,0 +1,110 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A Cache is an interface that maps keys to values. It has internal +// synchronization and may be safely accessed concurrently from +// multiple threads. It may automatically evict entries to make room +// for new entries. Values have a specified charge against the cache +// capacity. For example, a cache where the values are variable +// length strings, may use the length of the string as the charge for +// the string. +// +// A builtin cache implementation with a least-recently-used eviction +// policy is provided. Clients may use their own implementations if +// they want something more sophisticated (like scan-resistance, a +// custom eviction policy, variable cache sizing, etc.) + +#ifndef STORAGE_LEVELDB_INCLUDE_CACHE_H_ +#define STORAGE_LEVELDB_INCLUDE_CACHE_H_ + +#include +#include "leveldb/slice.h" + +namespace leveldb { + +class Cache; + +// Create a new cache with a fixed size capacity. This implementation +// of Cache uses a least-recently-used eviction policy. +extern Cache* NewLRUCache(size_t capacity); + +class Cache { + public: + Cache() { } + + // Destroys all existing entries by calling the "deleter" + // function that was passed to the constructor. + virtual ~Cache(); + + // Opaque handle to an entry stored in the cache. + struct Handle { }; + + // Insert a mapping from key->value into the cache and assign it + // the specified charge against the total cache capacity. + // + // Returns a handle that corresponds to the mapping. The caller + // must call this->Release(handle) when the returned mapping is no + // longer needed. + // + // When the inserted entry is no longer needed, the key and + // value will be passed to "deleter". + virtual Handle* Insert(const Slice& key, void* value, size_t charge, + void (*deleter)(const Slice& key, void* value)) = 0; + + // If the cache has no mapping for "key", returns NULL. + // + // Else return a handle that corresponds to the mapping. The caller + // must call this->Release(handle) when the returned mapping is no + // longer needed. + virtual Handle* Lookup(const Slice& key) = 0; + + // Release a mapping returned by a previous Lookup(). + // REQUIRES: handle must not have been released yet. + // REQUIRES: handle must have been returned by a method on *this. + virtual void Release(Handle* handle) = 0; + + // Return the value encapsulated in a handle returned by a + // successful Lookup(). + // REQUIRES: handle must not have been released yet. + // REQUIRES: handle must have been returned by a method on *this. + virtual void* Value(Handle* handle) = 0; + + // If the cache contains entry for key, erase it. Note that the + // underlying entry will be kept around until all existing handles + // to it have been released. + virtual void Erase(const Slice& key) = 0; + + // Return a new numeric id. May be used by multiple clients who are + // sharing the same cache to partition the key space. Typically the + // client will allocate a new id at startup and prepend the id to + // its cache keys. + virtual uint64_t NewId() = 0; + + // Remove all cache entries that are not actively in use. Memory-constrained + // applications may wish to call this method to reduce memory usage. + // Default implementation of Prune() does nothing. Subclasses are strongly + // encouraged to override the default implementation. A future release of + // leveldb may change Prune() to a pure abstract method. + virtual void Prune() {} + + // Return an estimate of the combined charges of all elements stored in the + // cache. + virtual size_t TotalCharge() const = 0; + + private: + void LRU_Remove(Handle* e); + void LRU_Append(Handle* e); + void Unref(Handle* e); + + struct Rep; + Rep* rep_; + + // No copying allowed + Cache(const Cache&); + void operator=(const Cache&); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_CACHE_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/comparator.h b/My Mind/Pods/leveldb-library/include/leveldb/comparator.h new file mode 100644 index 0000000..556b984 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/comparator.h @@ -0,0 +1,63 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_ +#define STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_ + +#include + +namespace leveldb { + +class Slice; + +// A Comparator object provides a total order across slices that are +// used as keys in an sstable or a database. A Comparator implementation +// must be thread-safe since leveldb may invoke its methods concurrently +// from multiple threads. +class Comparator { + public: + virtual ~Comparator(); + + // Three-way comparison. Returns value: + // < 0 iff "a" < "b", + // == 0 iff "a" == "b", + // > 0 iff "a" > "b" + virtual int Compare(const Slice& a, const Slice& b) const = 0; + + // The name of the comparator. Used to check for comparator + // mismatches (i.e., a DB created with one comparator is + // accessed using a different comparator. + // + // The client of this package should switch to a new name whenever + // the comparator implementation changes in a way that will cause + // the relative ordering of any two keys to change. + // + // Names starting with "leveldb." are reserved and should not be used + // by any clients of this package. + virtual const char* Name() const = 0; + + // Advanced functions: these are used to reduce the space requirements + // for internal data structures like index blocks. + + // If *start < limit, changes *start to a short string in [start,limit). + // Simple comparator implementations may return with *start unchanged, + // i.e., an implementation of this method that does nothing is correct. + virtual void FindShortestSeparator( + std::string* start, + const Slice& limit) const = 0; + + // Changes *key to a short string >= *key. + // Simple comparator implementations may return with *key unchanged, + // i.e., an implementation of this method that does nothing is correct. + virtual void FindShortSuccessor(std::string* key) const = 0; +}; + +// Return a builtin comparator that uses lexicographic byte-wise +// ordering. The result remains the property of this module and +// must not be deleted. +extern const Comparator* BytewiseComparator(); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/db.h b/My Mind/Pods/leveldb-library/include/leveldb/db.h new file mode 100644 index 0000000..bfab10a --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/db.h @@ -0,0 +1,163 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_INCLUDE_DB_H_ +#define STORAGE_LEVELDB_INCLUDE_DB_H_ + +#include +#include +#include "leveldb/iterator.h" +#include "leveldb/options.h" + +namespace leveldb { + +// Update Makefile if you change these +static const int kMajorVersion = 1; +static const int kMinorVersion = 20; + +struct Options; +struct ReadOptions; +struct WriteOptions; +class WriteBatch; + +// Abstract handle to particular state of a DB. +// A Snapshot is an immutable object and can therefore be safely +// accessed from multiple threads without any external synchronization. +class Snapshot { + protected: + virtual ~Snapshot(); +}; + +// A range of keys +struct Range { + Slice start; // Included in the range + Slice limit; // Not included in the range + + Range() { } + Range(const Slice& s, const Slice& l) : start(s), limit(l) { } +}; + +// A DB is a persistent ordered map from keys to values. +// A DB is safe for concurrent access from multiple threads without +// any external synchronization. +class DB { + public: + // Open the database with the specified "name". + // Stores a pointer to a heap-allocated database in *dbptr and returns + // OK on success. + // Stores NULL in *dbptr and returns a non-OK status on error. + // Caller should delete *dbptr when it is no longer needed. + static Status Open(const Options& options, + const std::string& name, + DB** dbptr); + + DB() { } + virtual ~DB(); + + // Set the database entry for "key" to "value". Returns OK on success, + // and a non-OK status on error. + // Note: consider setting options.sync = true. + virtual Status Put(const WriteOptions& options, + const Slice& key, + const Slice& value) = 0; + + // Remove the database entry (if any) for "key". Returns OK on + // success, and a non-OK status on error. It is not an error if "key" + // did not exist in the database. + // Note: consider setting options.sync = true. + virtual Status Delete(const WriteOptions& options, const Slice& key) = 0; + + // Apply the specified updates to the database. + // Returns OK on success, non-OK on failure. + // Note: consider setting options.sync = true. + virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0; + + // If the database contains an entry for "key" store the + // corresponding value in *value and return OK. + // + // If there is no entry for "key" leave *value unchanged and return + // a status for which Status::IsNotFound() returns true. + // + // May return some other Status on an error. + virtual Status Get(const ReadOptions& options, + const Slice& key, std::string* value) = 0; + + // Return a heap-allocated iterator over the contents of the database. + // The result of NewIterator() is initially invalid (caller must + // call one of the Seek methods on the iterator before using it). + // + // Caller should delete the iterator when it is no longer needed. + // The returned iterator should be deleted before this db is deleted. + virtual Iterator* NewIterator(const ReadOptions& options) = 0; + + // Return a handle to the current DB state. Iterators created with + // this handle will all observe a stable snapshot of the current DB + // state. The caller must call ReleaseSnapshot(result) when the + // snapshot is no longer needed. + virtual const Snapshot* GetSnapshot() = 0; + + // Release a previously acquired snapshot. The caller must not + // use "snapshot" after this call. + virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0; + + // DB implementations can export properties about their state + // via this method. If "property" is a valid property understood by this + // DB implementation, fills "*value" with its current value and returns + // true. Otherwise returns false. + // + // + // Valid property names include: + // + // "leveldb.num-files-at-level" - return the number of files at level , + // where is an ASCII representation of a level number (e.g. "0"). + // "leveldb.stats" - returns a multi-line string that describes statistics + // about the internal operation of the DB. + // "leveldb.sstables" - returns a multi-line string that describes all + // of the sstables that make up the db contents. + // "leveldb.approximate-memory-usage" - returns the approximate number of + // bytes of memory in use by the DB. + virtual bool GetProperty(const Slice& property, std::string* value) = 0; + + // For each i in [0,n-1], store in "sizes[i]", the approximate + // file system space used by keys in "[range[i].start .. range[i].limit)". + // + // Note that the returned sizes measure file system space usage, so + // if the user data compresses by a factor of ten, the returned + // sizes will be one-tenth the size of the corresponding user data size. + // + // The results may not include the sizes of recently written data. + virtual void GetApproximateSizes(const Range* range, int n, + uint64_t* sizes) = 0; + + // Compact the underlying storage for the key range [*begin,*end]. + // In particular, deleted and overwritten versions are discarded, + // and the data is rearranged to reduce the cost of operations + // needed to access the data. This operation should typically only + // be invoked by users who understand the underlying implementation. + // + // begin==NULL is treated as a key before all keys in the database. + // end==NULL is treated as a key after all keys in the database. + // Therefore the following call will compact the entire database: + // db->CompactRange(NULL, NULL); + virtual void CompactRange(const Slice* begin, const Slice* end) = 0; + + private: + // No copying allowed + DB(const DB&); + void operator=(const DB&); +}; + +// Destroy the contents of the specified database. +// Be very careful using this method. +Status DestroyDB(const std::string& name, const Options& options); + +// If a DB cannot be opened, you may attempt to call this method to +// resurrect as much of the contents of the database as possible. +// Some data may be lost, so be careful when calling this function +// on a database that contains important information. +Status RepairDB(const std::string& dbname, const Options& options); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_DB_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/dumpfile.h b/My Mind/Pods/leveldb-library/include/leveldb/dumpfile.h new file mode 100644 index 0000000..3f97fda --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/dumpfile.h @@ -0,0 +1,25 @@ +// Copyright (c) 2014 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_INCLUDE_DUMPFILE_H_ +#define STORAGE_LEVELDB_INCLUDE_DUMPFILE_H_ + +#include +#include "leveldb/env.h" +#include "leveldb/status.h" + +namespace leveldb { + +// Dump the contents of the file named by fname in text format to +// *dst. Makes a sequence of dst->Append() calls; each call is passed +// the newline-terminated text corresponding to a single item found +// in the file. +// +// Returns a non-OK result if fname does not name a leveldb storage +// file, or if the file cannot be read. +Status DumpFile(Env* env, const std::string& fname, WritableFile* dst); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_DUMPFILE_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/env.h b/My Mind/Pods/leveldb-library/include/leveldb/env.h new file mode 100644 index 0000000..99b6c21 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/env.h @@ -0,0 +1,351 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// An Env is an interface used by the leveldb implementation to access +// operating system functionality like the filesystem etc. Callers +// may wish to provide a custom Env object when opening a database to +// get fine gain control; e.g., to rate limit file system operations. +// +// All Env implementations are safe for concurrent access from +// multiple threads without any external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_ENV_H_ +#define STORAGE_LEVELDB_INCLUDE_ENV_H_ + +#include +#include +#include +#include +#include "leveldb/status.h" + +namespace leveldb { + +class FileLock; +class Logger; +class RandomAccessFile; +class SequentialFile; +class Slice; +class WritableFile; + +class Env { + public: + Env() { } + virtual ~Env(); + + // Return a default environment suitable for the current operating + // system. Sophisticated users may wish to provide their own Env + // implementation instead of relying on this default environment. + // + // The result of Default() belongs to leveldb and must never be deleted. + static Env* Default(); + + // Create a brand new sequentially-readable file with the specified name. + // On success, stores a pointer to the new file in *result and returns OK. + // On failure stores NULL in *result and returns non-OK. If the file does + // not exist, returns a non-OK status. + // + // The returned file will only be accessed by one thread at a time. + virtual Status NewSequentialFile(const std::string& fname, + SequentialFile** result) = 0; + + // Create a brand new random access read-only file with the + // specified name. On success, stores a pointer to the new file in + // *result and returns OK. On failure stores NULL in *result and + // returns non-OK. If the file does not exist, returns a non-OK + // status. + // + // The returned file may be concurrently accessed by multiple threads. + virtual Status NewRandomAccessFile(const std::string& fname, + RandomAccessFile** result) = 0; + + // Create an object that writes to a new file with the specified + // name. Deletes any existing file with the same name and creates a + // new file. On success, stores a pointer to the new file in + // *result and returns OK. On failure stores NULL in *result and + // returns non-OK. + // + // The returned file will only be accessed by one thread at a time. + virtual Status NewWritableFile(const std::string& fname, + WritableFile** result) = 0; + + // Create an object that either appends to an existing file, or + // writes to a new file (if the file does not exist to begin with). + // On success, stores a pointer to the new file in *result and + // returns OK. On failure stores NULL in *result and returns + // non-OK. + // + // The returned file will only be accessed by one thread at a time. + // + // May return an IsNotSupportedError error if this Env does + // not allow appending to an existing file. Users of Env (including + // the leveldb implementation) must be prepared to deal with + // an Env that does not support appending. + virtual Status NewAppendableFile(const std::string& fname, + WritableFile** result); + + // Returns true iff the named file exists. + virtual bool FileExists(const std::string& fname) = 0; + + // Store in *result the names of the children of the specified directory. + // The names are relative to "dir". + // Original contents of *results are dropped. + virtual Status GetChildren(const std::string& dir, + std::vector* result) = 0; + + // Delete the named file. + virtual Status DeleteFile(const std::string& fname) = 0; + + // Create the specified directory. + virtual Status CreateDir(const std::string& dirname) = 0; + + // Delete the specified directory. + virtual Status DeleteDir(const std::string& dirname) = 0; + + // Store the size of fname in *file_size. + virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) = 0; + + // Rename file src to target. + virtual Status RenameFile(const std::string& src, + const std::string& target) = 0; + + // Lock the specified file. Used to prevent concurrent access to + // the same db by multiple processes. On failure, stores NULL in + // *lock and returns non-OK. + // + // On success, stores a pointer to the object that represents the + // acquired lock in *lock and returns OK. The caller should call + // UnlockFile(*lock) to release the lock. If the process exits, + // the lock will be automatically released. + // + // If somebody else already holds the lock, finishes immediately + // with a failure. I.e., this call does not wait for existing locks + // to go away. + // + // May create the named file if it does not already exist. + virtual Status LockFile(const std::string& fname, FileLock** lock) = 0; + + // Release the lock acquired by a previous successful call to LockFile. + // REQUIRES: lock was returned by a successful LockFile() call + // REQUIRES: lock has not already been unlocked. + virtual Status UnlockFile(FileLock* lock) = 0; + + // Arrange to run "(*function)(arg)" once in a background thread. + // + // "function" may run in an unspecified thread. Multiple functions + // added to the same Env may run concurrently in different threads. + // I.e., the caller may not assume that background work items are + // serialized. + virtual void Schedule( + void (*function)(void* arg), + void* arg) = 0; + + // Start a new thread, invoking "function(arg)" within the new thread. + // When "function(arg)" returns, the thread will be destroyed. + virtual void StartThread(void (*function)(void* arg), void* arg) = 0; + + // *path is set to a temporary directory that can be used for testing. It may + // or many not have just been created. The directory may or may not differ + // between runs of the same process, but subsequent calls will return the + // same directory. + virtual Status GetTestDirectory(std::string* path) = 0; + + // Create and return a log file for storing informational messages. + virtual Status NewLogger(const std::string& fname, Logger** result) = 0; + + // Returns the number of micro-seconds since some fixed point in time. Only + // useful for computing deltas of time. + virtual uint64_t NowMicros() = 0; + + // Sleep/delay the thread for the prescribed number of micro-seconds. + virtual void SleepForMicroseconds(int micros) = 0; + + private: + // No copying allowed + Env(const Env&); + void operator=(const Env&); +}; + +// A file abstraction for reading sequentially through a file +class SequentialFile { + public: + SequentialFile() { } + virtual ~SequentialFile(); + + // Read up to "n" bytes from the file. "scratch[0..n-1]" may be + // written by this routine. Sets "*result" to the data that was + // read (including if fewer than "n" bytes were successfully read). + // May set "*result" to point at data in "scratch[0..n-1]", so + // "scratch[0..n-1]" must be live when "*result" is used. + // If an error was encountered, returns a non-OK status. + // + // REQUIRES: External synchronization + virtual Status Read(size_t n, Slice* result, char* scratch) = 0; + + // Skip "n" bytes from the file. This is guaranteed to be no + // slower that reading the same data, but may be faster. + // + // If end of file is reached, skipping will stop at the end of the + // file, and Skip will return OK. + // + // REQUIRES: External synchronization + virtual Status Skip(uint64_t n) = 0; + + private: + // No copying allowed + SequentialFile(const SequentialFile&); + void operator=(const SequentialFile&); +}; + +// A file abstraction for randomly reading the contents of a file. +class RandomAccessFile { + public: + RandomAccessFile() { } + virtual ~RandomAccessFile(); + + // Read up to "n" bytes from the file starting at "offset". + // "scratch[0..n-1]" may be written by this routine. Sets "*result" + // to the data that was read (including if fewer than "n" bytes were + // successfully read). May set "*result" to point at data in + // "scratch[0..n-1]", so "scratch[0..n-1]" must be live when + // "*result" is used. If an error was encountered, returns a non-OK + // status. + // + // Safe for concurrent use by multiple threads. + virtual Status Read(uint64_t offset, size_t n, Slice* result, + char* scratch) const = 0; + + private: + // No copying allowed + RandomAccessFile(const RandomAccessFile&); + void operator=(const RandomAccessFile&); +}; + +// A file abstraction for sequential writing. The implementation +// must provide buffering since callers may append small fragments +// at a time to the file. +class WritableFile { + public: + WritableFile() { } + virtual ~WritableFile(); + + virtual Status Append(const Slice& data) = 0; + virtual Status Close() = 0; + virtual Status Flush() = 0; + virtual Status Sync() = 0; + + private: + // No copying allowed + WritableFile(const WritableFile&); + void operator=(const WritableFile&); +}; + +// An interface for writing log messages. +class Logger { + public: + Logger() { } + virtual ~Logger(); + + // Write an entry to the log file with the specified format. + virtual void Logv(const char* format, va_list ap) = 0; + + private: + // No copying allowed + Logger(const Logger&); + void operator=(const Logger&); +}; + + +// Identifies a locked file. +class FileLock { + public: + FileLock() { } + virtual ~FileLock(); + private: + // No copying allowed + FileLock(const FileLock&); + void operator=(const FileLock&); +}; + +// Log the specified data to *info_log if info_log is non-NULL. +extern void Log(Logger* info_log, const char* format, ...) +# if defined(__GNUC__) || defined(__clang__) + __attribute__((__format__ (__printf__, 2, 3))) +# endif + ; + +// A utility routine: write "data" to the named file. +extern Status WriteStringToFile(Env* env, const Slice& data, + const std::string& fname); + +// A utility routine: read contents of named file into *data +extern Status ReadFileToString(Env* env, const std::string& fname, + std::string* data); + +// An implementation of Env that forwards all calls to another Env. +// May be useful to clients who wish to override just part of the +// functionality of another Env. +class EnvWrapper : public Env { + public: + // Initialize an EnvWrapper that delegates all calls to *t + explicit EnvWrapper(Env* t) : target_(t) { } + virtual ~EnvWrapper(); + + // Return the target to which this Env forwards all calls + Env* target() const { return target_; } + + // The following text is boilerplate that forwards all methods to target() + Status NewSequentialFile(const std::string& f, SequentialFile** r) { + return target_->NewSequentialFile(f, r); + } + Status NewRandomAccessFile(const std::string& f, RandomAccessFile** r) { + return target_->NewRandomAccessFile(f, r); + } + Status NewWritableFile(const std::string& f, WritableFile** r) { + return target_->NewWritableFile(f, r); + } + Status NewAppendableFile(const std::string& f, WritableFile** r) { + return target_->NewAppendableFile(f, r); + } + bool FileExists(const std::string& f) { return target_->FileExists(f); } + Status GetChildren(const std::string& dir, std::vector* r) { + return target_->GetChildren(dir, r); + } + Status DeleteFile(const std::string& f) { return target_->DeleteFile(f); } + Status CreateDir(const std::string& d) { return target_->CreateDir(d); } + Status DeleteDir(const std::string& d) { return target_->DeleteDir(d); } + Status GetFileSize(const std::string& f, uint64_t* s) { + return target_->GetFileSize(f, s); + } + Status RenameFile(const std::string& s, const std::string& t) { + return target_->RenameFile(s, t); + } + Status LockFile(const std::string& f, FileLock** l) { + return target_->LockFile(f, l); + } + Status UnlockFile(FileLock* l) { return target_->UnlockFile(l); } + void Schedule(void (*f)(void*), void* a) { + return target_->Schedule(f, a); + } + void StartThread(void (*f)(void*), void* a) { + return target_->StartThread(f, a); + } + virtual Status GetTestDirectory(std::string* path) { + return target_->GetTestDirectory(path); + } + virtual Status NewLogger(const std::string& fname, Logger** result) { + return target_->NewLogger(fname, result); + } + uint64_t NowMicros() { + return target_->NowMicros(); + } + void SleepForMicroseconds(int micros) { + target_->SleepForMicroseconds(micros); + } + private: + Env* target_; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_ENV_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/filter_policy.h b/My Mind/Pods/leveldb-library/include/leveldb/filter_policy.h new file mode 100644 index 0000000..1fba080 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/filter_policy.h @@ -0,0 +1,70 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A database can be configured with a custom FilterPolicy object. +// This object is responsible for creating a small filter from a set +// of keys. These filters are stored in leveldb and are consulted +// automatically by leveldb to decide whether or not to read some +// information from disk. In many cases, a filter can cut down the +// number of disk seeks form a handful to a single disk seek per +// DB::Get() call. +// +// Most people will want to use the builtin bloom filter support (see +// NewBloomFilterPolicy() below). + +#ifndef STORAGE_LEVELDB_INCLUDE_FILTER_POLICY_H_ +#define STORAGE_LEVELDB_INCLUDE_FILTER_POLICY_H_ + +#include + +namespace leveldb { + +class Slice; + +class FilterPolicy { + public: + virtual ~FilterPolicy(); + + // Return the name of this policy. Note that if the filter encoding + // changes in an incompatible way, the name returned by this method + // must be changed. Otherwise, old incompatible filters may be + // passed to methods of this type. + virtual const char* Name() const = 0; + + // keys[0,n-1] contains a list of keys (potentially with duplicates) + // that are ordered according to the user supplied comparator. + // Append a filter that summarizes keys[0,n-1] to *dst. + // + // Warning: do not change the initial contents of *dst. Instead, + // append the newly constructed filter to *dst. + virtual void CreateFilter(const Slice* keys, int n, std::string* dst) + const = 0; + + // "filter" contains the data appended by a preceding call to + // CreateFilter() on this class. This method must return true if + // the key was in the list of keys passed to CreateFilter(). + // This method may return true or false if the key was not on the + // list, but it should aim to return false with a high probability. + virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const = 0; +}; + +// Return a new filter policy that uses a bloom filter with approximately +// the specified number of bits per key. A good value for bits_per_key +// is 10, which yields a filter with ~ 1% false positive rate. +// +// Callers must delete the result after any database that is using the +// result has been closed. +// +// Note: if you are using a custom comparator that ignores some parts +// of the keys being compared, you must not use NewBloomFilterPolicy() +// and must provide your own FilterPolicy that also ignores the +// corresponding parts of the keys. For example, if the comparator +// ignores trailing spaces, it would be incorrect to use a +// FilterPolicy (like NewBloomFilterPolicy) that does not ignore +// trailing spaces in keys. +extern const FilterPolicy* NewBloomFilterPolicy(int bits_per_key); + +} + +#endif // STORAGE_LEVELDB_INCLUDE_FILTER_POLICY_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/iterator.h b/My Mind/Pods/leveldb-library/include/leveldb/iterator.h new file mode 100644 index 0000000..da631ed --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/iterator.h @@ -0,0 +1,100 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// An iterator yields a sequence of key/value pairs from a source. +// The following class defines the interface. Multiple implementations +// are provided by this library. In particular, iterators are provided +// to access the contents of a Table or a DB. +// +// Multiple threads can invoke const methods on an Iterator without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Iterator must use +// external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_ITERATOR_H_ +#define STORAGE_LEVELDB_INCLUDE_ITERATOR_H_ + +#include "leveldb/slice.h" +#include "leveldb/status.h" + +namespace leveldb { + +class Iterator { + public: + Iterator(); + virtual ~Iterator(); + + // An iterator is either positioned at a key/value pair, or + // not valid. This method returns true iff the iterator is valid. + virtual bool Valid() const = 0; + + // Position at the first key in the source. The iterator is Valid() + // after this call iff the source is not empty. + virtual void SeekToFirst() = 0; + + // Position at the last key in the source. The iterator is + // Valid() after this call iff the source is not empty. + virtual void SeekToLast() = 0; + + // Position at the first key in the source that is at or past target. + // The iterator is Valid() after this call iff the source contains + // an entry that comes at or past target. + virtual void Seek(const Slice& target) = 0; + + // Moves to the next entry in the source. After this call, Valid() is + // true iff the iterator was not positioned at the last entry in the source. + // REQUIRES: Valid() + virtual void Next() = 0; + + // Moves to the previous entry in the source. After this call, Valid() is + // true iff the iterator was not positioned at the first entry in source. + // REQUIRES: Valid() + virtual void Prev() = 0; + + // Return the key for the current entry. The underlying storage for + // the returned slice is valid only until the next modification of + // the iterator. + // REQUIRES: Valid() + virtual Slice key() const = 0; + + // Return the value for the current entry. The underlying storage for + // the returned slice is valid only until the next modification of + // the iterator. + // REQUIRES: Valid() + virtual Slice value() const = 0; + + // If an error has occurred, return it. Else return an ok status. + virtual Status status() const = 0; + + // Clients are allowed to register function/arg1/arg2 triples that + // will be invoked when this iterator is destroyed. + // + // Note that unlike all of the preceding methods, this method is + // not abstract and therefore clients should not override it. + typedef void (*CleanupFunction)(void* arg1, void* arg2); + void RegisterCleanup(CleanupFunction function, void* arg1, void* arg2); + + private: + struct Cleanup { + CleanupFunction function; + void* arg1; + void* arg2; + Cleanup* next; + }; + Cleanup cleanup_; + + // No copying allowed + Iterator(const Iterator&); + void operator=(const Iterator&); +}; + +// Return an empty iterator (yields nothing). +extern Iterator* NewEmptyIterator(); + +// Return an empty iterator with the specified status. +extern Iterator* NewErrorIterator(const Status& status); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_ITERATOR_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/options.h b/My Mind/Pods/leveldb-library/include/leveldb/options.h new file mode 100644 index 0000000..976e381 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/options.h @@ -0,0 +1,213 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_INCLUDE_OPTIONS_H_ +#define STORAGE_LEVELDB_INCLUDE_OPTIONS_H_ + +#include + +namespace leveldb { + +class Cache; +class Comparator; +class Env; +class FilterPolicy; +class Logger; +class Snapshot; + +// DB contents are stored in a set of blocks, each of which holds a +// sequence of key,value pairs. Each block may be compressed before +// being stored in a file. The following enum describes which +// compression method (if any) is used to compress a block. +enum CompressionType { + // NOTE: do not change the values of existing entries, as these are + // part of the persistent format on disk. + kNoCompression = 0x0, + kSnappyCompression = 0x1 +}; + +// Options to control the behavior of a database (passed to DB::Open) +struct Options { + // ------------------- + // Parameters that affect behavior + + // Comparator used to define the order of keys in the table. + // Default: a comparator that uses lexicographic byte-wise ordering + // + // REQUIRES: The client must ensure that the comparator supplied + // here has the same name and orders keys *exactly* the same as the + // comparator provided to previous open calls on the same DB. + const Comparator* comparator; + + // If true, the database will be created if it is missing. + // Default: false + bool create_if_missing; + + // If true, an error is raised if the database already exists. + // Default: false + bool error_if_exists; + + // If true, the implementation will do aggressive checking of the + // data it is processing and will stop early if it detects any + // errors. This may have unforeseen ramifications: for example, a + // corruption of one DB entry may cause a large number of entries to + // become unreadable or for the entire DB to become unopenable. + // Default: false + bool paranoid_checks; + + // Use the specified object to interact with the environment, + // e.g. to read/write files, schedule background work, etc. + // Default: Env::Default() + Env* env; + + // Any internal progress/error information generated by the db will + // be written to info_log if it is non-NULL, or to a file stored + // in the same directory as the DB contents if info_log is NULL. + // Default: NULL + Logger* info_log; + + // ------------------- + // Parameters that affect performance + + // Amount of data to build up in memory (backed by an unsorted log + // on disk) before converting to a sorted on-disk file. + // + // Larger values increase performance, especially during bulk loads. + // Up to two write buffers may be held in memory at the same time, + // so you may wish to adjust this parameter to control memory usage. + // Also, a larger write buffer will result in a longer recovery time + // the next time the database is opened. + // + // Default: 4MB + size_t write_buffer_size; + + // Number of open files that can be used by the DB. You may need to + // increase this if your database has a large working set (budget + // one open file per 2MB of working set). + // + // Default: 1000 + int max_open_files; + + // Control over blocks (user data is stored in a set of blocks, and + // a block is the unit of reading from disk). + + // If non-NULL, use the specified cache for blocks. + // If NULL, leveldb will automatically create and use an 8MB internal cache. + // Default: NULL + Cache* block_cache; + + // Approximate size of user data packed per block. Note that the + // block size specified here corresponds to uncompressed data. The + // actual size of the unit read from disk may be smaller if + // compression is enabled. This parameter can be changed dynamically. + // + // Default: 4K + size_t block_size; + + // Number of keys between restart points for delta encoding of keys. + // This parameter can be changed dynamically. Most clients should + // leave this parameter alone. + // + // Default: 16 + int block_restart_interval; + + // Leveldb will write up to this amount of bytes to a file before + // switching to a new one. + // Most clients should leave this parameter alone. However if your + // filesystem is more efficient with larger files, you could + // consider increasing the value. The downside will be longer + // compactions and hence longer latency/performance hiccups. + // Another reason to increase this parameter might be when you are + // initially populating a large database. + // + // Default: 2MB + size_t max_file_size; + + // Compress blocks using the specified compression algorithm. This + // parameter can be changed dynamically. + // + // Default: kSnappyCompression, which gives lightweight but fast + // compression. + // + // Typical speeds of kSnappyCompression on an Intel(R) Core(TM)2 2.4GHz: + // ~200-500MB/s compression + // ~400-800MB/s decompression + // Note that these speeds are significantly faster than most + // persistent storage speeds, and therefore it is typically never + // worth switching to kNoCompression. Even if the input data is + // incompressible, the kSnappyCompression implementation will + // efficiently detect that and will switch to uncompressed mode. + CompressionType compression; + + // EXPERIMENTAL: If true, append to existing MANIFEST and log files + // when a database is opened. This can significantly speed up open. + // + // Default: currently false, but may become true later. + bool reuse_logs; + + // If non-NULL, use the specified filter policy to reduce disk reads. + // Many applications will benefit from passing the result of + // NewBloomFilterPolicy() here. + // + // Default: NULL + const FilterPolicy* filter_policy; + + // Create an Options object with default values for all fields. + Options(); +}; + +// Options that control read operations +struct ReadOptions { + // If true, all data read from underlying storage will be + // verified against corresponding checksums. + // Default: false + bool verify_checksums; + + // Should the data read for this iteration be cached in memory? + // Callers may wish to set this field to false for bulk scans. + // Default: true + bool fill_cache; + + // If "snapshot" is non-NULL, read as of the supplied snapshot + // (which must belong to the DB that is being read and which must + // not have been released). If "snapshot" is NULL, use an implicit + // snapshot of the state at the beginning of this read operation. + // Default: NULL + const Snapshot* snapshot; + + ReadOptions() + : verify_checksums(false), + fill_cache(true), + snapshot(NULL) { + } +}; + +// Options that control write operations +struct WriteOptions { + // If true, the write will be flushed from the operating system + // buffer cache (by calling WritableFile::Sync()) before the write + // is considered complete. If this flag is true, writes will be + // slower. + // + // If this flag is false, and the machine crashes, some recent + // writes may be lost. Note that if it is just the process that + // crashes (i.e., the machine does not reboot), no writes will be + // lost even if sync==false. + // + // In other words, a DB write with sync==false has similar + // crash semantics as the "write()" system call. A DB write + // with sync==true has similar crash semantics to a "write()" + // system call followed by "fsync()". + // + // Default: false + bool sync; + + WriteOptions() + : sync(false) { + } +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_OPTIONS_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/slice.h b/My Mind/Pods/leveldb-library/include/leveldb/slice.h new file mode 100644 index 0000000..bc36798 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/slice.h @@ -0,0 +1,109 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Slice is a simple structure containing a pointer into some external +// storage and a size. The user of a Slice must ensure that the slice +// is not used after the corresponding external storage has been +// deallocated. +// +// Multiple threads can invoke const methods on a Slice without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Slice must use +// external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_SLICE_H_ +#define STORAGE_LEVELDB_INCLUDE_SLICE_H_ + +#include +#include +#include +#include + +namespace leveldb { + +class Slice { + public: + // Create an empty slice. + Slice() : data_(""), size_(0) { } + + // Create a slice that refers to d[0,n-1]. + Slice(const char* d, size_t n) : data_(d), size_(n) { } + + // Create a slice that refers to the contents of "s" + Slice(const std::string& s) : data_(s.data()), size_(s.size()) { } + + // Create a slice that refers to s[0,strlen(s)-1] + Slice(const char* s) : data_(s), size_(strlen(s)) { } + + // Return a pointer to the beginning of the referenced data + const char* data() const { return data_; } + + // Return the length (in bytes) of the referenced data + size_t size() const { return size_; } + + // Return true iff the length of the referenced data is zero + bool empty() const { return size_ == 0; } + + // Return the ith byte in the referenced data. + // REQUIRES: n < size() + char operator[](size_t n) const { + assert(n < size()); + return data_[n]; + } + + // Change this slice to refer to an empty array + void clear() { data_ = ""; size_ = 0; } + + // Drop the first "n" bytes from this slice. + void remove_prefix(size_t n) { + assert(n <= size()); + data_ += n; + size_ -= n; + } + + // Return a string that contains the copy of the referenced data. + std::string ToString() const { return std::string(data_, size_); } + + // Three-way comparison. Returns value: + // < 0 iff "*this" < "b", + // == 0 iff "*this" == "b", + // > 0 iff "*this" > "b" + int compare(const Slice& b) const; + + // Return true iff "x" is a prefix of "*this" + bool starts_with(const Slice& x) const { + return ((size_ >= x.size_) && + (memcmp(data_, x.data_, x.size_) == 0)); + } + + private: + const char* data_; + size_t size_; + + // Intentionally copyable +}; + +inline bool operator==(const Slice& x, const Slice& y) { + return ((x.size() == y.size()) && + (memcmp(x.data(), y.data(), x.size()) == 0)); +} + +inline bool operator!=(const Slice& x, const Slice& y) { + return !(x == y); +} + +inline int Slice::compare(const Slice& b) const { + const size_t min_len = (size_ < b.size_) ? size_ : b.size_; + int r = memcmp(data_, b.data_, min_len); + if (r == 0) { + if (size_ < b.size_) r = -1; + else if (size_ > b.size_) r = +1; + } + return r; +} + +} // namespace leveldb + + +#endif // STORAGE_LEVELDB_INCLUDE_SLICE_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/status.h b/My Mind/Pods/leveldb-library/include/leveldb/status.h new file mode 100644 index 0000000..d9575f9 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/status.h @@ -0,0 +1,112 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A Status encapsulates the result of an operation. It may indicate success, +// or it may indicate an error with an associated error message. +// +// Multiple threads can invoke const methods on a Status without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Status must use +// external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_STATUS_H_ +#define STORAGE_LEVELDB_INCLUDE_STATUS_H_ + +#include +#include "leveldb/slice.h" + +namespace leveldb { + +class Status { + public: + // Create a success status. + Status() : state_(NULL) { } + ~Status() { delete[] state_; } + + // Copy the specified status. + Status(const Status& s); + void operator=(const Status& s); + + // Return a success status. + static Status OK() { return Status(); } + + // Return error status of an appropriate type. + static Status NotFound(const Slice& msg, const Slice& msg2 = Slice()) { + return Status(kNotFound, msg, msg2); + } + static Status Corruption(const Slice& msg, const Slice& msg2 = Slice()) { + return Status(kCorruption, msg, msg2); + } + static Status NotSupported(const Slice& msg, const Slice& msg2 = Slice()) { + return Status(kNotSupported, msg, msg2); + } + static Status InvalidArgument(const Slice& msg, const Slice& msg2 = Slice()) { + return Status(kInvalidArgument, msg, msg2); + } + static Status IOError(const Slice& msg, const Slice& msg2 = Slice()) { + return Status(kIOError, msg, msg2); + } + + // Returns true iff the status indicates success. + bool ok() const { return (state_ == NULL); } + + // Returns true iff the status indicates a NotFound error. + bool IsNotFound() const { return code() == kNotFound; } + + // Returns true iff the status indicates a Corruption error. + bool IsCorruption() const { return code() == kCorruption; } + + // Returns true iff the status indicates an IOError. + bool IsIOError() const { return code() == kIOError; } + + // Returns true iff the status indicates a NotSupportedError. + bool IsNotSupportedError() const { return code() == kNotSupported; } + + // Returns true iff the status indicates an InvalidArgument. + bool IsInvalidArgument() const { return code() == kInvalidArgument; } + + // Return a string representation of this status suitable for printing. + // Returns the string "OK" for success. + std::string ToString() const; + + private: + // OK status has a NULL state_. Otherwise, state_ is a new[] array + // of the following form: + // state_[0..3] == length of message + // state_[4] == code + // state_[5..] == message + const char* state_; + + enum Code { + kOk = 0, + kNotFound = 1, + kCorruption = 2, + kNotSupported = 3, + kInvalidArgument = 4, + kIOError = 5 + }; + + Code code() const { + return (state_ == NULL) ? kOk : static_cast(state_[4]); + } + + Status(Code code, const Slice& msg, const Slice& msg2); + static const char* CopyState(const char* s); +}; + +inline Status::Status(const Status& s) { + state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); +} +inline void Status::operator=(const Status& s) { + // The following condition catches both aliasing (when this == &s), + // and the common case where both s and *this are ok. + if (state_ != s.state_) { + delete[] state_; + state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); + } +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_STATUS_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/table.h b/My Mind/Pods/leveldb-library/include/leveldb/table.h new file mode 100644 index 0000000..a9746c3 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/table.h @@ -0,0 +1,85 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_INCLUDE_TABLE_H_ +#define STORAGE_LEVELDB_INCLUDE_TABLE_H_ + +#include +#include "leveldb/iterator.h" + +namespace leveldb { + +class Block; +class BlockHandle; +class Footer; +struct Options; +class RandomAccessFile; +struct ReadOptions; +class TableCache; + +// A Table is a sorted map from strings to strings. Tables are +// immutable and persistent. A Table may be safely accessed from +// multiple threads without external synchronization. +class Table { + public: + // Attempt to open the table that is stored in bytes [0..file_size) + // of "file", and read the metadata entries necessary to allow + // retrieving data from the table. + // + // If successful, returns ok and sets "*table" to the newly opened + // table. The client should delete "*table" when no longer needed. + // If there was an error while initializing the table, sets "*table" + // to NULL and returns a non-ok status. Does not take ownership of + // "*source", but the client must ensure that "source" remains live + // for the duration of the returned table's lifetime. + // + // *file must remain live while this Table is in use. + static Status Open(const Options& options, + RandomAccessFile* file, + uint64_t file_size, + Table** table); + + ~Table(); + + // Returns a new iterator over the table contents. + // The result of NewIterator() is initially invalid (caller must + // call one of the Seek methods on the iterator before using it). + Iterator* NewIterator(const ReadOptions&) const; + + // Given a key, return an approximate byte offset in the file where + // the data for that key begins (or would begin if the key were + // present in the file). The returned value is in terms of file + // bytes, and so includes effects like compression of the underlying data. + // E.g., the approximate offset of the last key in the table will + // be close to the file length. + uint64_t ApproximateOffsetOf(const Slice& key) const; + + private: + struct Rep; + Rep* rep_; + + explicit Table(Rep* rep) { rep_ = rep; } + static Iterator* BlockReader(void*, const ReadOptions&, const Slice&); + + // Calls (*handle_result)(arg, ...) with the entry found after a call + // to Seek(key). May not make such a call if filter policy says + // that key is not present. + friend class TableCache; + Status InternalGet( + const ReadOptions&, const Slice& key, + void* arg, + void (*handle_result)(void* arg, const Slice& k, const Slice& v)); + + + void ReadMeta(const Footer& footer); + void ReadFilter(const Slice& filter_handle_value); + + // No copying allowed + Table(const Table&); + void operator=(const Table&); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_TABLE_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/table_builder.h b/My Mind/Pods/leveldb-library/include/leveldb/table_builder.h new file mode 100644 index 0000000..5fd1dc7 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/table_builder.h @@ -0,0 +1,92 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// TableBuilder provides the interface used to build a Table +// (an immutable and sorted map from keys to values). +// +// Multiple threads can invoke const methods on a TableBuilder without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same TableBuilder must use +// external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_ +#define STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_ + +#include +#include "leveldb/options.h" +#include "leveldb/status.h" + +namespace leveldb { + +class BlockBuilder; +class BlockHandle; +class WritableFile; + +class TableBuilder { + public: + // Create a builder that will store the contents of the table it is + // building in *file. Does not close the file. It is up to the + // caller to close the file after calling Finish(). + TableBuilder(const Options& options, WritableFile* file); + + // REQUIRES: Either Finish() or Abandon() has been called. + ~TableBuilder(); + + // Change the options used by this builder. Note: only some of the + // option fields can be changed after construction. If a field is + // not allowed to change dynamically and its value in the structure + // passed to the constructor is different from its value in the + // structure passed to this method, this method will return an error + // without changing any fields. + Status ChangeOptions(const Options& options); + + // Add key,value to the table being constructed. + // REQUIRES: key is after any previously added key according to comparator. + // REQUIRES: Finish(), Abandon() have not been called + void Add(const Slice& key, const Slice& value); + + // Advanced operation: flush any buffered key/value pairs to file. + // Can be used to ensure that two adjacent entries never live in + // the same data block. Most clients should not need to use this method. + // REQUIRES: Finish(), Abandon() have not been called + void Flush(); + + // Return non-ok iff some error has been detected. + Status status() const; + + // Finish building the table. Stops using the file passed to the + // constructor after this function returns. + // REQUIRES: Finish(), Abandon() have not been called + Status Finish(); + + // Indicate that the contents of this builder should be abandoned. Stops + // using the file passed to the constructor after this function returns. + // If the caller is not going to call Finish(), it must call Abandon() + // before destroying this builder. + // REQUIRES: Finish(), Abandon() have not been called + void Abandon(); + + // Number of calls to Add() so far. + uint64_t NumEntries() const; + + // Size of the file generated so far. If invoked after a successful + // Finish() call, returns the size of the final generated file. + uint64_t FileSize() const; + + private: + bool ok() const { return status().ok(); } + void WriteBlock(BlockBuilder* block, BlockHandle* handle); + void WriteRawBlock(const Slice& data, CompressionType, BlockHandle* handle); + + struct Rep; + Rep* rep_; + + // No copying allowed + TableBuilder(const TableBuilder&); + void operator=(const TableBuilder&); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_ diff --git a/My Mind/Pods/leveldb-library/include/leveldb/write_batch.h b/My Mind/Pods/leveldb-library/include/leveldb/write_batch.h new file mode 100644 index 0000000..ee9aab6 --- /dev/null +++ b/My Mind/Pods/leveldb-library/include/leveldb/write_batch.h @@ -0,0 +1,64 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// WriteBatch holds a collection of updates to apply atomically to a DB. +// +// The updates are applied in the order in which they are added +// to the WriteBatch. For example, the value of "key" will be "v3" +// after the following batch is written: +// +// batch.Put("key", "v1"); +// batch.Delete("key"); +// batch.Put("key", "v2"); +// batch.Put("key", "v3"); +// +// Multiple threads can invoke const methods on a WriteBatch without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same WriteBatch must use +// external synchronization. + +#ifndef STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_ +#define STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_ + +#include +#include "leveldb/status.h" + +namespace leveldb { + +class Slice; + +class WriteBatch { + public: + WriteBatch(); + ~WriteBatch(); + + // Store the mapping "key->value" in the database. + void Put(const Slice& key, const Slice& value); + + // If the database contains a mapping for "key", erase it. Else do nothing. + void Delete(const Slice& key); + + // Clear all updates buffered in this batch. + void Clear(); + + // Support for iterating over the contents of a batch. + class Handler { + public: + virtual ~Handler(); + virtual void Put(const Slice& key, const Slice& value) = 0; + virtual void Delete(const Slice& key) = 0; + }; + Status Iterate(Handler* handler) const; + + private: + friend class WriteBatchInternal; + + std::string rep_; // See comment in write_batch.cc for the format of rep_ + + // Intentionally copyable +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_ diff --git a/My Mind/Pods/leveldb-library/port/atomic_pointer.h b/My Mind/Pods/leveldb-library/port/atomic_pointer.h new file mode 100644 index 0000000..1c4c7aa --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/atomic_pointer.h @@ -0,0 +1,242 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +// AtomicPointer provides storage for a lock-free pointer. +// Platform-dependent implementation of AtomicPointer: +// - If the platform provides a cheap barrier, we use it with raw pointers +// - If is present (on newer versions of gcc, it is), we use +// a -based AtomicPointer. However we prefer the memory +// barrier based version, because at least on a gcc 4.4 32-bit build +// on linux, we have encountered a buggy implementation. +// Also, some implementations are much slower than a memory-barrier +// based implementation (~16ns for based acquire-load vs. ~1ns for +// a barrier based acquire-load). +// This code is based on atomicops-internals-* in Google's perftools: +// http://code.google.com/p/google-perftools/source/browse/#svn%2Ftrunk%2Fsrc%2Fbase + +#ifndef PORT_ATOMIC_POINTER_H_ +#define PORT_ATOMIC_POINTER_H_ + +#include +#ifdef LEVELDB_ATOMIC_PRESENT +#include +#endif +#ifdef OS_WIN +#include +#endif +#ifdef OS_MACOSX +#include +#endif + +#if defined(_M_X64) || defined(__x86_64__) +#define ARCH_CPU_X86_FAMILY 1 +#elif defined(_M_IX86) || defined(__i386__) || defined(__i386) +#define ARCH_CPU_X86_FAMILY 1 +#elif defined(__ARMEL__) +#define ARCH_CPU_ARM_FAMILY 1 +#elif defined(__aarch64__) +#define ARCH_CPU_ARM64_FAMILY 1 +#elif defined(__ppc__) || defined(__powerpc__) || defined(__powerpc64__) +#define ARCH_CPU_PPC_FAMILY 1 +#elif defined(__mips__) +#define ARCH_CPU_MIPS_FAMILY 1 +#endif + +namespace leveldb { +namespace port { + +// Define MemoryBarrier() if available +// Windows on x86 +#if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY) +// windows.h already provides a MemoryBarrier(void) macro +// http://msdn.microsoft.com/en-us/library/ms684208(v=vs.85).aspx +#define LEVELDB_HAVE_MEMORY_BARRIER + +// Mac OS +#elif defined(OS_MACOSX) +inline void MemoryBarrier() { + OSMemoryBarrier(); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// Gcc on x86 +#elif defined(ARCH_CPU_X86_FAMILY) && defined(__GNUC__) +inline void MemoryBarrier() { + // See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on + // this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering. + __asm__ __volatile__("" : : : "memory"); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// Sun Studio +#elif defined(ARCH_CPU_X86_FAMILY) && defined(__SUNPRO_CC) +inline void MemoryBarrier() { + // See http://gcc.gnu.org/ml/gcc/2003-04/msg01180.html for a discussion on + // this idiom. Also see http://en.wikipedia.org/wiki/Memory_ordering. + asm volatile("" : : : "memory"); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// ARM Linux +#elif defined(ARCH_CPU_ARM_FAMILY) && defined(__linux__) +typedef void (*LinuxKernelMemoryBarrierFunc)(void); +// The Linux ARM kernel provides a highly optimized device-specific memory +// barrier function at a fixed memory address that is mapped in every +// user-level process. +// +// This beats using CPU-specific instructions which are, on single-core +// devices, un-necessary and very costly (e.g. ARMv7-A "dmb" takes more +// than 180ns on a Cortex-A8 like the one on a Nexus One). Benchmarking +// shows that the extra function call cost is completely negligible on +// multi-core devices. +// +inline void MemoryBarrier() { + (*(LinuxKernelMemoryBarrierFunc)0xffff0fa0)(); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// ARM64 +#elif defined(ARCH_CPU_ARM64_FAMILY) +inline void MemoryBarrier() { + asm volatile("dmb sy" : : : "memory"); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// PPC +#elif defined(ARCH_CPU_PPC_FAMILY) && defined(__GNUC__) +inline void MemoryBarrier() { + // TODO for some powerpc expert: is there a cheaper suitable variant? + // Perhaps by having separate barriers for acquire and release ops. + asm volatile("sync" : : : "memory"); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +// MIPS +#elif defined(ARCH_CPU_MIPS_FAMILY) && defined(__GNUC__) +inline void MemoryBarrier() { + __asm__ __volatile__("sync" : : : "memory"); +} +#define LEVELDB_HAVE_MEMORY_BARRIER + +#endif + +// AtomicPointer built using platform-specific MemoryBarrier() +#if defined(LEVELDB_HAVE_MEMORY_BARRIER) +class AtomicPointer { + private: + void* rep_; + public: + AtomicPointer() { } + explicit AtomicPointer(void* p) : rep_(p) {} + inline void* NoBarrier_Load() const { return rep_; } + inline void NoBarrier_Store(void* v) { rep_ = v; } + inline void* Acquire_Load() const { + void* result = rep_; + MemoryBarrier(); + return result; + } + inline void Release_Store(void* v) { + MemoryBarrier(); + rep_ = v; + } +}; + +// AtomicPointer based on +#elif defined(LEVELDB_ATOMIC_PRESENT) +class AtomicPointer { + private: + std::atomic rep_; + public: + AtomicPointer() { } + explicit AtomicPointer(void* v) : rep_(v) { } + inline void* Acquire_Load() const { + return rep_.load(std::memory_order_acquire); + } + inline void Release_Store(void* v) { + rep_.store(v, std::memory_order_release); + } + inline void* NoBarrier_Load() const { + return rep_.load(std::memory_order_relaxed); + } + inline void NoBarrier_Store(void* v) { + rep_.store(v, std::memory_order_relaxed); + } +}; + +// Atomic pointer based on sparc memory barriers +#elif defined(__sparcv9) && defined(__GNUC__) +class AtomicPointer { + private: + void* rep_; + public: + AtomicPointer() { } + explicit AtomicPointer(void* v) : rep_(v) { } + inline void* Acquire_Load() const { + void* val; + __asm__ __volatile__ ( + "ldx [%[rep_]], %[val] \n\t" + "membar #LoadLoad|#LoadStore \n\t" + : [val] "=r" (val) + : [rep_] "r" (&rep_) + : "memory"); + return val; + } + inline void Release_Store(void* v) { + __asm__ __volatile__ ( + "membar #LoadStore|#StoreStore \n\t" + "stx %[v], [%[rep_]] \n\t" + : + : [rep_] "r" (&rep_), [v] "r" (v) + : "memory"); + } + inline void* NoBarrier_Load() const { return rep_; } + inline void NoBarrier_Store(void* v) { rep_ = v; } +}; + +// Atomic pointer based on ia64 acq/rel +#elif defined(__ia64) && defined(__GNUC__) +class AtomicPointer { + private: + void* rep_; + public: + AtomicPointer() { } + explicit AtomicPointer(void* v) : rep_(v) { } + inline void* Acquire_Load() const { + void* val ; + __asm__ __volatile__ ( + "ld8.acq %[val] = [%[rep_]] \n\t" + : [val] "=r" (val) + : [rep_] "r" (&rep_) + : "memory" + ); + return val; + } + inline void Release_Store(void* v) { + __asm__ __volatile__ ( + "st8.rel [%[rep_]] = %[v] \n\t" + : + : [rep_] "r" (&rep_), [v] "r" (v) + : "memory" + ); + } + inline void* NoBarrier_Load() const { return rep_; } + inline void NoBarrier_Store(void* v) { rep_ = v; } +}; + +// We have neither MemoryBarrier(), nor +#else +#error Please implement AtomicPointer for this platform. + +#endif + +#undef LEVELDB_HAVE_MEMORY_BARRIER +#undef ARCH_CPU_X86_FAMILY +#undef ARCH_CPU_ARM_FAMILY +#undef ARCH_CPU_ARM64_FAMILY +#undef ARCH_CPU_PPC_FAMILY + +} // namespace port +} // namespace leveldb + +#endif // PORT_ATOMIC_POINTER_H_ diff --git a/My Mind/Pods/leveldb-library/port/port.h b/My Mind/Pods/leveldb-library/port/port.h new file mode 100644 index 0000000..e667db4 --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/port.h @@ -0,0 +1,19 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_PORT_PORT_H_ +#define STORAGE_LEVELDB_PORT_PORT_H_ + +#include + +// Include the appropriate platform specific file below. If you are +// porting to a new platform, see "port_example.h" for documentation +// of what the new port_.h file must provide. +#if defined(LEVELDB_PLATFORM_POSIX) +# include "port/port_posix.h" +#elif defined(LEVELDB_PLATFORM_CHROMIUM) +# include "port/port_chromium.h" +#endif + +#endif // STORAGE_LEVELDB_PORT_PORT_H_ diff --git a/My Mind/Pods/leveldb-library/port/port_example.h b/My Mind/Pods/leveldb-library/port/port_example.h new file mode 100644 index 0000000..97bd669 --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/port_example.h @@ -0,0 +1,141 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// This file contains the specification, but not the implementations, +// of the types/operations/etc. that should be defined by a platform +// specific port_.h file. Use this file as a reference for +// how to port this package to a new platform. + +#ifndef STORAGE_LEVELDB_PORT_PORT_EXAMPLE_H_ +#define STORAGE_LEVELDB_PORT_PORT_EXAMPLE_H_ + +namespace leveldb { +namespace port { + +// TODO(jorlow): Many of these belong more in the environment class rather than +// here. We should try moving them and see if it affects perf. + +// The following boolean constant must be true on a little-endian machine +// and false otherwise. +static const bool kLittleEndian = true /* or some other expression */; + +// ------------------ Threading ------------------- + +// A Mutex represents an exclusive lock. +class Mutex { + public: + Mutex(); + ~Mutex(); + + // Lock the mutex. Waits until other lockers have exited. + // Will deadlock if the mutex is already locked by this thread. + void Lock(); + + // Unlock the mutex. + // REQUIRES: This mutex was locked by this thread. + void Unlock(); + + // Optionally crash if this thread does not hold this mutex. + // The implementation must be fast, especially if NDEBUG is + // defined. The implementation is allowed to skip all checks. + void AssertHeld(); +}; + +class CondVar { + public: + explicit CondVar(Mutex* mu); + ~CondVar(); + + // Atomically release *mu and block on this condition variable until + // either a call to SignalAll(), or a call to Signal() that picks + // this thread to wakeup. + // REQUIRES: this thread holds *mu + void Wait(); + + // If there are some threads waiting, wake up at least one of them. + void Signal(); + + // Wake up all waiting threads. + void SignallAll(); +}; + +// Thread-safe initialization. +// Used as follows: +// static port::OnceType init_control = LEVELDB_ONCE_INIT; +// static void Initializer() { ... do something ...; } +// ... +// port::InitOnce(&init_control, &Initializer); +typedef intptr_t OnceType; +#define LEVELDB_ONCE_INIT 0 +extern void InitOnce(port::OnceType*, void (*initializer)()); + +// A type that holds a pointer that can be read or written atomically +// (i.e., without word-tearing.) +class AtomicPointer { + private: + intptr_t rep_; + public: + // Initialize to arbitrary value + AtomicPointer(); + + // Initialize to hold v + explicit AtomicPointer(void* v) : rep_(v) { } + + // Read and return the stored pointer with the guarantee that no + // later memory access (read or write) by this thread can be + // reordered ahead of this read. + void* Acquire_Load() const; + + // Set v as the stored pointer with the guarantee that no earlier + // memory access (read or write) by this thread can be reordered + // after this store. + void Release_Store(void* v); + + // Read the stored pointer with no ordering guarantees. + void* NoBarrier_Load() const; + + // Set va as the stored pointer with no ordering guarantees. + void NoBarrier_Store(void* v); +}; + +// ------------------ Compression ------------------- + +// Store the snappy compression of "input[0,input_length-1]" in *output. +// Returns false if snappy is not supported by this port. +extern bool Snappy_Compress(const char* input, size_t input_length, + std::string* output); + +// If input[0,input_length-1] looks like a valid snappy compressed +// buffer, store the size of the uncompressed data in *result and +// return true. Else return false. +extern bool Snappy_GetUncompressedLength(const char* input, size_t length, + size_t* result); + +// Attempt to snappy uncompress input[0,input_length-1] into *output. +// Returns true if successful, false if the input is invalid lightweight +// compressed data. +// +// REQUIRES: at least the first "n" bytes of output[] must be writable +// where "n" is the result of a successful call to +// Snappy_GetUncompressedLength. +extern bool Snappy_Uncompress(const char* input_data, size_t input_length, + char* output); + +// ------------------ Miscellaneous ------------------- + +// If heap profiling is not supported, returns false. +// Else repeatedly calls (*func)(arg, data, n) and then returns true. +// The concatenation of all "data[0,n-1]" fragments is the heap profile. +extern bool GetHeapProfile(void (*func)(void*, const char*, int), void* arg); + +// Extend the CRC to include the first n bytes of buf. +// +// Returns zero if the CRC cannot be extended using acceleration, else returns +// the newly extended CRC value (which may also be zero). +uint32_t AcceleratedCRC32C(uint32_t crc, const char* buf, size_t size); + +} // namespace port +} // namespace leveldb + +#endif // STORAGE_LEVELDB_PORT_PORT_EXAMPLE_H_ diff --git a/My Mind/Pods/leveldb-library/port/port_posix.cc b/My Mind/Pods/leveldb-library/port/port_posix.cc new file mode 100644 index 0000000..30e8007 --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/port_posix.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "port/port_posix.h" + +#include +#include +#include + +namespace leveldb { +namespace port { + +static void PthreadCall(const char* label, int result) { + if (result != 0) { + fprintf(stderr, "pthread %s: %s\n", label, strerror(result)); + abort(); + } +} + +Mutex::Mutex() { PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL)); } + +Mutex::~Mutex() { PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); } + +void Mutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); } + +void Mutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); } + +CondVar::CondVar(Mutex* mu) + : mu_(mu) { + PthreadCall("init cv", pthread_cond_init(&cv_, NULL)); +} + +CondVar::~CondVar() { PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); } + +void CondVar::Wait() { + PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_)); +} + +void CondVar::Signal() { + PthreadCall("signal", pthread_cond_signal(&cv_)); +} + +void CondVar::SignalAll() { + PthreadCall("broadcast", pthread_cond_broadcast(&cv_)); +} + +void InitOnce(OnceType* once, void (*initializer)()) { + PthreadCall("once", pthread_once(once, initializer)); +} + +} // namespace port +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/port/port_posix.h b/My Mind/Pods/leveldb-library/port/port_posix.h new file mode 100644 index 0000000..d67ab68 --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/port_posix.h @@ -0,0 +1,156 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// See port_example.h for documentation for the following types/functions. + +#ifndef STORAGE_LEVELDB_PORT_PORT_POSIX_H_ +#define STORAGE_LEVELDB_PORT_PORT_POSIX_H_ + +#undef PLATFORM_IS_LITTLE_ENDIAN +#if defined(OS_MACOSX) + #include + #if defined(__DARWIN_LITTLE_ENDIAN) && defined(__DARWIN_BYTE_ORDER) + #define PLATFORM_IS_LITTLE_ENDIAN \ + (__DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN) + #endif +#elif defined(OS_SOLARIS) + #include + #ifdef _LITTLE_ENDIAN + #define PLATFORM_IS_LITTLE_ENDIAN true + #else + #define PLATFORM_IS_LITTLE_ENDIAN false + #endif +#elif defined(OS_FREEBSD) || defined(OS_OPENBSD) ||\ + defined(OS_NETBSD) || defined(OS_DRAGONFLYBSD) + #include + #include + #define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN) +#elif defined(OS_HPUX) + #define PLATFORM_IS_LITTLE_ENDIAN false +#elif defined(OS_ANDROID) + // Due to a bug in the NDK x86 definition, + // _BYTE_ORDER must be used instead of __BYTE_ORDER on Android. + // See http://code.google.com/p/android/issues/detail?id=39824 + #include + #define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN) +#else + #include +#endif + +#include +#ifdef SNAPPY +#include +#endif +#include +#include +#include "port/atomic_pointer.h" + +#ifndef PLATFORM_IS_LITTLE_ENDIAN +#define PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN) +#endif + +#if defined(OS_MACOSX) || defined(OS_SOLARIS) || defined(OS_FREEBSD) ||\ + defined(OS_NETBSD) || defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD) ||\ + defined(OS_ANDROID) || defined(OS_HPUX) || defined(CYGWIN) +// Use fread/fwrite/fflush on platforms without _unlocked variants +#define fread_unlocked fread +#define fwrite_unlocked fwrite +#define fflush_unlocked fflush +#endif + +#if defined(OS_MACOSX) || defined(OS_FREEBSD) ||\ + defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD) +// Use fsync() on platforms without fdatasync() +#define fdatasync fsync +#endif + +#if defined(OS_ANDROID) && __ANDROID_API__ < 9 +// fdatasync() was only introduced in API level 9 on Android. Use fsync() +// when targetting older platforms. +#define fdatasync fsync +#endif + +namespace leveldb { +namespace port { + +static const bool kLittleEndian = PLATFORM_IS_LITTLE_ENDIAN; +#undef PLATFORM_IS_LITTLE_ENDIAN + +class CondVar; + +class Mutex { + public: + Mutex(); + ~Mutex(); + + void Lock(); + void Unlock(); + void AssertHeld() { } + + private: + friend class CondVar; + pthread_mutex_t mu_; + + // No copying + Mutex(const Mutex&); + void operator=(const Mutex&); +}; + +class CondVar { + public: + explicit CondVar(Mutex* mu); + ~CondVar(); + void Wait(); + void Signal(); + void SignalAll(); + private: + pthread_cond_t cv_; + Mutex* mu_; +}; + +typedef pthread_once_t OnceType; +#define LEVELDB_ONCE_INIT PTHREAD_ONCE_INIT +extern void InitOnce(OnceType* once, void (*initializer)()); + +inline bool Snappy_Compress(const char* input, size_t length, + ::std::string* output) { +#ifdef SNAPPY + output->resize(snappy::MaxCompressedLength(length)); + size_t outlen; + snappy::RawCompress(input, length, &(*output)[0], &outlen); + output->resize(outlen); + return true; +#endif + + return false; +} + +inline bool Snappy_GetUncompressedLength(const char* input, size_t length, + size_t* result) { +#ifdef SNAPPY + return snappy::GetUncompressedLength(input, length, result); +#else + return false; +#endif +} + +inline bool Snappy_Uncompress(const char* input, size_t length, + char* output) { +#ifdef SNAPPY + return snappy::RawUncompress(input, length, output); +#else + return false; +#endif +} + +inline bool GetHeapProfile(void (*func)(void*, const char*, int), void* arg) { + return false; +} + +uint32_t AcceleratedCRC32C(uint32_t crc, const char* buf, size_t size); + +} // namespace port +} // namespace leveldb + +#endif // STORAGE_LEVELDB_PORT_PORT_POSIX_H_ diff --git a/My Mind/Pods/leveldb-library/port/port_posix_sse.cc b/My Mind/Pods/leveldb-library/port/port_posix_sse.cc new file mode 100644 index 0000000..1e519ba --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/port_posix_sse.cc @@ -0,0 +1,129 @@ +// Copyright 2016 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A portable implementation of crc32c, optimized to handle +// four bytes at a time. +// +// In a separate source file to allow this accelerated CRC32C function to be +// compiled with the appropriate compiler flags to enable x86 SSE 4.2 +// instructions. + +#include +#include +#include "port/port.h" + +#if defined(LEVELDB_PLATFORM_POSIX_SSE) + +#if defined(_MSC_VER) +#include +#elif defined(__GNUC__) && defined(__SSE4_2__) +#include +#include +#endif + +#endif // defined(LEVELDB_PLATFORM_POSIX_SSE) + +namespace leveldb { +namespace port { + +#if defined(LEVELDB_PLATFORM_POSIX_SSE) + +// Used to fetch a naturally-aligned 32-bit word in little endian byte-order +static inline uint32_t LE_LOAD32(const uint8_t *p) { + // SSE is x86 only, so ensured that |p| is always little-endian. + uint32_t word; + memcpy(&word, p, sizeof(word)); + return word; +} + +#if defined(_M_X64) || defined(__x86_64__) // LE_LOAD64 is only used on x64. + +// Used to fetch a naturally-aligned 64-bit word in little endian byte-order +static inline uint64_t LE_LOAD64(const uint8_t *p) { + uint64_t dword; + memcpy(&dword, p, sizeof(dword)); + return dword; +} + +#endif // defined(_M_X64) || defined(__x86_64__) + +static inline bool HaveSSE42() { +#if defined(_MSC_VER) + int cpu_info[4]; + __cpuid(cpu_info, 1); + return (cpu_info[2] & (1 << 20)) != 0; +#elif defined(__GNUC__) + unsigned int eax, ebx, ecx, edx; + __get_cpuid(1, &eax, &ebx, &ecx, &edx); + return (ecx & (1 << 20)) != 0; +#else + return false; +#endif +} + +#endif // defined(LEVELDB_PLATFORM_POSIX_SSE) + +// For further improvements see Intel publication at: +// http://download.intel.com/design/intarch/papers/323405.pdf +uint32_t AcceleratedCRC32C(uint32_t crc, const char* buf, size_t size) { +#if !defined(LEVELDB_PLATFORM_POSIX_SSE) + return 0; +#else + static bool have = HaveSSE42(); + if (!have) { + return 0; + } + + const uint8_t *p = reinterpret_cast(buf); + const uint8_t *e = p + size; + uint32_t l = crc ^ 0xffffffffu; + +#define STEP1 do { \ + l = _mm_crc32_u8(l, *p++); \ +} while (0) +#define STEP4 do { \ + l = _mm_crc32_u32(l, LE_LOAD32(p)); \ + p += 4; \ +} while (0) +#define STEP8 do { \ + l = _mm_crc32_u64(l, LE_LOAD64(p)); \ + p += 8; \ +} while (0) + + if (size > 16) { + // Process unaligned bytes + for (unsigned int i = reinterpret_cast(p) % 8; i; --i) { + STEP1; + } + + // _mm_crc32_u64 is only available on x64. +#if defined(_M_X64) || defined(__x86_64__) + // Process 8 bytes at a time + while ((e-p) >= 8) { + STEP8; + } + // Process 4 bytes at a time + if ((e-p) >= 4) { + STEP4; + } +#else // !(defined(_M_X64) || defined(__x86_64__)) + // Process 4 bytes at a time + while ((e-p) >= 4) { + STEP4; + } +#endif // defined(_M_X64) || defined(__x86_64__) + } + // Process the last few bytes + while (p != e) { + STEP1; + } +#undef STEP8 +#undef STEP4 +#undef STEP1 + return l ^ 0xffffffffu; +#endif // defined(LEVELDB_PLATFORM_POSIX_SSE) +} + +} // namespace port +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/port/thread_annotations.h b/My Mind/Pods/leveldb-library/port/thread_annotations.h new file mode 100644 index 0000000..9470ef5 --- /dev/null +++ b/My Mind/Pods/leveldb-library/port/thread_annotations.h @@ -0,0 +1,60 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_ +#define STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_ + +// Some environments provide custom macros to aid in static thread-safety +// analysis. Provide empty definitions of such macros unless they are already +// defined. + +#ifndef EXCLUSIVE_LOCKS_REQUIRED +#define EXCLUSIVE_LOCKS_REQUIRED(...) +#endif + +#ifndef SHARED_LOCKS_REQUIRED +#define SHARED_LOCKS_REQUIRED(...) +#endif + +#ifndef LOCKS_EXCLUDED +#define LOCKS_EXCLUDED(...) +#endif + +#ifndef LOCK_RETURNED +#define LOCK_RETURNED(x) +#endif + +#ifndef LOCKABLE +#define LOCKABLE +#endif + +#ifndef SCOPED_LOCKABLE +#define SCOPED_LOCKABLE +#endif + +#ifndef EXCLUSIVE_LOCK_FUNCTION +#define EXCLUSIVE_LOCK_FUNCTION(...) +#endif + +#ifndef SHARED_LOCK_FUNCTION +#define SHARED_LOCK_FUNCTION(...) +#endif + +#ifndef EXCLUSIVE_TRYLOCK_FUNCTION +#define EXCLUSIVE_TRYLOCK_FUNCTION(...) +#endif + +#ifndef SHARED_TRYLOCK_FUNCTION +#define SHARED_TRYLOCK_FUNCTION(...) +#endif + +#ifndef UNLOCK_FUNCTION +#define UNLOCK_FUNCTION(...) +#endif + +#ifndef NO_THREAD_SAFETY_ANALYSIS +#define NO_THREAD_SAFETY_ANALYSIS +#endif + +#endif // STORAGE_LEVELDB_PORT_THREAD_ANNOTATIONS_H_ diff --git a/My Mind/Pods/leveldb-library/table/block.cc b/My Mind/Pods/leveldb-library/table/block.cc new file mode 100644 index 0000000..43e402c --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/block.cc @@ -0,0 +1,268 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Decodes the blocks generated by block_builder.cc. + +#include "table/block.h" + +#include +#include +#include "leveldb/comparator.h" +#include "table/format.h" +#include "util/coding.h" +#include "util/logging.h" + +namespace leveldb { + +inline uint32_t Block::NumRestarts() const { + assert(size_ >= sizeof(uint32_t)); + return DecodeFixed32(data_ + size_ - sizeof(uint32_t)); +} + +Block::Block(const BlockContents& contents) + : data_(contents.data.data()), + size_(contents.data.size()), + owned_(contents.heap_allocated) { + if (size_ < sizeof(uint32_t)) { + size_ = 0; // Error marker + } else { + size_t max_restarts_allowed = (size_-sizeof(uint32_t)) / sizeof(uint32_t); + if (NumRestarts() > max_restarts_allowed) { + // The size is too small for NumRestarts() + size_ = 0; + } else { + restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t); + } + } +} + +Block::~Block() { + if (owned_) { + delete[] data_; + } +} + +// Helper routine: decode the next block entry starting at "p", +// storing the number of shared key bytes, non_shared key bytes, +// and the length of the value in "*shared", "*non_shared", and +// "*value_length", respectively. Will not dereference past "limit". +// +// If any errors are detected, returns NULL. Otherwise, returns a +// pointer to the key delta (just past the three decoded values). +static inline const char* DecodeEntry(const char* p, const char* limit, + uint32_t* shared, + uint32_t* non_shared, + uint32_t* value_length) { + if (limit - p < 3) return NULL; + *shared = reinterpret_cast(p)[0]; + *non_shared = reinterpret_cast(p)[1]; + *value_length = reinterpret_cast(p)[2]; + if ((*shared | *non_shared | *value_length) < 128) { + // Fast path: all three values are encoded in one byte each + p += 3; + } else { + if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL; + if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL; + if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL; + } + + if (static_cast(limit - p) < (*non_shared + *value_length)) { + return NULL; + } + return p; +} + +class Block::Iter : public Iterator { + private: + const Comparator* const comparator_; + const char* const data_; // underlying block contents + uint32_t const restarts_; // Offset of restart array (list of fixed32) + uint32_t const num_restarts_; // Number of uint32_t entries in restart array + + // current_ is offset in data_ of current entry. >= restarts_ if !Valid + uint32_t current_; + uint32_t restart_index_; // Index of restart block in which current_ falls + std::string key_; + Slice value_; + Status status_; + + inline int Compare(const Slice& a, const Slice& b) const { + return comparator_->Compare(a, b); + } + + // Return the offset in data_ just past the end of the current entry. + inline uint32_t NextEntryOffset() const { + return (value_.data() + value_.size()) - data_; + } + + uint32_t GetRestartPoint(uint32_t index) { + assert(index < num_restarts_); + return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t)); + } + + void SeekToRestartPoint(uint32_t index) { + key_.clear(); + restart_index_ = index; + // current_ will be fixed by ParseNextKey(); + + // ParseNextKey() starts at the end of value_, so set value_ accordingly + uint32_t offset = GetRestartPoint(index); + value_ = Slice(data_ + offset, 0); + } + + public: + Iter(const Comparator* comparator, + const char* data, + uint32_t restarts, + uint32_t num_restarts) + : comparator_(comparator), + data_(data), + restarts_(restarts), + num_restarts_(num_restarts), + current_(restarts_), + restart_index_(num_restarts_) { + assert(num_restarts_ > 0); + } + + virtual bool Valid() const { return current_ < restarts_; } + virtual Status status() const { return status_; } + virtual Slice key() const { + assert(Valid()); + return key_; + } + virtual Slice value() const { + assert(Valid()); + return value_; + } + + virtual void Next() { + assert(Valid()); + ParseNextKey(); + } + + virtual void Prev() { + assert(Valid()); + + // Scan backwards to a restart point before current_ + const uint32_t original = current_; + while (GetRestartPoint(restart_index_) >= original) { + if (restart_index_ == 0) { + // No more entries + current_ = restarts_; + restart_index_ = num_restarts_; + return; + } + restart_index_--; + } + + SeekToRestartPoint(restart_index_); + do { + // Loop until end of current entry hits the start of original entry + } while (ParseNextKey() && NextEntryOffset() < original); + } + + virtual void Seek(const Slice& target) { + // Binary search in restart array to find the last restart point + // with a key < target + uint32_t left = 0; + uint32_t right = num_restarts_ - 1; + while (left < right) { + uint32_t mid = (left + right + 1) / 2; + uint32_t region_offset = GetRestartPoint(mid); + uint32_t shared, non_shared, value_length; + const char* key_ptr = DecodeEntry(data_ + region_offset, + data_ + restarts_, + &shared, &non_shared, &value_length); + if (key_ptr == NULL || (shared != 0)) { + CorruptionError(); + return; + } + Slice mid_key(key_ptr, non_shared); + if (Compare(mid_key, target) < 0) { + // Key at "mid" is smaller than "target". Therefore all + // blocks before "mid" are uninteresting. + left = mid; + } else { + // Key at "mid" is >= "target". Therefore all blocks at or + // after "mid" are uninteresting. + right = mid - 1; + } + } + + // Linear search (within restart block) for first key >= target + SeekToRestartPoint(left); + while (true) { + if (!ParseNextKey()) { + return; + } + if (Compare(key_, target) >= 0) { + return; + } + } + } + + virtual void SeekToFirst() { + SeekToRestartPoint(0); + ParseNextKey(); + } + + virtual void SeekToLast() { + SeekToRestartPoint(num_restarts_ - 1); + while (ParseNextKey() && NextEntryOffset() < restarts_) { + // Keep skipping + } + } + + private: + void CorruptionError() { + current_ = restarts_; + restart_index_ = num_restarts_; + status_ = Status::Corruption("bad entry in block"); + key_.clear(); + value_.clear(); + } + + bool ParseNextKey() { + current_ = NextEntryOffset(); + const char* p = data_ + current_; + const char* limit = data_ + restarts_; // Restarts come right after data + if (p >= limit) { + // No more entries to return. Mark as invalid. + current_ = restarts_; + restart_index_ = num_restarts_; + return false; + } + + // Decode next entry + uint32_t shared, non_shared, value_length; + p = DecodeEntry(p, limit, &shared, &non_shared, &value_length); + if (p == NULL || key_.size() < shared) { + CorruptionError(); + return false; + } else { + key_.resize(shared); + key_.append(p, non_shared); + value_ = Slice(p + non_shared, value_length); + while (restart_index_ + 1 < num_restarts_ && + GetRestartPoint(restart_index_ + 1) < current_) { + ++restart_index_; + } + return true; + } + } +}; + +Iterator* Block::NewIterator(const Comparator* cmp) { + if (size_ < sizeof(uint32_t)) { + return NewErrorIterator(Status::Corruption("bad block contents")); + } + const uint32_t num_restarts = NumRestarts(); + if (num_restarts == 0) { + return NewEmptyIterator(); + } else { + return new Iter(cmp, data_, restart_offset_, num_restarts); + } +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/block.h b/My Mind/Pods/leveldb-library/table/block.h new file mode 100644 index 0000000..2493eb9 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/block.h @@ -0,0 +1,44 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_BLOCK_H_ +#define STORAGE_LEVELDB_TABLE_BLOCK_H_ + +#include +#include +#include "leveldb/iterator.h" + +namespace leveldb { + +struct BlockContents; +class Comparator; + +class Block { + public: + // Initialize the block with the specified contents. + explicit Block(const BlockContents& contents); + + ~Block(); + + size_t size() const { return size_; } + Iterator* NewIterator(const Comparator* comparator); + + private: + uint32_t NumRestarts() const; + + const char* data_; + size_t size_; + uint32_t restart_offset_; // Offset in data_ of restart array + bool owned_; // Block owns data_[] + + // No copying allowed + Block(const Block&); + void operator=(const Block&); + + class Iter; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_BLOCK_H_ diff --git a/My Mind/Pods/leveldb-library/table/block_builder.cc b/My Mind/Pods/leveldb-library/table/block_builder.cc new file mode 100644 index 0000000..db660cd --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/block_builder.cc @@ -0,0 +1,109 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// BlockBuilder generates blocks where keys are prefix-compressed: +// +// When we store a key, we drop the prefix shared with the previous +// string. This helps reduce the space requirement significantly. +// Furthermore, once every K keys, we do not apply the prefix +// compression and store the entire key. We call this a "restart +// point". The tail end of the block stores the offsets of all of the +// restart points, and can be used to do a binary search when looking +// for a particular key. Values are stored as-is (without compression) +// immediately following the corresponding key. +// +// An entry for a particular key-value pair has the form: +// shared_bytes: varint32 +// unshared_bytes: varint32 +// value_length: varint32 +// key_delta: char[unshared_bytes] +// value: char[value_length] +// shared_bytes == 0 for restart points. +// +// The trailer of the block has the form: +// restarts: uint32[num_restarts] +// num_restarts: uint32 +// restarts[i] contains the offset within the block of the ith restart point. + +#include "table/block_builder.h" + +#include +#include +#include "leveldb/comparator.h" +#include "leveldb/table_builder.h" +#include "util/coding.h" + +namespace leveldb { + +BlockBuilder::BlockBuilder(const Options* options) + : options_(options), + restarts_(), + counter_(0), + finished_(false) { + assert(options->block_restart_interval >= 1); + restarts_.push_back(0); // First restart point is at offset 0 +} + +void BlockBuilder::Reset() { + buffer_.clear(); + restarts_.clear(); + restarts_.push_back(0); // First restart point is at offset 0 + counter_ = 0; + finished_ = false; + last_key_.clear(); +} + +size_t BlockBuilder::CurrentSizeEstimate() const { + return (buffer_.size() + // Raw data buffer + restarts_.size() * sizeof(uint32_t) + // Restart array + sizeof(uint32_t)); // Restart array length +} + +Slice BlockBuilder::Finish() { + // Append restart array + for (size_t i = 0; i < restarts_.size(); i++) { + PutFixed32(&buffer_, restarts_[i]); + } + PutFixed32(&buffer_, restarts_.size()); + finished_ = true; + return Slice(buffer_); +} + +void BlockBuilder::Add(const Slice& key, const Slice& value) { + Slice last_key_piece(last_key_); + assert(!finished_); + assert(counter_ <= options_->block_restart_interval); + assert(buffer_.empty() // No values yet? + || options_->comparator->Compare(key, last_key_piece) > 0); + size_t shared = 0; + if (counter_ < options_->block_restart_interval) { + // See how much sharing to do with previous string + const size_t min_length = std::min(last_key_piece.size(), key.size()); + while ((shared < min_length) && (last_key_piece[shared] == key[shared])) { + shared++; + } + } else { + // Restart compression + restarts_.push_back(buffer_.size()); + counter_ = 0; + } + const size_t non_shared = key.size() - shared; + + // Add "" to buffer_ + PutVarint32(&buffer_, shared); + PutVarint32(&buffer_, non_shared); + PutVarint32(&buffer_, value.size()); + + // Add string delta to buffer_ followed by value + buffer_.append(key.data() + shared, non_shared); + buffer_.append(value.data(), value.size()); + + // Update state + last_key_.resize(shared); + last_key_.append(key.data() + shared, non_shared); + assert(Slice(last_key_) == key); + counter_++; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/block_builder.h b/My Mind/Pods/leveldb-library/table/block_builder.h new file mode 100644 index 0000000..4fbcb33 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/block_builder.h @@ -0,0 +1,57 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_BLOCK_BUILDER_H_ +#define STORAGE_LEVELDB_TABLE_BLOCK_BUILDER_H_ + +#include + +#include +#include "leveldb/slice.h" + +namespace leveldb { + +struct Options; + +class BlockBuilder { + public: + explicit BlockBuilder(const Options* options); + + // Reset the contents as if the BlockBuilder was just constructed. + void Reset(); + + // REQUIRES: Finish() has not been called since the last call to Reset(). + // REQUIRES: key is larger than any previously added key + void Add(const Slice& key, const Slice& value); + + // Finish building the block and return a slice that refers to the + // block contents. The returned slice will remain valid for the + // lifetime of this builder or until Reset() is called. + Slice Finish(); + + // Returns an estimate of the current (uncompressed) size of the block + // we are building. + size_t CurrentSizeEstimate() const; + + // Return true iff no entries have been added since the last Reset() + bool empty() const { + return buffer_.empty(); + } + + private: + const Options* options_; + std::string buffer_; // Destination buffer + std::vector restarts_; // Restart points + int counter_; // Number of entries emitted since restart + bool finished_; // Has Finish() been called? + std::string last_key_; + + // No copying allowed + BlockBuilder(const BlockBuilder&); + void operator=(const BlockBuilder&); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_BLOCK_BUILDER_H_ diff --git a/My Mind/Pods/leveldb-library/table/filter_block.cc b/My Mind/Pods/leveldb-library/table/filter_block.cc new file mode 100644 index 0000000..1ed5134 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/filter_block.cc @@ -0,0 +1,111 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "table/filter_block.h" + +#include "leveldb/filter_policy.h" +#include "util/coding.h" + +namespace leveldb { + +// See doc/table_format.md for an explanation of the filter block format. + +// Generate new filter every 2KB of data +static const size_t kFilterBaseLg = 11; +static const size_t kFilterBase = 1 << kFilterBaseLg; + +FilterBlockBuilder::FilterBlockBuilder(const FilterPolicy* policy) + : policy_(policy) { +} + +void FilterBlockBuilder::StartBlock(uint64_t block_offset) { + uint64_t filter_index = (block_offset / kFilterBase); + assert(filter_index >= filter_offsets_.size()); + while (filter_index > filter_offsets_.size()) { + GenerateFilter(); + } +} + +void FilterBlockBuilder::AddKey(const Slice& key) { + Slice k = key; + start_.push_back(keys_.size()); + keys_.append(k.data(), k.size()); +} + +Slice FilterBlockBuilder::Finish() { + if (!start_.empty()) { + GenerateFilter(); + } + + // Append array of per-filter offsets + const uint32_t array_offset = result_.size(); + for (size_t i = 0; i < filter_offsets_.size(); i++) { + PutFixed32(&result_, filter_offsets_[i]); + } + + PutFixed32(&result_, array_offset); + result_.push_back(kFilterBaseLg); // Save encoding parameter in result + return Slice(result_); +} + +void FilterBlockBuilder::GenerateFilter() { + const size_t num_keys = start_.size(); + if (num_keys == 0) { + // Fast path if there are no keys for this filter + filter_offsets_.push_back(result_.size()); + return; + } + + // Make list of keys from flattened key structure + start_.push_back(keys_.size()); // Simplify length computation + tmp_keys_.resize(num_keys); + for (size_t i = 0; i < num_keys; i++) { + const char* base = keys_.data() + start_[i]; + size_t length = start_[i+1] - start_[i]; + tmp_keys_[i] = Slice(base, length); + } + + // Generate filter for current set of keys and append to result_. + filter_offsets_.push_back(result_.size()); + policy_->CreateFilter(&tmp_keys_[0], static_cast(num_keys), &result_); + + tmp_keys_.clear(); + keys_.clear(); + start_.clear(); +} + +FilterBlockReader::FilterBlockReader(const FilterPolicy* policy, + const Slice& contents) + : policy_(policy), + data_(NULL), + offset_(NULL), + num_(0), + base_lg_(0) { + size_t n = contents.size(); + if (n < 5) return; // 1 byte for base_lg_ and 4 for start of offset array + base_lg_ = contents[n-1]; + uint32_t last_word = DecodeFixed32(contents.data() + n - 5); + if (last_word > n - 5) return; + data_ = contents.data(); + offset_ = data_ + last_word; + num_ = (n - 5 - last_word) / 4; +} + +bool FilterBlockReader::KeyMayMatch(uint64_t block_offset, const Slice& key) { + uint64_t index = block_offset >> base_lg_; + if (index < num_) { + uint32_t start = DecodeFixed32(offset_ + index*4); + uint32_t limit = DecodeFixed32(offset_ + index*4 + 4); + if (start <= limit && limit <= static_cast(offset_ - data_)) { + Slice filter = Slice(data_ + start, limit - start); + return policy_->KeyMayMatch(key, filter); + } else if (start == limit) { + // Empty filters do not match any keys + return false; + } + } + return true; // Errors are treated as potential matches +} + +} diff --git a/My Mind/Pods/leveldb-library/table/filter_block.h b/My Mind/Pods/leveldb-library/table/filter_block.h new file mode 100644 index 0000000..c67d010 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/filter_block.h @@ -0,0 +1,68 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A filter block is stored near the end of a Table file. It contains +// filters (e.g., bloom filters) for all data blocks in the table combined +// into a single filter block. + +#ifndef STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_ +#define STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_ + +#include +#include +#include +#include +#include "leveldb/slice.h" +#include "util/hash.h" + +namespace leveldb { + +class FilterPolicy; + +// A FilterBlockBuilder is used to construct all of the filters for a +// particular Table. It generates a single string which is stored as +// a special block in the Table. +// +// The sequence of calls to FilterBlockBuilder must match the regexp: +// (StartBlock AddKey*)* Finish +class FilterBlockBuilder { + public: + explicit FilterBlockBuilder(const FilterPolicy*); + + void StartBlock(uint64_t block_offset); + void AddKey(const Slice& key); + Slice Finish(); + + private: + void GenerateFilter(); + + const FilterPolicy* policy_; + std::string keys_; // Flattened key contents + std::vector start_; // Starting index in keys_ of each key + std::string result_; // Filter data computed so far + std::vector tmp_keys_; // policy_->CreateFilter() argument + std::vector filter_offsets_; + + // No copying allowed + FilterBlockBuilder(const FilterBlockBuilder&); + void operator=(const FilterBlockBuilder&); +}; + +class FilterBlockReader { + public: + // REQUIRES: "contents" and *policy must stay live while *this is live. + FilterBlockReader(const FilterPolicy* policy, const Slice& contents); + bool KeyMayMatch(uint64_t block_offset, const Slice& key); + + private: + const FilterPolicy* policy_; + const char* data_; // Pointer to filter data (at block-start) + const char* offset_; // Pointer to beginning of offset array (at block-end) + size_t num_; // Number of entries in offset array + size_t base_lg_; // Encoding parameter (see kFilterBaseLg in .cc file) +}; + +} + +#endif // STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_ diff --git a/My Mind/Pods/leveldb-library/table/format.cc b/My Mind/Pods/leveldb-library/table/format.cc new file mode 100644 index 0000000..24e4e02 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/format.cc @@ -0,0 +1,144 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "table/format.h" + +#include "leveldb/env.h" +#include "port/port.h" +#include "table/block.h" +#include "util/coding.h" +#include "util/crc32c.h" + +namespace leveldb { + +void BlockHandle::EncodeTo(std::string* dst) const { + // Sanity check that all fields have been set + assert(offset_ != ~static_cast(0)); + assert(size_ != ~static_cast(0)); + PutVarint64(dst, offset_); + PutVarint64(dst, size_); +} + +Status BlockHandle::DecodeFrom(Slice* input) { + if (GetVarint64(input, &offset_) && + GetVarint64(input, &size_)) { + return Status::OK(); + } else { + return Status::Corruption("bad block handle"); + } +} + +void Footer::EncodeTo(std::string* dst) const { + const size_t original_size = dst->size(); + metaindex_handle_.EncodeTo(dst); + index_handle_.EncodeTo(dst); + dst->resize(2 * BlockHandle::kMaxEncodedLength); // Padding + PutFixed32(dst, static_cast(kTableMagicNumber & 0xffffffffu)); + PutFixed32(dst, static_cast(kTableMagicNumber >> 32)); + assert(dst->size() == original_size + kEncodedLength); + (void)original_size; // Disable unused variable warning. +} + +Status Footer::DecodeFrom(Slice* input) { + const char* magic_ptr = input->data() + kEncodedLength - 8; + const uint32_t magic_lo = DecodeFixed32(magic_ptr); + const uint32_t magic_hi = DecodeFixed32(magic_ptr + 4); + const uint64_t magic = ((static_cast(magic_hi) << 32) | + (static_cast(magic_lo))); + if (magic != kTableMagicNumber) { + return Status::Corruption("not an sstable (bad magic number)"); + } + + Status result = metaindex_handle_.DecodeFrom(input); + if (result.ok()) { + result = index_handle_.DecodeFrom(input); + } + if (result.ok()) { + // We skip over any leftover data (just padding for now) in "input" + const char* end = magic_ptr + 8; + *input = Slice(end, input->data() + input->size() - end); + } + return result; +} + +Status ReadBlock(RandomAccessFile* file, + const ReadOptions& options, + const BlockHandle& handle, + BlockContents* result) { + result->data = Slice(); + result->cachable = false; + result->heap_allocated = false; + + // Read the block contents as well as the type/crc footer. + // See table_builder.cc for the code that built this structure. + size_t n = static_cast(handle.size()); + char* buf = new char[n + kBlockTrailerSize]; + Slice contents; + Status s = file->Read(handle.offset(), n + kBlockTrailerSize, &contents, buf); + if (!s.ok()) { + delete[] buf; + return s; + } + if (contents.size() != n + kBlockTrailerSize) { + delete[] buf; + return Status::Corruption("truncated block read"); + } + + // Check the crc of the type and the block contents + const char* data = contents.data(); // Pointer to where Read put the data + if (options.verify_checksums) { + const uint32_t crc = crc32c::Unmask(DecodeFixed32(data + n + 1)); + const uint32_t actual = crc32c::Value(data, n + 1); + if (actual != crc) { + delete[] buf; + s = Status::Corruption("block checksum mismatch"); + return s; + } + } + + switch (data[n]) { + case kNoCompression: + if (data != buf) { + // File implementation gave us pointer to some other data. + // Use it directly under the assumption that it will be live + // while the file is open. + delete[] buf; + result->data = Slice(data, n); + result->heap_allocated = false; + result->cachable = false; // Do not double-cache + } else { + result->data = Slice(buf, n); + result->heap_allocated = true; + result->cachable = true; + } + + // Ok + break; + case kSnappyCompression: { + size_t ulength = 0; + if (!port::Snappy_GetUncompressedLength(data, n, &ulength)) { + delete[] buf; + return Status::Corruption("corrupted compressed block contents"); + } + char* ubuf = new char[ulength]; + if (!port::Snappy_Uncompress(data, n, ubuf)) { + delete[] buf; + delete[] ubuf; + return Status::Corruption("corrupted compressed block contents"); + } + delete[] buf; + result->data = Slice(ubuf, ulength); + result->heap_allocated = true; + result->cachable = true; + break; + } + default: + delete[] buf; + return Status::Corruption("bad block type"); + } + + return Status::OK(); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/format.h b/My Mind/Pods/leveldb-library/table/format.h new file mode 100644 index 0000000..6c0b80c --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/format.h @@ -0,0 +1,108 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_FORMAT_H_ +#define STORAGE_LEVELDB_TABLE_FORMAT_H_ + +#include +#include +#include "leveldb/slice.h" +#include "leveldb/status.h" +#include "leveldb/table_builder.h" + +namespace leveldb { + +class Block; +class RandomAccessFile; +struct ReadOptions; + +// BlockHandle is a pointer to the extent of a file that stores a data +// block or a meta block. +class BlockHandle { + public: + BlockHandle(); + + // The offset of the block in the file. + uint64_t offset() const { return offset_; } + void set_offset(uint64_t offset) { offset_ = offset; } + + // The size of the stored block + uint64_t size() const { return size_; } + void set_size(uint64_t size) { size_ = size; } + + void EncodeTo(std::string* dst) const; + Status DecodeFrom(Slice* input); + + // Maximum encoding length of a BlockHandle + enum { kMaxEncodedLength = 10 + 10 }; + + private: + uint64_t offset_; + uint64_t size_; +}; + +// Footer encapsulates the fixed information stored at the tail +// end of every table file. +class Footer { + public: + Footer() { } + + // The block handle for the metaindex block of the table + const BlockHandle& metaindex_handle() const { return metaindex_handle_; } + void set_metaindex_handle(const BlockHandle& h) { metaindex_handle_ = h; } + + // The block handle for the index block of the table + const BlockHandle& index_handle() const { + return index_handle_; + } + void set_index_handle(const BlockHandle& h) { + index_handle_ = h; + } + + void EncodeTo(std::string* dst) const; + Status DecodeFrom(Slice* input); + + // Encoded length of a Footer. Note that the serialization of a + // Footer will always occupy exactly this many bytes. It consists + // of two block handles and a magic number. + enum { + kEncodedLength = 2*BlockHandle::kMaxEncodedLength + 8 + }; + + private: + BlockHandle metaindex_handle_; + BlockHandle index_handle_; +}; + +// kTableMagicNumber was picked by running +// echo http://code.google.com/p/leveldb/ | sha1sum +// and taking the leading 64 bits. +static const uint64_t kTableMagicNumber = 0xdb4775248b80fb57ull; + +// 1-byte type + 32-bit crc +static const size_t kBlockTrailerSize = 5; + +struct BlockContents { + Slice data; // Actual contents of data + bool cachable; // True iff data can be cached + bool heap_allocated; // True iff caller should delete[] data.data() +}; + +// Read the block identified by "handle" from "file". On failure +// return non-OK. On success fill *result and return OK. +extern Status ReadBlock(RandomAccessFile* file, + const ReadOptions& options, + const BlockHandle& handle, + BlockContents* result); + +// Implementation details follow. Clients should ignore, + +inline BlockHandle::BlockHandle() + : offset_(~static_cast(0)), + size_(~static_cast(0)) { +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_FORMAT_H_ diff --git a/My Mind/Pods/leveldb-library/table/iterator.cc b/My Mind/Pods/leveldb-library/table/iterator.cc new file mode 100644 index 0000000..3d1c87f --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/iterator.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/iterator.h" + +namespace leveldb { + +Iterator::Iterator() { + cleanup_.function = NULL; + cleanup_.next = NULL; +} + +Iterator::~Iterator() { + if (cleanup_.function != NULL) { + (*cleanup_.function)(cleanup_.arg1, cleanup_.arg2); + for (Cleanup* c = cleanup_.next; c != NULL; ) { + (*c->function)(c->arg1, c->arg2); + Cleanup* next = c->next; + delete c; + c = next; + } + } +} + +void Iterator::RegisterCleanup(CleanupFunction func, void* arg1, void* arg2) { + assert(func != NULL); + Cleanup* c; + if (cleanup_.function == NULL) { + c = &cleanup_; + } else { + c = new Cleanup; + c->next = cleanup_.next; + cleanup_.next = c; + } + c->function = func; + c->arg1 = arg1; + c->arg2 = arg2; +} + +namespace { +class EmptyIterator : public Iterator { + public: + EmptyIterator(const Status& s) : status_(s) { } + virtual bool Valid() const { return false; } + virtual void Seek(const Slice& target) { } + virtual void SeekToFirst() { } + virtual void SeekToLast() { } + virtual void Next() { assert(false); } + virtual void Prev() { assert(false); } + Slice key() const { assert(false); return Slice(); } + Slice value() const { assert(false); return Slice(); } + virtual Status status() const { return status_; } + private: + Status status_; +}; +} // namespace + +Iterator* NewEmptyIterator() { + return new EmptyIterator(Status::OK()); +} + +Iterator* NewErrorIterator(const Status& status) { + return new EmptyIterator(status); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/iterator_wrapper.h b/My Mind/Pods/leveldb-library/table/iterator_wrapper.h new file mode 100644 index 0000000..f410c3f --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/iterator_wrapper.h @@ -0,0 +1,66 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_ +#define STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_ + +#include "leveldb/iterator.h" +#include "leveldb/slice.h" + +namespace leveldb { + +// A internal wrapper class with an interface similar to Iterator that +// caches the valid() and key() results for an underlying iterator. +// This can help avoid virtual function calls and also gives better +// cache locality. +class IteratorWrapper { + public: + IteratorWrapper(): iter_(NULL), valid_(false) { } + explicit IteratorWrapper(Iterator* iter): iter_(NULL) { + Set(iter); + } + ~IteratorWrapper() { delete iter_; } + Iterator* iter() const { return iter_; } + + // Takes ownership of "iter" and will delete it when destroyed, or + // when Set() is invoked again. + void Set(Iterator* iter) { + delete iter_; + iter_ = iter; + if (iter_ == NULL) { + valid_ = false; + } else { + Update(); + } + } + + + // Iterator interface methods + bool Valid() const { return valid_; } + Slice key() const { assert(Valid()); return key_; } + Slice value() const { assert(Valid()); return iter_->value(); } + // Methods below require iter() != NULL + Status status() const { assert(iter_); return iter_->status(); } + void Next() { assert(iter_); iter_->Next(); Update(); } + void Prev() { assert(iter_); iter_->Prev(); Update(); } + void Seek(const Slice& k) { assert(iter_); iter_->Seek(k); Update(); } + void SeekToFirst() { assert(iter_); iter_->SeekToFirst(); Update(); } + void SeekToLast() { assert(iter_); iter_->SeekToLast(); Update(); } + + private: + void Update() { + valid_ = iter_->Valid(); + if (valid_) { + key_ = iter_->key(); + } + } + + Iterator* iter_; + bool valid_; + Slice key_; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_ITERATOR_WRAPPER_H_ diff --git a/My Mind/Pods/leveldb-library/table/merger.cc b/My Mind/Pods/leveldb-library/table/merger.cc new file mode 100644 index 0000000..2dde4dc --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/merger.cc @@ -0,0 +1,197 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "table/merger.h" + +#include "leveldb/comparator.h" +#include "leveldb/iterator.h" +#include "table/iterator_wrapper.h" + +namespace leveldb { + +namespace { +class MergingIterator : public Iterator { + public: + MergingIterator(const Comparator* comparator, Iterator** children, int n) + : comparator_(comparator), + children_(new IteratorWrapper[n]), + n_(n), + current_(NULL), + direction_(kForward) { + for (int i = 0; i < n; i++) { + children_[i].Set(children[i]); + } + } + + virtual ~MergingIterator() { + delete[] children_; + } + + virtual bool Valid() const { + return (current_ != NULL); + } + + virtual void SeekToFirst() { + for (int i = 0; i < n_; i++) { + children_[i].SeekToFirst(); + } + FindSmallest(); + direction_ = kForward; + } + + virtual void SeekToLast() { + for (int i = 0; i < n_; i++) { + children_[i].SeekToLast(); + } + FindLargest(); + direction_ = kReverse; + } + + virtual void Seek(const Slice& target) { + for (int i = 0; i < n_; i++) { + children_[i].Seek(target); + } + FindSmallest(); + direction_ = kForward; + } + + virtual void Next() { + assert(Valid()); + + // Ensure that all children are positioned after key(). + // If we are moving in the forward direction, it is already + // true for all of the non-current_ children since current_ is + // the smallest child and key() == current_->key(). Otherwise, + // we explicitly position the non-current_ children. + if (direction_ != kForward) { + for (int i = 0; i < n_; i++) { + IteratorWrapper* child = &children_[i]; + if (child != current_) { + child->Seek(key()); + if (child->Valid() && + comparator_->Compare(key(), child->key()) == 0) { + child->Next(); + } + } + } + direction_ = kForward; + } + + current_->Next(); + FindSmallest(); + } + + virtual void Prev() { + assert(Valid()); + + // Ensure that all children are positioned before key(). + // If we are moving in the reverse direction, it is already + // true for all of the non-current_ children since current_ is + // the largest child and key() == current_->key(). Otherwise, + // we explicitly position the non-current_ children. + if (direction_ != kReverse) { + for (int i = 0; i < n_; i++) { + IteratorWrapper* child = &children_[i]; + if (child != current_) { + child->Seek(key()); + if (child->Valid()) { + // Child is at first entry >= key(). Step back one to be < key() + child->Prev(); + } else { + // Child has no entries >= key(). Position at last entry. + child->SeekToLast(); + } + } + } + direction_ = kReverse; + } + + current_->Prev(); + FindLargest(); + } + + virtual Slice key() const { + assert(Valid()); + return current_->key(); + } + + virtual Slice value() const { + assert(Valid()); + return current_->value(); + } + + virtual Status status() const { + Status status; + for (int i = 0; i < n_; i++) { + status = children_[i].status(); + if (!status.ok()) { + break; + } + } + return status; + } + + private: + void FindSmallest(); + void FindLargest(); + + // We might want to use a heap in case there are lots of children. + // For now we use a simple array since we expect a very small number + // of children in leveldb. + const Comparator* comparator_; + IteratorWrapper* children_; + int n_; + IteratorWrapper* current_; + + // Which direction is the iterator moving? + enum Direction { + kForward, + kReverse + }; + Direction direction_; +}; + +void MergingIterator::FindSmallest() { + IteratorWrapper* smallest = NULL; + for (int i = 0; i < n_; i++) { + IteratorWrapper* child = &children_[i]; + if (child->Valid()) { + if (smallest == NULL) { + smallest = child; + } else if (comparator_->Compare(child->key(), smallest->key()) < 0) { + smallest = child; + } + } + } + current_ = smallest; +} + +void MergingIterator::FindLargest() { + IteratorWrapper* largest = NULL; + for (int i = n_-1; i >= 0; i--) { + IteratorWrapper* child = &children_[i]; + if (child->Valid()) { + if (largest == NULL) { + largest = child; + } else if (comparator_->Compare(child->key(), largest->key()) > 0) { + largest = child; + } + } + } + current_ = largest; +} +} // namespace + +Iterator* NewMergingIterator(const Comparator* cmp, Iterator** list, int n) { + assert(n >= 0); + if (n == 0) { + return NewEmptyIterator(); + } else if (n == 1) { + return list[0]; + } else { + return new MergingIterator(cmp, list, n); + } +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/merger.h b/My Mind/Pods/leveldb-library/table/merger.h new file mode 100644 index 0000000..91ddd80 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/merger.h @@ -0,0 +1,26 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_MERGER_H_ +#define STORAGE_LEVELDB_TABLE_MERGER_H_ + +namespace leveldb { + +class Comparator; +class Iterator; + +// Return an iterator that provided the union of the data in +// children[0,n-1]. Takes ownership of the child iterators and +// will delete them when the result iterator is deleted. +// +// The result does no duplicate suppression. I.e., if a particular +// key is present in K child iterators, it will be yielded K times. +// +// REQUIRES: n >= 0 +extern Iterator* NewMergingIterator( + const Comparator* comparator, Iterator** children, int n); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_MERGER_H_ diff --git a/My Mind/Pods/leveldb-library/table/table.cc b/My Mind/Pods/leveldb-library/table/table.cc new file mode 100644 index 0000000..decf808 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/table.cc @@ -0,0 +1,285 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/table.h" + +#include "leveldb/cache.h" +#include "leveldb/comparator.h" +#include "leveldb/env.h" +#include "leveldb/filter_policy.h" +#include "leveldb/options.h" +#include "table/block.h" +#include "table/filter_block.h" +#include "table/format.h" +#include "table/two_level_iterator.h" +#include "util/coding.h" + +namespace leveldb { + +struct Table::Rep { + ~Rep() { + delete filter; + delete [] filter_data; + delete index_block; + } + + Options options; + Status status; + RandomAccessFile* file; + uint64_t cache_id; + FilterBlockReader* filter; + const char* filter_data; + + BlockHandle metaindex_handle; // Handle to metaindex_block: saved from footer + Block* index_block; +}; + +Status Table::Open(const Options& options, + RandomAccessFile* file, + uint64_t size, + Table** table) { + *table = NULL; + if (size < Footer::kEncodedLength) { + return Status::Corruption("file is too short to be an sstable"); + } + + char footer_space[Footer::kEncodedLength]; + Slice footer_input; + Status s = file->Read(size - Footer::kEncodedLength, Footer::kEncodedLength, + &footer_input, footer_space); + if (!s.ok()) return s; + + Footer footer; + s = footer.DecodeFrom(&footer_input); + if (!s.ok()) return s; + + // Read the index block + BlockContents contents; + Block* index_block = NULL; + if (s.ok()) { + ReadOptions opt; + if (options.paranoid_checks) { + opt.verify_checksums = true; + } + s = ReadBlock(file, opt, footer.index_handle(), &contents); + if (s.ok()) { + index_block = new Block(contents); + } + } + + if (s.ok()) { + // We've successfully read the footer and the index block: we're + // ready to serve requests. + Rep* rep = new Table::Rep; + rep->options = options; + rep->file = file; + rep->metaindex_handle = footer.metaindex_handle(); + rep->index_block = index_block; + rep->cache_id = (options.block_cache ? options.block_cache->NewId() : 0); + rep->filter_data = NULL; + rep->filter = NULL; + *table = new Table(rep); + (*table)->ReadMeta(footer); + } else { + delete index_block; + } + + return s; +} + +void Table::ReadMeta(const Footer& footer) { + if (rep_->options.filter_policy == NULL) { + return; // Do not need any metadata + } + + // TODO(sanjay): Skip this if footer.metaindex_handle() size indicates + // it is an empty block. + ReadOptions opt; + if (rep_->options.paranoid_checks) { + opt.verify_checksums = true; + } + BlockContents contents; + if (!ReadBlock(rep_->file, opt, footer.metaindex_handle(), &contents).ok()) { + // Do not propagate errors since meta info is not needed for operation + return; + } + Block* meta = new Block(contents); + + Iterator* iter = meta->NewIterator(BytewiseComparator()); + std::string key = "filter."; + key.append(rep_->options.filter_policy->Name()); + iter->Seek(key); + if (iter->Valid() && iter->key() == Slice(key)) { + ReadFilter(iter->value()); + } + delete iter; + delete meta; +} + +void Table::ReadFilter(const Slice& filter_handle_value) { + Slice v = filter_handle_value; + BlockHandle filter_handle; + if (!filter_handle.DecodeFrom(&v).ok()) { + return; + } + + // We might want to unify with ReadBlock() if we start + // requiring checksum verification in Table::Open. + ReadOptions opt; + if (rep_->options.paranoid_checks) { + opt.verify_checksums = true; + } + BlockContents block; + if (!ReadBlock(rep_->file, opt, filter_handle, &block).ok()) { + return; + } + if (block.heap_allocated) { + rep_->filter_data = block.data.data(); // Will need to delete later + } + rep_->filter = new FilterBlockReader(rep_->options.filter_policy, block.data); +} + +Table::~Table() { + delete rep_; +} + +static void DeleteBlock(void* arg, void* ignored) { + delete reinterpret_cast(arg); +} + +static void DeleteCachedBlock(const Slice& key, void* value) { + Block* block = reinterpret_cast(value); + delete block; +} + +static void ReleaseBlock(void* arg, void* h) { + Cache* cache = reinterpret_cast(arg); + Cache::Handle* handle = reinterpret_cast(h); + cache->Release(handle); +} + +// Convert an index iterator value (i.e., an encoded BlockHandle) +// into an iterator over the contents of the corresponding block. +Iterator* Table::BlockReader(void* arg, + const ReadOptions& options, + const Slice& index_value) { + Table* table = reinterpret_cast(arg); + Cache* block_cache = table->rep_->options.block_cache; + Block* block = NULL; + Cache::Handle* cache_handle = NULL; + + BlockHandle handle; + Slice input = index_value; + Status s = handle.DecodeFrom(&input); + // We intentionally allow extra stuff in index_value so that we + // can add more features in the future. + + if (s.ok()) { + BlockContents contents; + if (block_cache != NULL) { + char cache_key_buffer[16]; + EncodeFixed64(cache_key_buffer, table->rep_->cache_id); + EncodeFixed64(cache_key_buffer+8, handle.offset()); + Slice key(cache_key_buffer, sizeof(cache_key_buffer)); + cache_handle = block_cache->Lookup(key); + if (cache_handle != NULL) { + block = reinterpret_cast(block_cache->Value(cache_handle)); + } else { + s = ReadBlock(table->rep_->file, options, handle, &contents); + if (s.ok()) { + block = new Block(contents); + if (contents.cachable && options.fill_cache) { + cache_handle = block_cache->Insert( + key, block, block->size(), &DeleteCachedBlock); + } + } + } + } else { + s = ReadBlock(table->rep_->file, options, handle, &contents); + if (s.ok()) { + block = new Block(contents); + } + } + } + + Iterator* iter; + if (block != NULL) { + iter = block->NewIterator(table->rep_->options.comparator); + if (cache_handle == NULL) { + iter->RegisterCleanup(&DeleteBlock, block, NULL); + } else { + iter->RegisterCleanup(&ReleaseBlock, block_cache, cache_handle); + } + } else { + iter = NewErrorIterator(s); + } + return iter; +} + +Iterator* Table::NewIterator(const ReadOptions& options) const { + return NewTwoLevelIterator( + rep_->index_block->NewIterator(rep_->options.comparator), + &Table::BlockReader, const_cast(this), options); +} + +Status Table::InternalGet(const ReadOptions& options, const Slice& k, + void* arg, + void (*saver)(void*, const Slice&, const Slice&)) { + Status s; + Iterator* iiter = rep_->index_block->NewIterator(rep_->options.comparator); + iiter->Seek(k); + if (iiter->Valid()) { + Slice handle_value = iiter->value(); + FilterBlockReader* filter = rep_->filter; + BlockHandle handle; + if (filter != NULL && + handle.DecodeFrom(&handle_value).ok() && + !filter->KeyMayMatch(handle.offset(), k)) { + // Not found + } else { + Iterator* block_iter = BlockReader(this, options, iiter->value()); + block_iter->Seek(k); + if (block_iter->Valid()) { + (*saver)(arg, block_iter->key(), block_iter->value()); + } + s = block_iter->status(); + delete block_iter; + } + } + if (s.ok()) { + s = iiter->status(); + } + delete iiter; + return s; +} + + +uint64_t Table::ApproximateOffsetOf(const Slice& key) const { + Iterator* index_iter = + rep_->index_block->NewIterator(rep_->options.comparator); + index_iter->Seek(key); + uint64_t result; + if (index_iter->Valid()) { + BlockHandle handle; + Slice input = index_iter->value(); + Status s = handle.DecodeFrom(&input); + if (s.ok()) { + result = handle.offset(); + } else { + // Strange: we can't decode the block handle in the index block. + // We'll just return the offset of the metaindex block, which is + // close to the whole file size for this case. + result = rep_->metaindex_handle.offset(); + } + } else { + // key is past the last key in the file. Approximate the offset + // by returning the offset of the metaindex block (which is + // right near the end of the file). + result = rep_->metaindex_handle.offset(); + } + delete index_iter; + return result; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/table_builder.cc b/My Mind/Pods/leveldb-library/table/table_builder.cc new file mode 100644 index 0000000..62002c8 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/table_builder.cc @@ -0,0 +1,270 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/table_builder.h" + +#include +#include "leveldb/comparator.h" +#include "leveldb/env.h" +#include "leveldb/filter_policy.h" +#include "leveldb/options.h" +#include "table/block_builder.h" +#include "table/filter_block.h" +#include "table/format.h" +#include "util/coding.h" +#include "util/crc32c.h" + +namespace leveldb { + +struct TableBuilder::Rep { + Options options; + Options index_block_options; + WritableFile* file; + uint64_t offset; + Status status; + BlockBuilder data_block; + BlockBuilder index_block; + std::string last_key; + int64_t num_entries; + bool closed; // Either Finish() or Abandon() has been called. + FilterBlockBuilder* filter_block; + + // We do not emit the index entry for a block until we have seen the + // first key for the next data block. This allows us to use shorter + // keys in the index block. For example, consider a block boundary + // between the keys "the quick brown fox" and "the who". We can use + // "the r" as the key for the index block entry since it is >= all + // entries in the first block and < all entries in subsequent + // blocks. + // + // Invariant: r->pending_index_entry is true only if data_block is empty. + bool pending_index_entry; + BlockHandle pending_handle; // Handle to add to index block + + std::string compressed_output; + + Rep(const Options& opt, WritableFile* f) + : options(opt), + index_block_options(opt), + file(f), + offset(0), + data_block(&options), + index_block(&index_block_options), + num_entries(0), + closed(false), + filter_block(opt.filter_policy == NULL ? NULL + : new FilterBlockBuilder(opt.filter_policy)), + pending_index_entry(false) { + index_block_options.block_restart_interval = 1; + } +}; + +TableBuilder::TableBuilder(const Options& options, WritableFile* file) + : rep_(new Rep(options, file)) { + if (rep_->filter_block != NULL) { + rep_->filter_block->StartBlock(0); + } +} + +TableBuilder::~TableBuilder() { + assert(rep_->closed); // Catch errors where caller forgot to call Finish() + delete rep_->filter_block; + delete rep_; +} + +Status TableBuilder::ChangeOptions(const Options& options) { + // Note: if more fields are added to Options, update + // this function to catch changes that should not be allowed to + // change in the middle of building a Table. + if (options.comparator != rep_->options.comparator) { + return Status::InvalidArgument("changing comparator while building table"); + } + + // Note that any live BlockBuilders point to rep_->options and therefore + // will automatically pick up the updated options. + rep_->options = options; + rep_->index_block_options = options; + rep_->index_block_options.block_restart_interval = 1; + return Status::OK(); +} + +void TableBuilder::Add(const Slice& key, const Slice& value) { + Rep* r = rep_; + assert(!r->closed); + if (!ok()) return; + if (r->num_entries > 0) { + assert(r->options.comparator->Compare(key, Slice(r->last_key)) > 0); + } + + if (r->pending_index_entry) { + assert(r->data_block.empty()); + r->options.comparator->FindShortestSeparator(&r->last_key, key); + std::string handle_encoding; + r->pending_handle.EncodeTo(&handle_encoding); + r->index_block.Add(r->last_key, Slice(handle_encoding)); + r->pending_index_entry = false; + } + + if (r->filter_block != NULL) { + r->filter_block->AddKey(key); + } + + r->last_key.assign(key.data(), key.size()); + r->num_entries++; + r->data_block.Add(key, value); + + const size_t estimated_block_size = r->data_block.CurrentSizeEstimate(); + if (estimated_block_size >= r->options.block_size) { + Flush(); + } +} + +void TableBuilder::Flush() { + Rep* r = rep_; + assert(!r->closed); + if (!ok()) return; + if (r->data_block.empty()) return; + assert(!r->pending_index_entry); + WriteBlock(&r->data_block, &r->pending_handle); + if (ok()) { + r->pending_index_entry = true; + r->status = r->file->Flush(); + } + if (r->filter_block != NULL) { + r->filter_block->StartBlock(r->offset); + } +} + +void TableBuilder::WriteBlock(BlockBuilder* block, BlockHandle* handle) { + // File format contains a sequence of blocks where each block has: + // block_data: uint8[n] + // type: uint8 + // crc: uint32 + assert(ok()); + Rep* r = rep_; + Slice raw = block->Finish(); + + Slice block_contents; + CompressionType type = r->options.compression; + // TODO(postrelease): Support more compression options: zlib? + switch (type) { + case kNoCompression: + block_contents = raw; + break; + + case kSnappyCompression: { + std::string* compressed = &r->compressed_output; + if (port::Snappy_Compress(raw.data(), raw.size(), compressed) && + compressed->size() < raw.size() - (raw.size() / 8u)) { + block_contents = *compressed; + } else { + // Snappy not supported, or compressed less than 12.5%, so just + // store uncompressed form + block_contents = raw; + type = kNoCompression; + } + break; + } + } + WriteRawBlock(block_contents, type, handle); + r->compressed_output.clear(); + block->Reset(); +} + +void TableBuilder::WriteRawBlock(const Slice& block_contents, + CompressionType type, + BlockHandle* handle) { + Rep* r = rep_; + handle->set_offset(r->offset); + handle->set_size(block_contents.size()); + r->status = r->file->Append(block_contents); + if (r->status.ok()) { + char trailer[kBlockTrailerSize]; + trailer[0] = type; + uint32_t crc = crc32c::Value(block_contents.data(), block_contents.size()); + crc = crc32c::Extend(crc, trailer, 1); // Extend crc to cover block type + EncodeFixed32(trailer+1, crc32c::Mask(crc)); + r->status = r->file->Append(Slice(trailer, kBlockTrailerSize)); + if (r->status.ok()) { + r->offset += block_contents.size() + kBlockTrailerSize; + } + } +} + +Status TableBuilder::status() const { + return rep_->status; +} + +Status TableBuilder::Finish() { + Rep* r = rep_; + Flush(); + assert(!r->closed); + r->closed = true; + + BlockHandle filter_block_handle, metaindex_block_handle, index_block_handle; + + // Write filter block + if (ok() && r->filter_block != NULL) { + WriteRawBlock(r->filter_block->Finish(), kNoCompression, + &filter_block_handle); + } + + // Write metaindex block + if (ok()) { + BlockBuilder meta_index_block(&r->options); + if (r->filter_block != NULL) { + // Add mapping from "filter.Name" to location of filter data + std::string key = "filter."; + key.append(r->options.filter_policy->Name()); + std::string handle_encoding; + filter_block_handle.EncodeTo(&handle_encoding); + meta_index_block.Add(key, handle_encoding); + } + + // TODO(postrelease): Add stats and other meta blocks + WriteBlock(&meta_index_block, &metaindex_block_handle); + } + + // Write index block + if (ok()) { + if (r->pending_index_entry) { + r->options.comparator->FindShortSuccessor(&r->last_key); + std::string handle_encoding; + r->pending_handle.EncodeTo(&handle_encoding); + r->index_block.Add(r->last_key, Slice(handle_encoding)); + r->pending_index_entry = false; + } + WriteBlock(&r->index_block, &index_block_handle); + } + + // Write footer + if (ok()) { + Footer footer; + footer.set_metaindex_handle(metaindex_block_handle); + footer.set_index_handle(index_block_handle); + std::string footer_encoding; + footer.EncodeTo(&footer_encoding); + r->status = r->file->Append(footer_encoding); + if (r->status.ok()) { + r->offset += footer_encoding.size(); + } + } + return r->status; +} + +void TableBuilder::Abandon() { + Rep* r = rep_; + assert(!r->closed); + r->closed = true; +} + +uint64_t TableBuilder::NumEntries() const { + return rep_->num_entries; +} + +uint64_t TableBuilder::FileSize() const { + return rep_->offset; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/two_level_iterator.cc b/My Mind/Pods/leveldb-library/table/two_level_iterator.cc new file mode 100644 index 0000000..7822eba --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/two_level_iterator.cc @@ -0,0 +1,182 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "table/two_level_iterator.h" + +#include "leveldb/table.h" +#include "table/block.h" +#include "table/format.h" +#include "table/iterator_wrapper.h" + +namespace leveldb { + +namespace { + +typedef Iterator* (*BlockFunction)(void*, const ReadOptions&, const Slice&); + +class TwoLevelIterator: public Iterator { + public: + TwoLevelIterator( + Iterator* index_iter, + BlockFunction block_function, + void* arg, + const ReadOptions& options); + + virtual ~TwoLevelIterator(); + + virtual void Seek(const Slice& target); + virtual void SeekToFirst(); + virtual void SeekToLast(); + virtual void Next(); + virtual void Prev(); + + virtual bool Valid() const { + return data_iter_.Valid(); + } + virtual Slice key() const { + assert(Valid()); + return data_iter_.key(); + } + virtual Slice value() const { + assert(Valid()); + return data_iter_.value(); + } + virtual Status status() const { + // It'd be nice if status() returned a const Status& instead of a Status + if (!index_iter_.status().ok()) { + return index_iter_.status(); + } else if (data_iter_.iter() != NULL && !data_iter_.status().ok()) { + return data_iter_.status(); + } else { + return status_; + } + } + + private: + void SaveError(const Status& s) { + if (status_.ok() && !s.ok()) status_ = s; + } + void SkipEmptyDataBlocksForward(); + void SkipEmptyDataBlocksBackward(); + void SetDataIterator(Iterator* data_iter); + void InitDataBlock(); + + BlockFunction block_function_; + void* arg_; + const ReadOptions options_; + Status status_; + IteratorWrapper index_iter_; + IteratorWrapper data_iter_; // May be NULL + // If data_iter_ is non-NULL, then "data_block_handle_" holds the + // "index_value" passed to block_function_ to create the data_iter_. + std::string data_block_handle_; +}; + +TwoLevelIterator::TwoLevelIterator( + Iterator* index_iter, + BlockFunction block_function, + void* arg, + const ReadOptions& options) + : block_function_(block_function), + arg_(arg), + options_(options), + index_iter_(index_iter), + data_iter_(NULL) { +} + +TwoLevelIterator::~TwoLevelIterator() { +} + +void TwoLevelIterator::Seek(const Slice& target) { + index_iter_.Seek(target); + InitDataBlock(); + if (data_iter_.iter() != NULL) data_iter_.Seek(target); + SkipEmptyDataBlocksForward(); +} + +void TwoLevelIterator::SeekToFirst() { + index_iter_.SeekToFirst(); + InitDataBlock(); + if (data_iter_.iter() != NULL) data_iter_.SeekToFirst(); + SkipEmptyDataBlocksForward(); +} + +void TwoLevelIterator::SeekToLast() { + index_iter_.SeekToLast(); + InitDataBlock(); + if (data_iter_.iter() != NULL) data_iter_.SeekToLast(); + SkipEmptyDataBlocksBackward(); +} + +void TwoLevelIterator::Next() { + assert(Valid()); + data_iter_.Next(); + SkipEmptyDataBlocksForward(); +} + +void TwoLevelIterator::Prev() { + assert(Valid()); + data_iter_.Prev(); + SkipEmptyDataBlocksBackward(); +} + + +void TwoLevelIterator::SkipEmptyDataBlocksForward() { + while (data_iter_.iter() == NULL || !data_iter_.Valid()) { + // Move to next block + if (!index_iter_.Valid()) { + SetDataIterator(NULL); + return; + } + index_iter_.Next(); + InitDataBlock(); + if (data_iter_.iter() != NULL) data_iter_.SeekToFirst(); + } +} + +void TwoLevelIterator::SkipEmptyDataBlocksBackward() { + while (data_iter_.iter() == NULL || !data_iter_.Valid()) { + // Move to next block + if (!index_iter_.Valid()) { + SetDataIterator(NULL); + return; + } + index_iter_.Prev(); + InitDataBlock(); + if (data_iter_.iter() != NULL) data_iter_.SeekToLast(); + } +} + +void TwoLevelIterator::SetDataIterator(Iterator* data_iter) { + if (data_iter_.iter() != NULL) SaveError(data_iter_.status()); + data_iter_.Set(data_iter); +} + +void TwoLevelIterator::InitDataBlock() { + if (!index_iter_.Valid()) { + SetDataIterator(NULL); + } else { + Slice handle = index_iter_.value(); + if (data_iter_.iter() != NULL && handle.compare(data_block_handle_) == 0) { + // data_iter_ is already constructed with this iterator, so + // no need to change anything + } else { + Iterator* iter = (*block_function_)(arg_, options_, handle); + data_block_handle_.assign(handle.data(), handle.size()); + SetDataIterator(iter); + } + } +} + +} // namespace + +Iterator* NewTwoLevelIterator( + Iterator* index_iter, + BlockFunction block_function, + void* arg, + const ReadOptions& options) { + return new TwoLevelIterator(index_iter, block_function, arg, options); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/table/two_level_iterator.h b/My Mind/Pods/leveldb-library/table/two_level_iterator.h new file mode 100644 index 0000000..629ca34 --- /dev/null +++ b/My Mind/Pods/leveldb-library/table/two_level_iterator.h @@ -0,0 +1,34 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_ +#define STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_ + +#include "leveldb/iterator.h" + +namespace leveldb { + +struct ReadOptions; + +// Return a new two level iterator. A two-level iterator contains an +// index iterator whose values point to a sequence of blocks where +// each block is itself a sequence of key,value pairs. The returned +// two-level iterator yields the concatenation of all key/value pairs +// in the sequence of blocks. Takes ownership of "index_iter" and +// will delete it when no longer needed. +// +// Uses a supplied function to convert an index_iter value into +// an iterator over the contents of the corresponding block. +extern Iterator* NewTwoLevelIterator( + Iterator* index_iter, + Iterator* (*block_function)( + void* arg, + const ReadOptions& options, + const Slice& index_value), + void* arg, + const ReadOptions& options); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_ diff --git a/My Mind/Pods/leveldb-library/util/arena.cc b/My Mind/Pods/leveldb-library/util/arena.cc new file mode 100644 index 0000000..7407821 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/arena.cc @@ -0,0 +1,68 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "util/arena.h" +#include + +namespace leveldb { + +static const int kBlockSize = 4096; + +Arena::Arena() : memory_usage_(0) { + alloc_ptr_ = NULL; // First allocation will allocate a block + alloc_bytes_remaining_ = 0; +} + +Arena::~Arena() { + for (size_t i = 0; i < blocks_.size(); i++) { + delete[] blocks_[i]; + } +} + +char* Arena::AllocateFallback(size_t bytes) { + if (bytes > kBlockSize / 4) { + // Object is more than a quarter of our block size. Allocate it separately + // to avoid wasting too much space in leftover bytes. + char* result = AllocateNewBlock(bytes); + return result; + } + + // We waste the remaining space in the current block. + alloc_ptr_ = AllocateNewBlock(kBlockSize); + alloc_bytes_remaining_ = kBlockSize; + + char* result = alloc_ptr_; + alloc_ptr_ += bytes; + alloc_bytes_remaining_ -= bytes; + return result; +} + +char* Arena::AllocateAligned(size_t bytes) { + const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8; + assert((align & (align-1)) == 0); // Pointer size should be a power of 2 + size_t current_mod = reinterpret_cast(alloc_ptr_) & (align-1); + size_t slop = (current_mod == 0 ? 0 : align - current_mod); + size_t needed = bytes + slop; + char* result; + if (needed <= alloc_bytes_remaining_) { + result = alloc_ptr_ + slop; + alloc_ptr_ += needed; + alloc_bytes_remaining_ -= needed; + } else { + // AllocateFallback always returned aligned memory + result = AllocateFallback(bytes); + } + assert((reinterpret_cast(result) & (align-1)) == 0); + return result; +} + +char* Arena::AllocateNewBlock(size_t block_bytes) { + char* result = new char[block_bytes]; + blocks_.push_back(result); + memory_usage_.NoBarrier_Store( + reinterpret_cast(MemoryUsage() + block_bytes + sizeof(char*))); + return result; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/arena.h b/My Mind/Pods/leveldb-library/util/arena.h new file mode 100644 index 0000000..48bab33 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/arena.h @@ -0,0 +1,68 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_ARENA_H_ +#define STORAGE_LEVELDB_UTIL_ARENA_H_ + +#include +#include +#include +#include +#include "port/port.h" + +namespace leveldb { + +class Arena { + public: + Arena(); + ~Arena(); + + // Return a pointer to a newly allocated memory block of "bytes" bytes. + char* Allocate(size_t bytes); + + // Allocate memory with the normal alignment guarantees provided by malloc + char* AllocateAligned(size_t bytes); + + // Returns an estimate of the total memory usage of data allocated + // by the arena. + size_t MemoryUsage() const { + return reinterpret_cast(memory_usage_.NoBarrier_Load()); + } + + private: + char* AllocateFallback(size_t bytes); + char* AllocateNewBlock(size_t block_bytes); + + // Allocation state + char* alloc_ptr_; + size_t alloc_bytes_remaining_; + + // Array of new[] allocated memory blocks + std::vector blocks_; + + // Total memory usage of the arena. + port::AtomicPointer memory_usage_; + + // No copying allowed + Arena(const Arena&); + void operator=(const Arena&); +}; + +inline char* Arena::Allocate(size_t bytes) { + // The semantics of what to return are a bit messy if we allow + // 0-byte allocations, so we disallow them here (we don't need + // them for our internal use). + assert(bytes > 0); + if (bytes <= alloc_bytes_remaining_) { + char* result = alloc_ptr_; + alloc_ptr_ += bytes; + alloc_bytes_remaining_ -= bytes; + return result; + } + return AllocateFallback(bytes); +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_ARENA_H_ diff --git a/My Mind/Pods/leveldb-library/util/bloom.cc b/My Mind/Pods/leveldb-library/util/bloom.cc new file mode 100644 index 0000000..bf3e4ca --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/bloom.cc @@ -0,0 +1,95 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/filter_policy.h" + +#include "leveldb/slice.h" +#include "util/hash.h" + +namespace leveldb { + +namespace { +static uint32_t BloomHash(const Slice& key) { + return Hash(key.data(), key.size(), 0xbc9f1d34); +} + +class BloomFilterPolicy : public FilterPolicy { + private: + size_t bits_per_key_; + size_t k_; + + public: + explicit BloomFilterPolicy(int bits_per_key) + : bits_per_key_(bits_per_key) { + // We intentionally round down to reduce probing cost a little bit + k_ = static_cast(bits_per_key * 0.69); // 0.69 =~ ln(2) + if (k_ < 1) k_ = 1; + if (k_ > 30) k_ = 30; + } + + virtual const char* Name() const { + return "leveldb.BuiltinBloomFilter2"; + } + + virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const { + // Compute bloom filter size (in both bits and bytes) + size_t bits = n * bits_per_key_; + + // For small n, we can see a very high false positive rate. Fix it + // by enforcing a minimum bloom filter length. + if (bits < 64) bits = 64; + + size_t bytes = (bits + 7) / 8; + bits = bytes * 8; + + const size_t init_size = dst->size(); + dst->resize(init_size + bytes, 0); + dst->push_back(static_cast(k_)); // Remember # of probes in filter + char* array = &(*dst)[init_size]; + for (int i = 0; i < n; i++) { + // Use double-hashing to generate a sequence of hash values. + // See analysis in [Kirsch,Mitzenmacher 2006]. + uint32_t h = BloomHash(keys[i]); + const uint32_t delta = (h >> 17) | (h << 15); // Rotate right 17 bits + for (size_t j = 0; j < k_; j++) { + const uint32_t bitpos = h % bits; + array[bitpos/8] |= (1 << (bitpos % 8)); + h += delta; + } + } + } + + virtual bool KeyMayMatch(const Slice& key, const Slice& bloom_filter) const { + const size_t len = bloom_filter.size(); + if (len < 2) return false; + + const char* array = bloom_filter.data(); + const size_t bits = (len - 1) * 8; + + // Use the encoded k so that we can read filters generated by + // bloom filters created using different parameters. + const size_t k = array[len-1]; + if (k > 30) { + // Reserved for potentially new encodings for short bloom filters. + // Consider it a match. + return true; + } + + uint32_t h = BloomHash(key); + const uint32_t delta = (h >> 17) | (h << 15); // Rotate right 17 bits + for (size_t j = 0; j < k; j++) { + const uint32_t bitpos = h % bits; + if ((array[bitpos/8] & (1 << (bitpos % 8))) == 0) return false; + h += delta; + } + return true; + } +}; +} + +const FilterPolicy* NewBloomFilterPolicy(int bits_per_key) { + return new BloomFilterPolicy(bits_per_key); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/cache.cc b/My Mind/Pods/leveldb-library/util/cache.cc new file mode 100644 index 0000000..ce46886 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/cache.cc @@ -0,0 +1,405 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include +#include + +#include "leveldb/cache.h" +#include "port/port.h" +#include "util/hash.h" +#include "util/mutexlock.h" + +namespace leveldb { + +Cache::~Cache() { +} + +namespace { + +// LRU cache implementation +// +// Cache entries have an "in_cache" boolean indicating whether the cache has a +// reference on the entry. The only ways that this can become false without the +// entry being passed to its "deleter" are via Erase(), via Insert() when +// an element with a duplicate key is inserted, or on destruction of the cache. +// +// The cache keeps two linked lists of items in the cache. All items in the +// cache are in one list or the other, and never both. Items still referenced +// by clients but erased from the cache are in neither list. The lists are: +// - in-use: contains the items currently referenced by clients, in no +// particular order. (This list is used for invariant checking. If we +// removed the check, elements that would otherwise be on this list could be +// left as disconnected singleton lists.) +// - LRU: contains the items not currently referenced by clients, in LRU order +// Elements are moved between these lists by the Ref() and Unref() methods, +// when they detect an element in the cache acquiring or losing its only +// external reference. + +// An entry is a variable length heap-allocated structure. Entries +// are kept in a circular doubly linked list ordered by access time. +struct LRUHandle { + void* value; + void (*deleter)(const Slice&, void* value); + LRUHandle* next_hash; + LRUHandle* next; + LRUHandle* prev; + size_t charge; // TODO(opt): Only allow uint32_t? + size_t key_length; + bool in_cache; // Whether entry is in the cache. + uint32_t refs; // References, including cache reference, if present. + uint32_t hash; // Hash of key(); used for fast sharding and comparisons + char key_data[1]; // Beginning of key + + Slice key() const { + // For cheaper lookups, we allow a temporary Handle object + // to store a pointer to a key in "value". + if (next == this) { + return *(reinterpret_cast(value)); + } else { + return Slice(key_data, key_length); + } + } +}; + +// We provide our own simple hash table since it removes a whole bunch +// of porting hacks and is also faster than some of the built-in hash +// table implementations in some of the compiler/runtime combinations +// we have tested. E.g., readrandom speeds up by ~5% over the g++ +// 4.4.3's builtin hashtable. +class HandleTable { + public: + HandleTable() : length_(0), elems_(0), list_(NULL) { Resize(); } + ~HandleTable() { delete[] list_; } + + LRUHandle* Lookup(const Slice& key, uint32_t hash) { + return *FindPointer(key, hash); + } + + LRUHandle* Insert(LRUHandle* h) { + LRUHandle** ptr = FindPointer(h->key(), h->hash); + LRUHandle* old = *ptr; + h->next_hash = (old == NULL ? NULL : old->next_hash); + *ptr = h; + if (old == NULL) { + ++elems_; + if (elems_ > length_) { + // Since each cache entry is fairly large, we aim for a small + // average linked list length (<= 1). + Resize(); + } + } + return old; + } + + LRUHandle* Remove(const Slice& key, uint32_t hash) { + LRUHandle** ptr = FindPointer(key, hash); + LRUHandle* result = *ptr; + if (result != NULL) { + *ptr = result->next_hash; + --elems_; + } + return result; + } + + private: + // The table consists of an array of buckets where each bucket is + // a linked list of cache entries that hash into the bucket. + uint32_t length_; + uint32_t elems_; + LRUHandle** list_; + + // Return a pointer to slot that points to a cache entry that + // matches key/hash. If there is no such cache entry, return a + // pointer to the trailing slot in the corresponding linked list. + LRUHandle** FindPointer(const Slice& key, uint32_t hash) { + LRUHandle** ptr = &list_[hash & (length_ - 1)]; + while (*ptr != NULL && + ((*ptr)->hash != hash || key != (*ptr)->key())) { + ptr = &(*ptr)->next_hash; + } + return ptr; + } + + void Resize() { + uint32_t new_length = 4; + while (new_length < elems_) { + new_length *= 2; + } + LRUHandle** new_list = new LRUHandle*[new_length]; + memset(new_list, 0, sizeof(new_list[0]) * new_length); + uint32_t count = 0; + for (uint32_t i = 0; i < length_; i++) { + LRUHandle* h = list_[i]; + while (h != NULL) { + LRUHandle* next = h->next_hash; + uint32_t hash = h->hash; + LRUHandle** ptr = &new_list[hash & (new_length - 1)]; + h->next_hash = *ptr; + *ptr = h; + h = next; + count++; + } + } + assert(elems_ == count); + delete[] list_; + list_ = new_list; + length_ = new_length; + } +}; + +// A single shard of sharded cache. +class LRUCache { + public: + LRUCache(); + ~LRUCache(); + + // Separate from constructor so caller can easily make an array of LRUCache + void SetCapacity(size_t capacity) { capacity_ = capacity; } + + // Like Cache methods, but with an extra "hash" parameter. + Cache::Handle* Insert(const Slice& key, uint32_t hash, + void* value, size_t charge, + void (*deleter)(const Slice& key, void* value)); + Cache::Handle* Lookup(const Slice& key, uint32_t hash); + void Release(Cache::Handle* handle); + void Erase(const Slice& key, uint32_t hash); + void Prune(); + size_t TotalCharge() const { + MutexLock l(&mutex_); + return usage_; + } + + private: + void LRU_Remove(LRUHandle* e); + void LRU_Append(LRUHandle*list, LRUHandle* e); + void Ref(LRUHandle* e); + void Unref(LRUHandle* e); + bool FinishErase(LRUHandle* e); + + // Initialized before use. + size_t capacity_; + + // mutex_ protects the following state. + mutable port::Mutex mutex_; + size_t usage_; + + // Dummy head of LRU list. + // lru.prev is newest entry, lru.next is oldest entry. + // Entries have refs==1 and in_cache==true. + LRUHandle lru_; + + // Dummy head of in-use list. + // Entries are in use by clients, and have refs >= 2 and in_cache==true. + LRUHandle in_use_; + + HandleTable table_; +}; + +LRUCache::LRUCache() + : usage_(0) { + // Make empty circular linked lists. + lru_.next = &lru_; + lru_.prev = &lru_; + in_use_.next = &in_use_; + in_use_.prev = &in_use_; +} + +LRUCache::~LRUCache() { + assert(in_use_.next == &in_use_); // Error if caller has an unreleased handle + for (LRUHandle* e = lru_.next; e != &lru_; ) { + LRUHandle* next = e->next; + assert(e->in_cache); + e->in_cache = false; + assert(e->refs == 1); // Invariant of lru_ list. + Unref(e); + e = next; + } +} + +void LRUCache::Ref(LRUHandle* e) { + if (e->refs == 1 && e->in_cache) { // If on lru_ list, move to in_use_ list. + LRU_Remove(e); + LRU_Append(&in_use_, e); + } + e->refs++; +} + +void LRUCache::Unref(LRUHandle* e) { + assert(e->refs > 0); + e->refs--; + if (e->refs == 0) { // Deallocate. + assert(!e->in_cache); + (*e->deleter)(e->key(), e->value); + free(e); + } else if (e->in_cache && e->refs == 1) { // No longer in use; move to lru_ list. + LRU_Remove(e); + LRU_Append(&lru_, e); + } +} + +void LRUCache::LRU_Remove(LRUHandle* e) { + e->next->prev = e->prev; + e->prev->next = e->next; +} + +void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) { + // Make "e" newest entry by inserting just before *list + e->next = list; + e->prev = list->prev; + e->prev->next = e; + e->next->prev = e; +} + +Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) { + MutexLock l(&mutex_); + LRUHandle* e = table_.Lookup(key, hash); + if (e != NULL) { + Ref(e); + } + return reinterpret_cast(e); +} + +void LRUCache::Release(Cache::Handle* handle) { + MutexLock l(&mutex_); + Unref(reinterpret_cast(handle)); +} + +Cache::Handle* LRUCache::Insert( + const Slice& key, uint32_t hash, void* value, size_t charge, + void (*deleter)(const Slice& key, void* value)) { + MutexLock l(&mutex_); + + LRUHandle* e = reinterpret_cast( + malloc(sizeof(LRUHandle)-1 + key.size())); + e->value = value; + e->deleter = deleter; + e->charge = charge; + e->key_length = key.size(); + e->hash = hash; + e->in_cache = false; + e->refs = 1; // for the returned handle. + memcpy(e->key_data, key.data(), key.size()); + + if (capacity_ > 0) { + e->refs++; // for the cache's reference. + e->in_cache = true; + LRU_Append(&in_use_, e); + usage_ += charge; + FinishErase(table_.Insert(e)); + } // else don't cache. (Tests use capacity_==0 to turn off caching.) + + while (usage_ > capacity_ && lru_.next != &lru_) { + LRUHandle* old = lru_.next; + assert(old->refs == 1); + bool erased = FinishErase(table_.Remove(old->key(), old->hash)); + if (!erased) { // to avoid unused variable when compiled NDEBUG + assert(erased); + } + } + + return reinterpret_cast(e); +} + +// If e != NULL, finish removing *e from the cache; it has already been removed +// from the hash table. Return whether e != NULL. Requires mutex_ held. +bool LRUCache::FinishErase(LRUHandle* e) { + if (e != NULL) { + assert(e->in_cache); + LRU_Remove(e); + e->in_cache = false; + usage_ -= e->charge; + Unref(e); + } + return e != NULL; +} + +void LRUCache::Erase(const Slice& key, uint32_t hash) { + MutexLock l(&mutex_); + FinishErase(table_.Remove(key, hash)); +} + +void LRUCache::Prune() { + MutexLock l(&mutex_); + while (lru_.next != &lru_) { + LRUHandle* e = lru_.next; + assert(e->refs == 1); + bool erased = FinishErase(table_.Remove(e->key(), e->hash)); + if (!erased) { // to avoid unused variable when compiled NDEBUG + assert(erased); + } + } +} + +static const int kNumShardBits = 4; +static const int kNumShards = 1 << kNumShardBits; + +class ShardedLRUCache : public Cache { + private: + LRUCache shard_[kNumShards]; + port::Mutex id_mutex_; + uint64_t last_id_; + + static inline uint32_t HashSlice(const Slice& s) { + return Hash(s.data(), s.size(), 0); + } + + static uint32_t Shard(uint32_t hash) { + return hash >> (32 - kNumShardBits); + } + + public: + explicit ShardedLRUCache(size_t capacity) + : last_id_(0) { + const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards; + for (int s = 0; s < kNumShards; s++) { + shard_[s].SetCapacity(per_shard); + } + } + virtual ~ShardedLRUCache() { } + virtual Handle* Insert(const Slice& key, void* value, size_t charge, + void (*deleter)(const Slice& key, void* value)) { + const uint32_t hash = HashSlice(key); + return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter); + } + virtual Handle* Lookup(const Slice& key) { + const uint32_t hash = HashSlice(key); + return shard_[Shard(hash)].Lookup(key, hash); + } + virtual void Release(Handle* handle) { + LRUHandle* h = reinterpret_cast(handle); + shard_[Shard(h->hash)].Release(handle); + } + virtual void Erase(const Slice& key) { + const uint32_t hash = HashSlice(key); + shard_[Shard(hash)].Erase(key, hash); + } + virtual void* Value(Handle* handle) { + return reinterpret_cast(handle)->value; + } + virtual uint64_t NewId() { + MutexLock l(&id_mutex_); + return ++(last_id_); + } + virtual void Prune() { + for (int s = 0; s < kNumShards; s++) { + shard_[s].Prune(); + } + } + virtual size_t TotalCharge() const { + size_t total = 0; + for (int s = 0; s < kNumShards; s++) { + total += shard_[s].TotalCharge(); + } + return total; + } +}; + +} // end anonymous namespace + +Cache* NewLRUCache(size_t capacity) { + return new ShardedLRUCache(capacity); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/coding.cc b/My Mind/Pods/leveldb-library/util/coding.cc new file mode 100644 index 0000000..21e3186 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/coding.cc @@ -0,0 +1,194 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "util/coding.h" + +namespace leveldb { + +void EncodeFixed32(char* buf, uint32_t value) { + if (port::kLittleEndian) { + memcpy(buf, &value, sizeof(value)); + } else { + buf[0] = value & 0xff; + buf[1] = (value >> 8) & 0xff; + buf[2] = (value >> 16) & 0xff; + buf[3] = (value >> 24) & 0xff; + } +} + +void EncodeFixed64(char* buf, uint64_t value) { + if (port::kLittleEndian) { + memcpy(buf, &value, sizeof(value)); + } else { + buf[0] = value & 0xff; + buf[1] = (value >> 8) & 0xff; + buf[2] = (value >> 16) & 0xff; + buf[3] = (value >> 24) & 0xff; + buf[4] = (value >> 32) & 0xff; + buf[5] = (value >> 40) & 0xff; + buf[6] = (value >> 48) & 0xff; + buf[7] = (value >> 56) & 0xff; + } +} + +void PutFixed32(std::string* dst, uint32_t value) { + char buf[sizeof(value)]; + EncodeFixed32(buf, value); + dst->append(buf, sizeof(buf)); +} + +void PutFixed64(std::string* dst, uint64_t value) { + char buf[sizeof(value)]; + EncodeFixed64(buf, value); + dst->append(buf, sizeof(buf)); +} + +char* EncodeVarint32(char* dst, uint32_t v) { + // Operate on characters as unsigneds + unsigned char* ptr = reinterpret_cast(dst); + static const int B = 128; + if (v < (1<<7)) { + *(ptr++) = v; + } else if (v < (1<<14)) { + *(ptr++) = v | B; + *(ptr++) = v>>7; + } else if (v < (1<<21)) { + *(ptr++) = v | B; + *(ptr++) = (v>>7) | B; + *(ptr++) = v>>14; + } else if (v < (1<<28)) { + *(ptr++) = v | B; + *(ptr++) = (v>>7) | B; + *(ptr++) = (v>>14) | B; + *(ptr++) = v>>21; + } else { + *(ptr++) = v | B; + *(ptr++) = (v>>7) | B; + *(ptr++) = (v>>14) | B; + *(ptr++) = (v>>21) | B; + *(ptr++) = v>>28; + } + return reinterpret_cast(ptr); +} + +void PutVarint32(std::string* dst, uint32_t v) { + char buf[5]; + char* ptr = EncodeVarint32(buf, v); + dst->append(buf, ptr - buf); +} + +char* EncodeVarint64(char* dst, uint64_t v) { + static const int B = 128; + unsigned char* ptr = reinterpret_cast(dst); + while (v >= B) { + *(ptr++) = (v & (B-1)) | B; + v >>= 7; + } + *(ptr++) = static_cast(v); + return reinterpret_cast(ptr); +} + +void PutVarint64(std::string* dst, uint64_t v) { + char buf[10]; + char* ptr = EncodeVarint64(buf, v); + dst->append(buf, ptr - buf); +} + +void PutLengthPrefixedSlice(std::string* dst, const Slice& value) { + PutVarint32(dst, value.size()); + dst->append(value.data(), value.size()); +} + +int VarintLength(uint64_t v) { + int len = 1; + while (v >= 128) { + v >>= 7; + len++; + } + return len; +} + +const char* GetVarint32PtrFallback(const char* p, + const char* limit, + uint32_t* value) { + uint32_t result = 0; + for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) { + uint32_t byte = *(reinterpret_cast(p)); + p++; + if (byte & 128) { + // More bytes are present + result |= ((byte & 127) << shift); + } else { + result |= (byte << shift); + *value = result; + return reinterpret_cast(p); + } + } + return NULL; +} + +bool GetVarint32(Slice* input, uint32_t* value) { + const char* p = input->data(); + const char* limit = p + input->size(); + const char* q = GetVarint32Ptr(p, limit, value); + if (q == NULL) { + return false; + } else { + *input = Slice(q, limit - q); + return true; + } +} + +const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) { + uint64_t result = 0; + for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) { + uint64_t byte = *(reinterpret_cast(p)); + p++; + if (byte & 128) { + // More bytes are present + result |= ((byte & 127) << shift); + } else { + result |= (byte << shift); + *value = result; + return reinterpret_cast(p); + } + } + return NULL; +} + +bool GetVarint64(Slice* input, uint64_t* value) { + const char* p = input->data(); + const char* limit = p + input->size(); + const char* q = GetVarint64Ptr(p, limit, value); + if (q == NULL) { + return false; + } else { + *input = Slice(q, limit - q); + return true; + } +} + +const char* GetLengthPrefixedSlice(const char* p, const char* limit, + Slice* result) { + uint32_t len; + p = GetVarint32Ptr(p, limit, &len); + if (p == NULL) return NULL; + if (p + len > limit) return NULL; + *result = Slice(p, len); + return p + len; +} + +bool GetLengthPrefixedSlice(Slice* input, Slice* result) { + uint32_t len; + if (GetVarint32(input, &len) && + input->size() >= len) { + *result = Slice(input->data(), len); + input->remove_prefix(len); + return true; + } else { + return false; + } +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/coding.h b/My Mind/Pods/leveldb-library/util/coding.h new file mode 100644 index 0000000..3993c4a --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/coding.h @@ -0,0 +1,104 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Endian-neutral encoding: +// * Fixed-length numbers are encoded with least-significant byte first +// * In addition we support variable length "varint" encoding +// * Strings are encoded prefixed by their length in varint format + +#ifndef STORAGE_LEVELDB_UTIL_CODING_H_ +#define STORAGE_LEVELDB_UTIL_CODING_H_ + +#include +#include +#include +#include "leveldb/slice.h" +#include "port/port.h" + +namespace leveldb { + +// Standard Put... routines append to a string +extern void PutFixed32(std::string* dst, uint32_t value); +extern void PutFixed64(std::string* dst, uint64_t value); +extern void PutVarint32(std::string* dst, uint32_t value); +extern void PutVarint64(std::string* dst, uint64_t value); +extern void PutLengthPrefixedSlice(std::string* dst, const Slice& value); + +// Standard Get... routines parse a value from the beginning of a Slice +// and advance the slice past the parsed value. +extern bool GetVarint32(Slice* input, uint32_t* value); +extern bool GetVarint64(Slice* input, uint64_t* value); +extern bool GetLengthPrefixedSlice(Slice* input, Slice* result); + +// Pointer-based variants of GetVarint... These either store a value +// in *v and return a pointer just past the parsed value, or return +// NULL on error. These routines only look at bytes in the range +// [p..limit-1] +extern const char* GetVarint32Ptr(const char* p,const char* limit, uint32_t* v); +extern const char* GetVarint64Ptr(const char* p,const char* limit, uint64_t* v); + +// Returns the length of the varint32 or varint64 encoding of "v" +extern int VarintLength(uint64_t v); + +// Lower-level versions of Put... that write directly into a character buffer +// REQUIRES: dst has enough space for the value being written +extern void EncodeFixed32(char* dst, uint32_t value); +extern void EncodeFixed64(char* dst, uint64_t value); + +// Lower-level versions of Put... that write directly into a character buffer +// and return a pointer just past the last byte written. +// REQUIRES: dst has enough space for the value being written +extern char* EncodeVarint32(char* dst, uint32_t value); +extern char* EncodeVarint64(char* dst, uint64_t value); + +// Lower-level versions of Get... that read directly from a character buffer +// without any bounds checking. + +inline uint32_t DecodeFixed32(const char* ptr) { + if (port::kLittleEndian) { + // Load the raw bytes + uint32_t result; + memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load + return result; + } else { + return ((static_cast(static_cast(ptr[0]))) + | (static_cast(static_cast(ptr[1])) << 8) + | (static_cast(static_cast(ptr[2])) << 16) + | (static_cast(static_cast(ptr[3])) << 24)); + } +} + +inline uint64_t DecodeFixed64(const char* ptr) { + if (port::kLittleEndian) { + // Load the raw bytes + uint64_t result; + memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load + return result; + } else { + uint64_t lo = DecodeFixed32(ptr); + uint64_t hi = DecodeFixed32(ptr + 4); + return (hi << 32) | lo; + } +} + +// Internal routine for use by fallback path of GetVarint32Ptr +extern const char* GetVarint32PtrFallback(const char* p, + const char* limit, + uint32_t* value); +inline const char* GetVarint32Ptr(const char* p, + const char* limit, + uint32_t* value) { + if (p < limit) { + uint32_t result = *(reinterpret_cast(p)); + if ((result & 128) == 0) { + *value = result; + return p + 1; + } + } + return GetVarint32PtrFallback(p, limit, value); +} + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_CODING_H_ diff --git a/My Mind/Pods/leveldb-library/util/comparator.cc b/My Mind/Pods/leveldb-library/util/comparator.cc new file mode 100644 index 0000000..4b7b572 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/comparator.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include +#include "leveldb/comparator.h" +#include "leveldb/slice.h" +#include "port/port.h" +#include "util/logging.h" + +namespace leveldb { + +Comparator::~Comparator() { } + +namespace { +class BytewiseComparatorImpl : public Comparator { + public: + BytewiseComparatorImpl() { } + + virtual const char* Name() const { + return "leveldb.BytewiseComparator"; + } + + virtual int Compare(const Slice& a, const Slice& b) const { + return a.compare(b); + } + + virtual void FindShortestSeparator( + std::string* start, + const Slice& limit) const { + // Find length of common prefix + size_t min_length = std::min(start->size(), limit.size()); + size_t diff_index = 0; + while ((diff_index < min_length) && + ((*start)[diff_index] == limit[diff_index])) { + diff_index++; + } + + if (diff_index >= min_length) { + // Do not shorten if one string is a prefix of the other + } else { + uint8_t diff_byte = static_cast((*start)[diff_index]); + if (diff_byte < static_cast(0xff) && + diff_byte + 1 < static_cast(limit[diff_index])) { + (*start)[diff_index]++; + start->resize(diff_index + 1); + assert(Compare(*start, limit) < 0); + } + } + } + + virtual void FindShortSuccessor(std::string* key) const { + // Find first character that can be incremented + size_t n = key->size(); + for (size_t i = 0; i < n; i++) { + const uint8_t byte = (*key)[i]; + if (byte != static_cast(0xff)) { + (*key)[i] = byte + 1; + key->resize(i+1); + return; + } + } + // *key is a run of 0xffs. Leave it alone. + } +}; +} // namespace + +static port::OnceType once = LEVELDB_ONCE_INIT; +static const Comparator* bytewise; + +static void InitModule() { + bytewise = new BytewiseComparatorImpl; +} + +const Comparator* BytewiseComparator() { + port::InitOnce(&once, InitModule); + return bytewise; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/crc32c.cc b/My Mind/Pods/leveldb-library/util/crc32c.cc new file mode 100644 index 0000000..edd61cf --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/crc32c.cc @@ -0,0 +1,350 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A portable implementation of crc32c, optimized to handle +// four bytes at a time. + +#include "util/crc32c.h" + +#include + +#include "port/port.h" +#include "util/coding.h" + +namespace leveldb { +namespace crc32c { + +static const uint32_t table0_[256] = { + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, + 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, + 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, + 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, + 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, + 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, + 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, + 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, + 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, + 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, + 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, + 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, + 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, + 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, + 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, + 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, + 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, + 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, + 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, + 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, + 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, + 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, + 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, + 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, + 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, + 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, + 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, + 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, + 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, + 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, + 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, + 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, + 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, + 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, + 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, + 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, + 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, + 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, + 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, + 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, + 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, + 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, + 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351 +}; +static const uint32_t table1_[256] = { + 0x00000000, 0x13a29877, 0x274530ee, 0x34e7a899, + 0x4e8a61dc, 0x5d28f9ab, 0x69cf5132, 0x7a6dc945, + 0x9d14c3b8, 0x8eb65bcf, 0xba51f356, 0xa9f36b21, + 0xd39ea264, 0xc03c3a13, 0xf4db928a, 0xe7790afd, + 0x3fc5f181, 0x2c6769f6, 0x1880c16f, 0x0b225918, + 0x714f905d, 0x62ed082a, 0x560aa0b3, 0x45a838c4, + 0xa2d13239, 0xb173aa4e, 0x859402d7, 0x96369aa0, + 0xec5b53e5, 0xfff9cb92, 0xcb1e630b, 0xd8bcfb7c, + 0x7f8be302, 0x6c297b75, 0x58ced3ec, 0x4b6c4b9b, + 0x310182de, 0x22a31aa9, 0x1644b230, 0x05e62a47, + 0xe29f20ba, 0xf13db8cd, 0xc5da1054, 0xd6788823, + 0xac154166, 0xbfb7d911, 0x8b507188, 0x98f2e9ff, + 0x404e1283, 0x53ec8af4, 0x670b226d, 0x74a9ba1a, + 0x0ec4735f, 0x1d66eb28, 0x298143b1, 0x3a23dbc6, + 0xdd5ad13b, 0xcef8494c, 0xfa1fe1d5, 0xe9bd79a2, + 0x93d0b0e7, 0x80722890, 0xb4958009, 0xa737187e, + 0xff17c604, 0xecb55e73, 0xd852f6ea, 0xcbf06e9d, + 0xb19da7d8, 0xa23f3faf, 0x96d89736, 0x857a0f41, + 0x620305bc, 0x71a19dcb, 0x45463552, 0x56e4ad25, + 0x2c896460, 0x3f2bfc17, 0x0bcc548e, 0x186eccf9, + 0xc0d23785, 0xd370aff2, 0xe797076b, 0xf4359f1c, + 0x8e585659, 0x9dface2e, 0xa91d66b7, 0xbabffec0, + 0x5dc6f43d, 0x4e646c4a, 0x7a83c4d3, 0x69215ca4, + 0x134c95e1, 0x00ee0d96, 0x3409a50f, 0x27ab3d78, + 0x809c2506, 0x933ebd71, 0xa7d915e8, 0xb47b8d9f, + 0xce1644da, 0xddb4dcad, 0xe9537434, 0xfaf1ec43, + 0x1d88e6be, 0x0e2a7ec9, 0x3acdd650, 0x296f4e27, + 0x53028762, 0x40a01f15, 0x7447b78c, 0x67e52ffb, + 0xbf59d487, 0xacfb4cf0, 0x981ce469, 0x8bbe7c1e, + 0xf1d3b55b, 0xe2712d2c, 0xd69685b5, 0xc5341dc2, + 0x224d173f, 0x31ef8f48, 0x050827d1, 0x16aabfa6, + 0x6cc776e3, 0x7f65ee94, 0x4b82460d, 0x5820de7a, + 0xfbc3faf9, 0xe861628e, 0xdc86ca17, 0xcf245260, + 0xb5499b25, 0xa6eb0352, 0x920cabcb, 0x81ae33bc, + 0x66d73941, 0x7575a136, 0x419209af, 0x523091d8, + 0x285d589d, 0x3bffc0ea, 0x0f186873, 0x1cbaf004, + 0xc4060b78, 0xd7a4930f, 0xe3433b96, 0xf0e1a3e1, + 0x8a8c6aa4, 0x992ef2d3, 0xadc95a4a, 0xbe6bc23d, + 0x5912c8c0, 0x4ab050b7, 0x7e57f82e, 0x6df56059, + 0x1798a91c, 0x043a316b, 0x30dd99f2, 0x237f0185, + 0x844819fb, 0x97ea818c, 0xa30d2915, 0xb0afb162, + 0xcac27827, 0xd960e050, 0xed8748c9, 0xfe25d0be, + 0x195cda43, 0x0afe4234, 0x3e19eaad, 0x2dbb72da, + 0x57d6bb9f, 0x447423e8, 0x70938b71, 0x63311306, + 0xbb8de87a, 0xa82f700d, 0x9cc8d894, 0x8f6a40e3, + 0xf50789a6, 0xe6a511d1, 0xd242b948, 0xc1e0213f, + 0x26992bc2, 0x353bb3b5, 0x01dc1b2c, 0x127e835b, + 0x68134a1e, 0x7bb1d269, 0x4f567af0, 0x5cf4e287, + 0x04d43cfd, 0x1776a48a, 0x23910c13, 0x30339464, + 0x4a5e5d21, 0x59fcc556, 0x6d1b6dcf, 0x7eb9f5b8, + 0x99c0ff45, 0x8a626732, 0xbe85cfab, 0xad2757dc, + 0xd74a9e99, 0xc4e806ee, 0xf00fae77, 0xe3ad3600, + 0x3b11cd7c, 0x28b3550b, 0x1c54fd92, 0x0ff665e5, + 0x759baca0, 0x663934d7, 0x52de9c4e, 0x417c0439, + 0xa6050ec4, 0xb5a796b3, 0x81403e2a, 0x92e2a65d, + 0xe88f6f18, 0xfb2df76f, 0xcfca5ff6, 0xdc68c781, + 0x7b5fdfff, 0x68fd4788, 0x5c1aef11, 0x4fb87766, + 0x35d5be23, 0x26772654, 0x12908ecd, 0x013216ba, + 0xe64b1c47, 0xf5e98430, 0xc10e2ca9, 0xd2acb4de, + 0xa8c17d9b, 0xbb63e5ec, 0x8f844d75, 0x9c26d502, + 0x449a2e7e, 0x5738b609, 0x63df1e90, 0x707d86e7, + 0x0a104fa2, 0x19b2d7d5, 0x2d557f4c, 0x3ef7e73b, + 0xd98eedc6, 0xca2c75b1, 0xfecbdd28, 0xed69455f, + 0x97048c1a, 0x84a6146d, 0xb041bcf4, 0xa3e32483 +}; +static const uint32_t table2_[256] = { + 0x00000000, 0xa541927e, 0x4f6f520d, 0xea2ec073, + 0x9edea41a, 0x3b9f3664, 0xd1b1f617, 0x74f06469, + 0x38513ec5, 0x9d10acbb, 0x773e6cc8, 0xd27ffeb6, + 0xa68f9adf, 0x03ce08a1, 0xe9e0c8d2, 0x4ca15aac, + 0x70a27d8a, 0xd5e3eff4, 0x3fcd2f87, 0x9a8cbdf9, + 0xee7cd990, 0x4b3d4bee, 0xa1138b9d, 0x045219e3, + 0x48f3434f, 0xedb2d131, 0x079c1142, 0xa2dd833c, + 0xd62de755, 0x736c752b, 0x9942b558, 0x3c032726, + 0xe144fb14, 0x4405696a, 0xae2ba919, 0x0b6a3b67, + 0x7f9a5f0e, 0xdadbcd70, 0x30f50d03, 0x95b49f7d, + 0xd915c5d1, 0x7c5457af, 0x967a97dc, 0x333b05a2, + 0x47cb61cb, 0xe28af3b5, 0x08a433c6, 0xade5a1b8, + 0x91e6869e, 0x34a714e0, 0xde89d493, 0x7bc846ed, + 0x0f382284, 0xaa79b0fa, 0x40577089, 0xe516e2f7, + 0xa9b7b85b, 0x0cf62a25, 0xe6d8ea56, 0x43997828, + 0x37691c41, 0x92288e3f, 0x78064e4c, 0xdd47dc32, + 0xc76580d9, 0x622412a7, 0x880ad2d4, 0x2d4b40aa, + 0x59bb24c3, 0xfcfab6bd, 0x16d476ce, 0xb395e4b0, + 0xff34be1c, 0x5a752c62, 0xb05bec11, 0x151a7e6f, + 0x61ea1a06, 0xc4ab8878, 0x2e85480b, 0x8bc4da75, + 0xb7c7fd53, 0x12866f2d, 0xf8a8af5e, 0x5de93d20, + 0x29195949, 0x8c58cb37, 0x66760b44, 0xc337993a, + 0x8f96c396, 0x2ad751e8, 0xc0f9919b, 0x65b803e5, + 0x1148678c, 0xb409f5f2, 0x5e273581, 0xfb66a7ff, + 0x26217bcd, 0x8360e9b3, 0x694e29c0, 0xcc0fbbbe, + 0xb8ffdfd7, 0x1dbe4da9, 0xf7908dda, 0x52d11fa4, + 0x1e704508, 0xbb31d776, 0x511f1705, 0xf45e857b, + 0x80aee112, 0x25ef736c, 0xcfc1b31f, 0x6a802161, + 0x56830647, 0xf3c29439, 0x19ec544a, 0xbcadc634, + 0xc85da25d, 0x6d1c3023, 0x8732f050, 0x2273622e, + 0x6ed23882, 0xcb93aafc, 0x21bd6a8f, 0x84fcf8f1, + 0xf00c9c98, 0x554d0ee6, 0xbf63ce95, 0x1a225ceb, + 0x8b277743, 0x2e66e53d, 0xc448254e, 0x6109b730, + 0x15f9d359, 0xb0b84127, 0x5a968154, 0xffd7132a, + 0xb3764986, 0x1637dbf8, 0xfc191b8b, 0x595889f5, + 0x2da8ed9c, 0x88e97fe2, 0x62c7bf91, 0xc7862def, + 0xfb850ac9, 0x5ec498b7, 0xb4ea58c4, 0x11abcaba, + 0x655baed3, 0xc01a3cad, 0x2a34fcde, 0x8f756ea0, + 0xc3d4340c, 0x6695a672, 0x8cbb6601, 0x29faf47f, + 0x5d0a9016, 0xf84b0268, 0x1265c21b, 0xb7245065, + 0x6a638c57, 0xcf221e29, 0x250cde5a, 0x804d4c24, + 0xf4bd284d, 0x51fcba33, 0xbbd27a40, 0x1e93e83e, + 0x5232b292, 0xf77320ec, 0x1d5de09f, 0xb81c72e1, + 0xccec1688, 0x69ad84f6, 0x83834485, 0x26c2d6fb, + 0x1ac1f1dd, 0xbf8063a3, 0x55aea3d0, 0xf0ef31ae, + 0x841f55c7, 0x215ec7b9, 0xcb7007ca, 0x6e3195b4, + 0x2290cf18, 0x87d15d66, 0x6dff9d15, 0xc8be0f6b, + 0xbc4e6b02, 0x190ff97c, 0xf321390f, 0x5660ab71, + 0x4c42f79a, 0xe90365e4, 0x032da597, 0xa66c37e9, + 0xd29c5380, 0x77ddc1fe, 0x9df3018d, 0x38b293f3, + 0x7413c95f, 0xd1525b21, 0x3b7c9b52, 0x9e3d092c, + 0xeacd6d45, 0x4f8cff3b, 0xa5a23f48, 0x00e3ad36, + 0x3ce08a10, 0x99a1186e, 0x738fd81d, 0xd6ce4a63, + 0xa23e2e0a, 0x077fbc74, 0xed517c07, 0x4810ee79, + 0x04b1b4d5, 0xa1f026ab, 0x4bdee6d8, 0xee9f74a6, + 0x9a6f10cf, 0x3f2e82b1, 0xd50042c2, 0x7041d0bc, + 0xad060c8e, 0x08479ef0, 0xe2695e83, 0x4728ccfd, + 0x33d8a894, 0x96993aea, 0x7cb7fa99, 0xd9f668e7, + 0x9557324b, 0x3016a035, 0xda386046, 0x7f79f238, + 0x0b899651, 0xaec8042f, 0x44e6c45c, 0xe1a75622, + 0xdda47104, 0x78e5e37a, 0x92cb2309, 0x378ab177, + 0x437ad51e, 0xe63b4760, 0x0c158713, 0xa954156d, + 0xe5f54fc1, 0x40b4ddbf, 0xaa9a1dcc, 0x0fdb8fb2, + 0x7b2bebdb, 0xde6a79a5, 0x3444b9d6, 0x91052ba8 +}; +static const uint32_t table3_[256] = { + 0x00000000, 0xdd45aab8, 0xbf672381, 0x62228939, + 0x7b2231f3, 0xa6679b4b, 0xc4451272, 0x1900b8ca, + 0xf64463e6, 0x2b01c95e, 0x49234067, 0x9466eadf, + 0x8d665215, 0x5023f8ad, 0x32017194, 0xef44db2c, + 0xe964b13d, 0x34211b85, 0x560392bc, 0x8b463804, + 0x924680ce, 0x4f032a76, 0x2d21a34f, 0xf06409f7, + 0x1f20d2db, 0xc2657863, 0xa047f15a, 0x7d025be2, + 0x6402e328, 0xb9474990, 0xdb65c0a9, 0x06206a11, + 0xd725148b, 0x0a60be33, 0x6842370a, 0xb5079db2, + 0xac072578, 0x71428fc0, 0x136006f9, 0xce25ac41, + 0x2161776d, 0xfc24ddd5, 0x9e0654ec, 0x4343fe54, + 0x5a43469e, 0x8706ec26, 0xe524651f, 0x3861cfa7, + 0x3e41a5b6, 0xe3040f0e, 0x81268637, 0x5c632c8f, + 0x45639445, 0x98263efd, 0xfa04b7c4, 0x27411d7c, + 0xc805c650, 0x15406ce8, 0x7762e5d1, 0xaa274f69, + 0xb327f7a3, 0x6e625d1b, 0x0c40d422, 0xd1057e9a, + 0xaba65fe7, 0x76e3f55f, 0x14c17c66, 0xc984d6de, + 0xd0846e14, 0x0dc1c4ac, 0x6fe34d95, 0xb2a6e72d, + 0x5de23c01, 0x80a796b9, 0xe2851f80, 0x3fc0b538, + 0x26c00df2, 0xfb85a74a, 0x99a72e73, 0x44e284cb, + 0x42c2eeda, 0x9f874462, 0xfda5cd5b, 0x20e067e3, + 0x39e0df29, 0xe4a57591, 0x8687fca8, 0x5bc25610, + 0xb4868d3c, 0x69c32784, 0x0be1aebd, 0xd6a40405, + 0xcfa4bccf, 0x12e11677, 0x70c39f4e, 0xad8635f6, + 0x7c834b6c, 0xa1c6e1d4, 0xc3e468ed, 0x1ea1c255, + 0x07a17a9f, 0xdae4d027, 0xb8c6591e, 0x6583f3a6, + 0x8ac7288a, 0x57828232, 0x35a00b0b, 0xe8e5a1b3, + 0xf1e51979, 0x2ca0b3c1, 0x4e823af8, 0x93c79040, + 0x95e7fa51, 0x48a250e9, 0x2a80d9d0, 0xf7c57368, + 0xeec5cba2, 0x3380611a, 0x51a2e823, 0x8ce7429b, + 0x63a399b7, 0xbee6330f, 0xdcc4ba36, 0x0181108e, + 0x1881a844, 0xc5c402fc, 0xa7e68bc5, 0x7aa3217d, + 0x52a0c93f, 0x8fe56387, 0xedc7eabe, 0x30824006, + 0x2982f8cc, 0xf4c75274, 0x96e5db4d, 0x4ba071f5, + 0xa4e4aad9, 0x79a10061, 0x1b838958, 0xc6c623e0, + 0xdfc69b2a, 0x02833192, 0x60a1b8ab, 0xbde41213, + 0xbbc47802, 0x6681d2ba, 0x04a35b83, 0xd9e6f13b, + 0xc0e649f1, 0x1da3e349, 0x7f816a70, 0xa2c4c0c8, + 0x4d801be4, 0x90c5b15c, 0xf2e73865, 0x2fa292dd, + 0x36a22a17, 0xebe780af, 0x89c50996, 0x5480a32e, + 0x8585ddb4, 0x58c0770c, 0x3ae2fe35, 0xe7a7548d, + 0xfea7ec47, 0x23e246ff, 0x41c0cfc6, 0x9c85657e, + 0x73c1be52, 0xae8414ea, 0xcca69dd3, 0x11e3376b, + 0x08e38fa1, 0xd5a62519, 0xb784ac20, 0x6ac10698, + 0x6ce16c89, 0xb1a4c631, 0xd3864f08, 0x0ec3e5b0, + 0x17c35d7a, 0xca86f7c2, 0xa8a47efb, 0x75e1d443, + 0x9aa50f6f, 0x47e0a5d7, 0x25c22cee, 0xf8878656, + 0xe1873e9c, 0x3cc29424, 0x5ee01d1d, 0x83a5b7a5, + 0xf90696d8, 0x24433c60, 0x4661b559, 0x9b241fe1, + 0x8224a72b, 0x5f610d93, 0x3d4384aa, 0xe0062e12, + 0x0f42f53e, 0xd2075f86, 0xb025d6bf, 0x6d607c07, + 0x7460c4cd, 0xa9256e75, 0xcb07e74c, 0x16424df4, + 0x106227e5, 0xcd278d5d, 0xaf050464, 0x7240aedc, + 0x6b401616, 0xb605bcae, 0xd4273597, 0x09629f2f, + 0xe6264403, 0x3b63eebb, 0x59416782, 0x8404cd3a, + 0x9d0475f0, 0x4041df48, 0x22635671, 0xff26fcc9, + 0x2e238253, 0xf36628eb, 0x9144a1d2, 0x4c010b6a, + 0x5501b3a0, 0x88441918, 0xea669021, 0x37233a99, + 0xd867e1b5, 0x05224b0d, 0x6700c234, 0xba45688c, + 0xa345d046, 0x7e007afe, 0x1c22f3c7, 0xc167597f, + 0xc747336e, 0x1a0299d6, 0x782010ef, 0xa565ba57, + 0xbc65029d, 0x6120a825, 0x0302211c, 0xde478ba4, + 0x31035088, 0xec46fa30, 0x8e647309, 0x5321d9b1, + 0x4a21617b, 0x9764cbc3, 0xf54642fa, 0x2803e842 +}; + +// Used to fetch a naturally-aligned 32-bit word in little endian byte-order +static inline uint32_t LE_LOAD32(const uint8_t *p) { + return DecodeFixed32(reinterpret_cast(p)); +} + +// Determine if the CPU running this program can accelerate the CRC32C +// calculation. +static bool CanAccelerateCRC32C() { + // port::AcceleretedCRC32C returns zero when unable to accelerate. + static const char kTestCRCBuffer[] = "TestCRCBuffer"; + static const char kBufSize = sizeof(kTestCRCBuffer) - 1; + static const uint32_t kTestCRCValue = 0xdcbc59fa; + + return port::AcceleratedCRC32C(0, kTestCRCBuffer, kBufSize) == kTestCRCValue; +} + +uint32_t Extend(uint32_t crc, const char* buf, size_t size) { + static bool accelerate = CanAccelerateCRC32C(); + if (accelerate) { + return port::AcceleratedCRC32C(crc, buf, size); + } + + const uint8_t *p = reinterpret_cast(buf); + const uint8_t *e = p + size; + uint32_t l = crc ^ 0xffffffffu; + +#define STEP1 do { \ + int c = (l & 0xff) ^ *p++; \ + l = table0_[c] ^ (l >> 8); \ +} while (0) +#define STEP4 do { \ + uint32_t c = l ^ LE_LOAD32(p); \ + p += 4; \ + l = table3_[c & 0xff] ^ \ + table2_[(c >> 8) & 0xff] ^ \ + table1_[(c >> 16) & 0xff] ^ \ + table0_[c >> 24]; \ +} while (0) + + // Point x at first 4-byte aligned byte in string. This might be + // just past the end of the string. + const uintptr_t pval = reinterpret_cast(p); + const uint8_t* x = reinterpret_cast(((pval + 3) >> 2) << 2); + if (x <= e) { + // Process bytes until finished or p is 4-byte aligned + while (p != x) { + STEP1; + } + } + // Process bytes 16 at a time + while ((e-p) >= 16) { + STEP4; STEP4; STEP4; STEP4; + } + // Process bytes 4 at a time + while ((e-p) >= 4) { + STEP4; + } + // Process the last few bytes + while (p != e) { + STEP1; + } +#undef STEP4 +#undef STEP1 + return l ^ 0xffffffffu; +} + +} // namespace crc32c +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/crc32c.h b/My Mind/Pods/leveldb-library/util/crc32c.h new file mode 100644 index 0000000..1d7e5c0 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/crc32c.h @@ -0,0 +1,45 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_CRC32C_H_ +#define STORAGE_LEVELDB_UTIL_CRC32C_H_ + +#include +#include + +namespace leveldb { +namespace crc32c { + +// Return the crc32c of concat(A, data[0,n-1]) where init_crc is the +// crc32c of some string A. Extend() is often used to maintain the +// crc32c of a stream of data. +extern uint32_t Extend(uint32_t init_crc, const char* data, size_t n); + +// Return the crc32c of data[0,n-1] +inline uint32_t Value(const char* data, size_t n) { + return Extend(0, data, n); +} + +static const uint32_t kMaskDelta = 0xa282ead8ul; + +// Return a masked representation of crc. +// +// Motivation: it is problematic to compute the CRC of a string that +// contains embedded CRCs. Therefore we recommend that CRCs stored +// somewhere (e.g., in files) should be masked before being stored. +inline uint32_t Mask(uint32_t crc) { + // Rotate right by 15 bits and add a constant. + return ((crc >> 15) | (crc << 17)) + kMaskDelta; +} + +// Return the crc whose masked representation is masked_crc. +inline uint32_t Unmask(uint32_t masked_crc) { + uint32_t rot = masked_crc - kMaskDelta; + return ((rot >> 17) | (rot << 15)); +} + +} // namespace crc32c +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_CRC32C_H_ diff --git a/My Mind/Pods/leveldb-library/util/env.cc b/My Mind/Pods/leveldb-library/util/env.cc new file mode 100644 index 0000000..c58a082 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/env.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/env.h" + +namespace leveldb { + +Env::~Env() { +} + +Status Env::NewAppendableFile(const std::string& fname, WritableFile** result) { + return Status::NotSupported("NewAppendableFile", fname); +} + +SequentialFile::~SequentialFile() { +} + +RandomAccessFile::~RandomAccessFile() { +} + +WritableFile::~WritableFile() { +} + +Logger::~Logger() { +} + +FileLock::~FileLock() { +} + +void Log(Logger* info_log, const char* format, ...) { + if (info_log != NULL) { + va_list ap; + va_start(ap, format); + info_log->Logv(format, ap); + va_end(ap); + } +} + +static Status DoWriteStringToFile(Env* env, const Slice& data, + const std::string& fname, + bool should_sync) { + WritableFile* file; + Status s = env->NewWritableFile(fname, &file); + if (!s.ok()) { + return s; + } + s = file->Append(data); + if (s.ok() && should_sync) { + s = file->Sync(); + } + if (s.ok()) { + s = file->Close(); + } + delete file; // Will auto-close if we did not close above + if (!s.ok()) { + env->DeleteFile(fname); + } + return s; +} + +Status WriteStringToFile(Env* env, const Slice& data, + const std::string& fname) { + return DoWriteStringToFile(env, data, fname, false); +} + +Status WriteStringToFileSync(Env* env, const Slice& data, + const std::string& fname) { + return DoWriteStringToFile(env, data, fname, true); +} + +Status ReadFileToString(Env* env, const std::string& fname, std::string* data) { + data->clear(); + SequentialFile* file; + Status s = env->NewSequentialFile(fname, &file); + if (!s.ok()) { + return s; + } + static const int kBufferSize = 8192; + char* space = new char[kBufferSize]; + while (true) { + Slice fragment; + s = file->Read(kBufferSize, &fragment, space); + if (!s.ok()) { + break; + } + data->append(fragment.data(), fragment.size()); + if (fragment.empty()) { + break; + } + } + delete[] space; + delete file; + return s; +} + +EnvWrapper::~EnvWrapper() { +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/env_posix.cc b/My Mind/Pods/leveldb-library/util/env_posix.cc new file mode 100644 index 0000000..84aabb2 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/env_posix.cc @@ -0,0 +1,695 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "leveldb/env.h" +#include "leveldb/slice.h" +#include "port/port.h" +#include "util/logging.h" +#include "util/mutexlock.h" +#include "util/posix_logger.h" +#include "util/env_posix_test_helper.h" + +namespace leveldb { + +namespace { + +static int open_read_only_file_limit = -1; +static int mmap_limit = -1; + +static Status IOError(const std::string& context, int err_number) { + return Status::IOError(context, strerror(err_number)); +} + +// Helper class to limit resource usage to avoid exhaustion. +// Currently used to limit read-only file descriptors and mmap file usage +// so that we do not end up running out of file descriptors, virtual memory, +// or running into kernel performance problems for very large databases. +class Limiter { + public: + // Limit maximum number of resources to |n|. + Limiter(intptr_t n) { + SetAllowed(n); + } + + // If another resource is available, acquire it and return true. + // Else return false. + bool Acquire() { + if (GetAllowed() <= 0) { + return false; + } + MutexLock l(&mu_); + intptr_t x = GetAllowed(); + if (x <= 0) { + return false; + } else { + SetAllowed(x - 1); + return true; + } + } + + // Release a resource acquired by a previous call to Acquire() that returned + // true. + void Release() { + MutexLock l(&mu_); + SetAllowed(GetAllowed() + 1); + } + + private: + port::Mutex mu_; + port::AtomicPointer allowed_; + + intptr_t GetAllowed() const { + return reinterpret_cast(allowed_.Acquire_Load()); + } + + // REQUIRES: mu_ must be held + void SetAllowed(intptr_t v) { + allowed_.Release_Store(reinterpret_cast(v)); + } + + Limiter(const Limiter&); + void operator=(const Limiter&); +}; + +class PosixSequentialFile: public SequentialFile { + private: + std::string filename_; + FILE* file_; + + public: + PosixSequentialFile(const std::string& fname, FILE* f) + : filename_(fname), file_(f) { } + virtual ~PosixSequentialFile() { fclose(file_); } + + virtual Status Read(size_t n, Slice* result, char* scratch) { + Status s; + size_t r = fread_unlocked(scratch, 1, n, file_); + *result = Slice(scratch, r); + if (r < n) { + if (feof(file_)) { + // We leave status as ok if we hit the end of the file + } else { + // A partial read with an error: return a non-ok status + s = IOError(filename_, errno); + } + } + return s; + } + + virtual Status Skip(uint64_t n) { + if (fseek(file_, n, SEEK_CUR)) { + return IOError(filename_, errno); + } + return Status::OK(); + } +}; + +// pread() based random-access +class PosixRandomAccessFile: public RandomAccessFile { + private: + std::string filename_; + bool temporary_fd_; // If true, fd_ is -1 and we open on every read. + int fd_; + Limiter* limiter_; + + public: + PosixRandomAccessFile(const std::string& fname, int fd, Limiter* limiter) + : filename_(fname), fd_(fd), limiter_(limiter) { + temporary_fd_ = !limiter->Acquire(); + if (temporary_fd_) { + // Open file on every access. + close(fd_); + fd_ = -1; + } + } + + virtual ~PosixRandomAccessFile() { + if (!temporary_fd_) { + close(fd_); + limiter_->Release(); + } + } + + virtual Status Read(uint64_t offset, size_t n, Slice* result, + char* scratch) const { + int fd = fd_; + if (temporary_fd_) { + fd = open(filename_.c_str(), O_RDONLY); + if (fd < 0) { + return IOError(filename_, errno); + } + } + + Status s; + ssize_t r = pread(fd, scratch, n, static_cast(offset)); + *result = Slice(scratch, (r < 0) ? 0 : r); + if (r < 0) { + // An error: return a non-ok status + s = IOError(filename_, errno); + } + if (temporary_fd_) { + // Close the temporary file descriptor opened earlier. + close(fd); + } + return s; + } +}; + +// mmap() based random-access +class PosixMmapReadableFile: public RandomAccessFile { + private: + std::string filename_; + void* mmapped_region_; + size_t length_; + Limiter* limiter_; + + public: + // base[0,length-1] contains the mmapped contents of the file. + PosixMmapReadableFile(const std::string& fname, void* base, size_t length, + Limiter* limiter) + : filename_(fname), mmapped_region_(base), length_(length), + limiter_(limiter) { + } + + virtual ~PosixMmapReadableFile() { + munmap(mmapped_region_, length_); + limiter_->Release(); + } + + virtual Status Read(uint64_t offset, size_t n, Slice* result, + char* scratch) const { + Status s; + if (offset + n > length_) { + *result = Slice(); + s = IOError(filename_, EINVAL); + } else { + *result = Slice(reinterpret_cast(mmapped_region_) + offset, n); + } + return s; + } +}; + +class PosixWritableFile : public WritableFile { + private: + std::string filename_; + FILE* file_; + + public: + PosixWritableFile(const std::string& fname, FILE* f) + : filename_(fname), file_(f) { } + + ~PosixWritableFile() { + if (file_ != NULL) { + // Ignoring any potential errors + fclose(file_); + } + } + + virtual Status Append(const Slice& data) { + size_t r = fwrite_unlocked(data.data(), 1, data.size(), file_); + if (r != data.size()) { + return IOError(filename_, errno); + } + return Status::OK(); + } + + virtual Status Close() { + Status result; + if (fclose(file_) != 0) { + result = IOError(filename_, errno); + } + file_ = NULL; + return result; + } + + virtual Status Flush() { + if (fflush_unlocked(file_) != 0) { + return IOError(filename_, errno); + } + return Status::OK(); + } + + Status SyncDirIfManifest() { + const char* f = filename_.c_str(); + const char* sep = strrchr(f, '/'); + Slice basename; + std::string dir; + if (sep == NULL) { + dir = "."; + basename = f; + } else { + dir = std::string(f, sep - f); + basename = sep + 1; + } + Status s; + if (basename.starts_with("MANIFEST")) { + int fd = open(dir.c_str(), O_RDONLY); + if (fd < 0) { + s = IOError(dir, errno); + } else { + if (fsync(fd) < 0) { + s = IOError(dir, errno); + } + close(fd); + } + } + return s; + } + + virtual Status Sync() { + // Ensure new files referred to by the manifest are in the filesystem. + Status s = SyncDirIfManifest(); + if (!s.ok()) { + return s; + } + if (fflush_unlocked(file_) != 0 || + fdatasync(fileno(file_)) != 0) { + s = Status::IOError(filename_, strerror(errno)); + } + return s; + } +}; + +static int LockOrUnlock(int fd, bool lock) { + errno = 0; + struct flock f; + memset(&f, 0, sizeof(f)); + f.l_type = (lock ? F_WRLCK : F_UNLCK); + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; // Lock/unlock entire file + return fcntl(fd, F_SETLK, &f); +} + +class PosixFileLock : public FileLock { + public: + int fd_; + std::string name_; +}; + +// Set of locked files. We keep a separate set instead of just +// relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide +// any protection against multiple uses from the same process. +class PosixLockTable { + private: + port::Mutex mu_; + std::set locked_files_; + public: + bool Insert(const std::string& fname) { + MutexLock l(&mu_); + return locked_files_.insert(fname).second; + } + void Remove(const std::string& fname) { + MutexLock l(&mu_); + locked_files_.erase(fname); + } +}; + +class PosixEnv : public Env { + public: + PosixEnv(); + virtual ~PosixEnv() { + char msg[] = "Destroying Env::Default()\n"; + fwrite(msg, 1, sizeof(msg), stderr); + abort(); + } + + virtual Status NewSequentialFile(const std::string& fname, + SequentialFile** result) { + FILE* f = fopen(fname.c_str(), "r"); + if (f == NULL) { + *result = NULL; + return IOError(fname, errno); + } else { + *result = new PosixSequentialFile(fname, f); + return Status::OK(); + } + } + + virtual Status NewRandomAccessFile(const std::string& fname, + RandomAccessFile** result) { + *result = NULL; + Status s; + int fd = open(fname.c_str(), O_RDONLY); + if (fd < 0) { + s = IOError(fname, errno); + } else if (mmap_limit_.Acquire()) { + uint64_t size; + s = GetFileSize(fname, &size); + if (s.ok()) { + void* base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); + if (base != MAP_FAILED) { + *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_); + } else { + s = IOError(fname, errno); + } + } + close(fd); + if (!s.ok()) { + mmap_limit_.Release(); + } + } else { + *result = new PosixRandomAccessFile(fname, fd, &fd_limit_); + } + return s; + } + + virtual Status NewWritableFile(const std::string& fname, + WritableFile** result) { + Status s; + FILE* f = fopen(fname.c_str(), "w"); + if (f == NULL) { + *result = NULL; + s = IOError(fname, errno); + } else { + *result = new PosixWritableFile(fname, f); + } + return s; + } + + virtual Status NewAppendableFile(const std::string& fname, + WritableFile** result) { + Status s; + FILE* f = fopen(fname.c_str(), "a"); + if (f == NULL) { + *result = NULL; + s = IOError(fname, errno); + } else { + *result = new PosixWritableFile(fname, f); + } + return s; + } + + virtual bool FileExists(const std::string& fname) { + return access(fname.c_str(), F_OK) == 0; + } + + virtual Status GetChildren(const std::string& dir, + std::vector* result) { + result->clear(); + DIR* d = opendir(dir.c_str()); + if (d == NULL) { + return IOError(dir, errno); + } + struct dirent* entry; + while ((entry = readdir(d)) != NULL) { + result->push_back(entry->d_name); + } + closedir(d); + return Status::OK(); + } + + virtual Status DeleteFile(const std::string& fname) { + Status result; + if (unlink(fname.c_str()) != 0) { + result = IOError(fname, errno); + } + return result; + } + + virtual Status CreateDir(const std::string& name) { + Status result; + if (mkdir(name.c_str(), 0755) != 0) { + result = IOError(name, errno); + } + return result; + } + + virtual Status DeleteDir(const std::string& name) { + Status result; + if (rmdir(name.c_str()) != 0) { + result = IOError(name, errno); + } + return result; + } + + virtual Status GetFileSize(const std::string& fname, uint64_t* size) { + Status s; + struct stat sbuf; + if (stat(fname.c_str(), &sbuf) != 0) { + *size = 0; + s = IOError(fname, errno); + } else { + *size = sbuf.st_size; + } + return s; + } + + virtual Status RenameFile(const std::string& src, const std::string& target) { + Status result; + if (rename(src.c_str(), target.c_str()) != 0) { + result = IOError(src, errno); + } + return result; + } + + virtual Status LockFile(const std::string& fname, FileLock** lock) { + *lock = NULL; + Status result; + int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644); + if (fd < 0) { + result = IOError(fname, errno); + } else if (!locks_.Insert(fname)) { + close(fd); + result = Status::IOError("lock " + fname, "already held by process"); + } else if (LockOrUnlock(fd, true) == -1) { + result = IOError("lock " + fname, errno); + close(fd); + locks_.Remove(fname); + } else { + PosixFileLock* my_lock = new PosixFileLock; + my_lock->fd_ = fd; + my_lock->name_ = fname; + *lock = my_lock; + } + return result; + } + + virtual Status UnlockFile(FileLock* lock) { + PosixFileLock* my_lock = reinterpret_cast(lock); + Status result; + if (LockOrUnlock(my_lock->fd_, false) == -1) { + result = IOError("unlock", errno); + } + locks_.Remove(my_lock->name_); + close(my_lock->fd_); + delete my_lock; + return result; + } + + virtual void Schedule(void (*function)(void*), void* arg); + + virtual void StartThread(void (*function)(void* arg), void* arg); + + virtual Status GetTestDirectory(std::string* result) { + const char* env = getenv("TEST_TMPDIR"); + if (env && env[0] != '\0') { + *result = env; + } else { + char buf[100]; + snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid())); + *result = buf; + } + // Directory may already exist + CreateDir(*result); + return Status::OK(); + } + + static uint64_t gettid() { + pthread_t tid = pthread_self(); + uint64_t thread_id = 0; + memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid))); + return thread_id; + } + + virtual Status NewLogger(const std::string& fname, Logger** result) { + FILE* f = fopen(fname.c_str(), "w"); + if (f == NULL) { + *result = NULL; + return IOError(fname, errno); + } else { + *result = new PosixLogger(f, &PosixEnv::gettid); + return Status::OK(); + } + } + + virtual uint64_t NowMicros() { + struct timeval tv; + gettimeofday(&tv, NULL); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; + } + + virtual void SleepForMicroseconds(int micros) { + usleep(micros); + } + + private: + void PthreadCall(const char* label, int result) { + if (result != 0) { + fprintf(stderr, "pthread %s: %s\n", label, strerror(result)); + abort(); + } + } + + // BGThread() is the body of the background thread + void BGThread(); + static void* BGThreadWrapper(void* arg) { + reinterpret_cast(arg)->BGThread(); + return NULL; + } + + pthread_mutex_t mu_; + pthread_cond_t bgsignal_; + pthread_t bgthread_; + bool started_bgthread_; + + // Entry per Schedule() call + struct BGItem { void* arg; void (*function)(void*); }; + typedef std::deque BGQueue; + BGQueue queue_; + + PosixLockTable locks_; + Limiter mmap_limit_; + Limiter fd_limit_; +}; + +// Return the maximum number of concurrent mmaps. +static int MaxMmaps() { + if (mmap_limit >= 0) { + return mmap_limit; + } + // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes. + mmap_limit = sizeof(void*) >= 8 ? 1000 : 0; + return mmap_limit; +} + +// Return the maximum number of read-only files to keep open. +static intptr_t MaxOpenFiles() { + if (open_read_only_file_limit >= 0) { + return open_read_only_file_limit; + } + struct rlimit rlim; + if (getrlimit(RLIMIT_NOFILE, &rlim)) { + // getrlimit failed, fallback to hard-coded default. + open_read_only_file_limit = 50; + } else if (rlim.rlim_cur == RLIM_INFINITY) { + open_read_only_file_limit = std::numeric_limits::max(); + } else { + // Allow use of 20% of available file descriptors for read-only files. + open_read_only_file_limit = rlim.rlim_cur / 5; + } + return open_read_only_file_limit; +} + +PosixEnv::PosixEnv() + : started_bgthread_(false), + mmap_limit_(MaxMmaps()), + fd_limit_(MaxOpenFiles()) { + PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL)); + PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL)); +} + +void PosixEnv::Schedule(void (*function)(void*), void* arg) { + PthreadCall("lock", pthread_mutex_lock(&mu_)); + + // Start background thread if necessary + if (!started_bgthread_) { + started_bgthread_ = true; + PthreadCall( + "create thread", + pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this)); + } + + // If the queue is currently empty, the background thread may currently be + // waiting. + if (queue_.empty()) { + PthreadCall("signal", pthread_cond_signal(&bgsignal_)); + } + + // Add to priority queue + queue_.push_back(BGItem()); + queue_.back().function = function; + queue_.back().arg = arg; + + PthreadCall("unlock", pthread_mutex_unlock(&mu_)); +} + +void PosixEnv::BGThread() { + while (true) { + // Wait until there is an item that is ready to run + PthreadCall("lock", pthread_mutex_lock(&mu_)); + while (queue_.empty()) { + PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_)); + } + + void (*function)(void*) = queue_.front().function; + void* arg = queue_.front().arg; + queue_.pop_front(); + + PthreadCall("unlock", pthread_mutex_unlock(&mu_)); + (*function)(arg); + } +} + +namespace { +struct StartThreadState { + void (*user_function)(void*); + void* arg; +}; +} +static void* StartThreadWrapper(void* arg) { + StartThreadState* state = reinterpret_cast(arg); + state->user_function(state->arg); + delete state; + return NULL; +} + +void PosixEnv::StartThread(void (*function)(void* arg), void* arg) { + pthread_t t; + StartThreadState* state = new StartThreadState; + state->user_function = function; + state->arg = arg; + PthreadCall("start thread", + pthread_create(&t, NULL, &StartThreadWrapper, state)); +} + +} // namespace + +static pthread_once_t once = PTHREAD_ONCE_INIT; +static Env* default_env; +static void InitDefaultEnv() { default_env = new PosixEnv; } + +void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit) { + assert(default_env == NULL); + open_read_only_file_limit = limit; +} + +void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit) { + assert(default_env == NULL); + mmap_limit = limit; +} + +Env* Env::Default() { + pthread_once(&once, InitDefaultEnv); + return default_env; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/env_posix_test_helper.h b/My Mind/Pods/leveldb-library/util/env_posix_test_helper.h new file mode 100644 index 0000000..0386960 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/env_posix_test_helper.h @@ -0,0 +1,28 @@ +// Copyright 2017 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_ +#define STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_ + +namespace leveldb { + +class EnvPosixTest; + +// A helper for the POSIX Env to facilitate testing. +class EnvPosixTestHelper { + private: + friend class EnvPosixTest; + + // Set the maximum number of read-only files that will be opened. + // Must be called before creating an Env. + static void SetReadOnlyFDLimit(int limit); + + // Set the maximum number of read-only files that will be mapped via mmap. + // Must be called before creating an Env. + static void SetReadOnlyMMapLimit(int limit); +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_ENV_POSIX_TEST_HELPER_H_ diff --git a/My Mind/Pods/leveldb-library/util/filter_policy.cc b/My Mind/Pods/leveldb-library/util/filter_policy.cc new file mode 100644 index 0000000..7b045c8 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/filter_policy.cc @@ -0,0 +1,11 @@ +// Copyright (c) 2012 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/filter_policy.h" + +namespace leveldb { + +FilterPolicy::~FilterPolicy() { } + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/hash.cc b/My Mind/Pods/leveldb-library/util/hash.cc new file mode 100644 index 0000000..ed439ce --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/hash.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include "util/coding.h" +#include "util/hash.h" + +// The FALLTHROUGH_INTENDED macro can be used to annotate implicit fall-through +// between switch labels. The real definition should be provided externally. +// This one is a fallback version for unsupported compilers. +#ifndef FALLTHROUGH_INTENDED +#define FALLTHROUGH_INTENDED do { } while (0) +#endif + +namespace leveldb { + +uint32_t Hash(const char* data, size_t n, uint32_t seed) { + // Similar to murmur hash + const uint32_t m = 0xc6a4a793; + const uint32_t r = 24; + const char* limit = data + n; + uint32_t h = seed ^ (n * m); + + // Pick up four bytes at a time + while (data + 4 <= limit) { + uint32_t w = DecodeFixed32(data); + data += 4; + h += w; + h *= m; + h ^= (h >> 16); + } + + // Pick up remaining bytes + switch (limit - data) { + case 3: + h += static_cast(data[2]) << 16; + FALLTHROUGH_INTENDED; + case 2: + h += static_cast(data[1]) << 8; + FALLTHROUGH_INTENDED; + case 1: + h += static_cast(data[0]); + h *= m; + h ^= (h >> r); + break; + } + return h; +} + + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/hash.h b/My Mind/Pods/leveldb-library/util/hash.h new file mode 100644 index 0000000..8889d56 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/hash.h @@ -0,0 +1,19 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Simple hash function used for internal data structures + +#ifndef STORAGE_LEVELDB_UTIL_HASH_H_ +#define STORAGE_LEVELDB_UTIL_HASH_H_ + +#include +#include + +namespace leveldb { + +extern uint32_t Hash(const char* data, size_t n, uint32_t seed); + +} + +#endif // STORAGE_LEVELDB_UTIL_HASH_H_ diff --git a/My Mind/Pods/leveldb-library/util/histogram.cc b/My Mind/Pods/leveldb-library/util/histogram.cc new file mode 100644 index 0000000..bb95f58 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/histogram.cc @@ -0,0 +1,139 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include +#include "port/port.h" +#include "util/histogram.h" + +namespace leveldb { + +const double Histogram::kBucketLimit[kNumBuckets] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 25, 30, 35, 40, 45, + 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200, 250, 300, 350, 400, 450, + 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, + 3500, 4000, 4500, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000, + 16000, 18000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 60000, + 70000, 80000, 90000, 100000, 120000, 140000, 160000, 180000, 200000, + 250000, 300000, 350000, 400000, 450000, 500000, 600000, 700000, 800000, + 900000, 1000000, 1200000, 1400000, 1600000, 1800000, 2000000, 2500000, + 3000000, 3500000, 4000000, 4500000, 5000000, 6000000, 7000000, 8000000, + 9000000, 10000000, 12000000, 14000000, 16000000, 18000000, 20000000, + 25000000, 30000000, 35000000, 40000000, 45000000, 50000000, 60000000, + 70000000, 80000000, 90000000, 100000000, 120000000, 140000000, 160000000, + 180000000, 200000000, 250000000, 300000000, 350000000, 400000000, + 450000000, 500000000, 600000000, 700000000, 800000000, 900000000, + 1000000000, 1200000000, 1400000000, 1600000000, 1800000000, 2000000000, + 2500000000.0, 3000000000.0, 3500000000.0, 4000000000.0, 4500000000.0, + 5000000000.0, 6000000000.0, 7000000000.0, 8000000000.0, 9000000000.0, + 1e200, +}; + +void Histogram::Clear() { + min_ = kBucketLimit[kNumBuckets-1]; + max_ = 0; + num_ = 0; + sum_ = 0; + sum_squares_ = 0; + for (int i = 0; i < kNumBuckets; i++) { + buckets_[i] = 0; + } +} + +void Histogram::Add(double value) { + // Linear search is fast enough for our usage in db_bench + int b = 0; + while (b < kNumBuckets - 1 && kBucketLimit[b] <= value) { + b++; + } + buckets_[b] += 1.0; + if (min_ > value) min_ = value; + if (max_ < value) max_ = value; + num_++; + sum_ += value; + sum_squares_ += (value * value); +} + +void Histogram::Merge(const Histogram& other) { + if (other.min_ < min_) min_ = other.min_; + if (other.max_ > max_) max_ = other.max_; + num_ += other.num_; + sum_ += other.sum_; + sum_squares_ += other.sum_squares_; + for (int b = 0; b < kNumBuckets; b++) { + buckets_[b] += other.buckets_[b]; + } +} + +double Histogram::Median() const { + return Percentile(50.0); +} + +double Histogram::Percentile(double p) const { + double threshold = num_ * (p / 100.0); + double sum = 0; + for (int b = 0; b < kNumBuckets; b++) { + sum += buckets_[b]; + if (sum >= threshold) { + // Scale linearly within this bucket + double left_point = (b == 0) ? 0 : kBucketLimit[b-1]; + double right_point = kBucketLimit[b]; + double left_sum = sum - buckets_[b]; + double right_sum = sum; + double pos = (threshold - left_sum) / (right_sum - left_sum); + double r = left_point + (right_point - left_point) * pos; + if (r < min_) r = min_; + if (r > max_) r = max_; + return r; + } + } + return max_; +} + +double Histogram::Average() const { + if (num_ == 0.0) return 0; + return sum_ / num_; +} + +double Histogram::StandardDeviation() const { + if (num_ == 0.0) return 0; + double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_); + return sqrt(variance); +} + +std::string Histogram::ToString() const { + std::string r; + char buf[200]; + snprintf(buf, sizeof(buf), + "Count: %.0f Average: %.4f StdDev: %.2f\n", + num_, Average(), StandardDeviation()); + r.append(buf); + snprintf(buf, sizeof(buf), + "Min: %.4f Median: %.4f Max: %.4f\n", + (num_ == 0.0 ? 0.0 : min_), Median(), max_); + r.append(buf); + r.append("------------------------------------------------------\n"); + const double mult = 100.0 / num_; + double sum = 0; + for (int b = 0; b < kNumBuckets; b++) { + if (buckets_[b] <= 0.0) continue; + sum += buckets_[b]; + snprintf(buf, sizeof(buf), + "[ %7.0f, %7.0f ) %7.0f %7.3f%% %7.3f%% ", + ((b == 0) ? 0.0 : kBucketLimit[b-1]), // left + kBucketLimit[b], // right + buckets_[b], // count + mult * buckets_[b], // percentage + mult * sum); // cumulative percentage + r.append(buf); + + // Add hash marks based on percentage; 20 marks for 100%. + int marks = static_cast(20*(buckets_[b] / num_) + 0.5); + r.append(marks, '#'); + r.push_back('\n'); + } + return r; +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/histogram.h b/My Mind/Pods/leveldb-library/util/histogram.h new file mode 100644 index 0000000..1ef9f3c --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/histogram.h @@ -0,0 +1,42 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_HISTOGRAM_H_ +#define STORAGE_LEVELDB_UTIL_HISTOGRAM_H_ + +#include + +namespace leveldb { + +class Histogram { + public: + Histogram() { } + ~Histogram() { } + + void Clear(); + void Add(double value); + void Merge(const Histogram& other); + + std::string ToString() const; + + private: + double min_; + double max_; + double num_; + double sum_; + double sum_squares_; + + enum { kNumBuckets = 154 }; + static const double kBucketLimit[kNumBuckets]; + double buckets_[kNumBuckets]; + + double Median() const; + double Percentile(double p) const; + double Average() const; + double StandardDeviation() const; +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_HISTOGRAM_H_ diff --git a/My Mind/Pods/leveldb-library/util/logging.cc b/My Mind/Pods/leveldb-library/util/logging.cc new file mode 100644 index 0000000..ca6b324 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/logging.cc @@ -0,0 +1,72 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "util/logging.h" + +#include +#include +#include +#include +#include "leveldb/env.h" +#include "leveldb/slice.h" + +namespace leveldb { + +void AppendNumberTo(std::string* str, uint64_t num) { + char buf[30]; + snprintf(buf, sizeof(buf), "%llu", (unsigned long long) num); + str->append(buf); +} + +void AppendEscapedStringTo(std::string* str, const Slice& value) { + for (size_t i = 0; i < value.size(); i++) { + char c = value[i]; + if (c >= ' ' && c <= '~') { + str->push_back(c); + } else { + char buf[10]; + snprintf(buf, sizeof(buf), "\\x%02x", + static_cast(c) & 0xff); + str->append(buf); + } + } +} + +std::string NumberToString(uint64_t num) { + std::string r; + AppendNumberTo(&r, num); + return r; +} + +std::string EscapeString(const Slice& value) { + std::string r; + AppendEscapedStringTo(&r, value); + return r; +} + +bool ConsumeDecimalNumber(Slice* in, uint64_t* val) { + uint64_t v = 0; + int digits = 0; + while (!in->empty()) { + char c = (*in)[0]; + if (c >= '0' && c <= '9') { + ++digits; + const int delta = (c - '0'); + static const uint64_t kMaxUint64 = ~static_cast(0); + if (v > kMaxUint64/10 || + (v == kMaxUint64/10 && delta > kMaxUint64%10)) { + // Overflow + return false; + } + v = (v * 10) + delta; + in->remove_prefix(1); + } else { + break; + } + } + *val = v; + return (digits > 0); +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/logging.h b/My Mind/Pods/leveldb-library/util/logging.h new file mode 100644 index 0000000..1b450d2 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/logging.h @@ -0,0 +1,43 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Must not be included from any .h files to avoid polluting the namespace +// with macros. + +#ifndef STORAGE_LEVELDB_UTIL_LOGGING_H_ +#define STORAGE_LEVELDB_UTIL_LOGGING_H_ + +#include +#include +#include +#include "port/port.h" + +namespace leveldb { + +class Slice; +class WritableFile; + +// Append a human-readable printout of "num" to *str +extern void AppendNumberTo(std::string* str, uint64_t num); + +// Append a human-readable printout of "value" to *str. +// Escapes any non-printable characters found in "value". +extern void AppendEscapedStringTo(std::string* str, const Slice& value); + +// Return a human-readable printout of "num" +extern std::string NumberToString(uint64_t num); + +// Return a human-readable version of "value". +// Escapes any non-printable characters found in "value". +extern std::string EscapeString(const Slice& value); + +// Parse a human-readable number from "*in" into *value. On success, +// advances "*in" past the consumed number and sets "*val" to the +// numeric value. Otherwise, returns false and leaves *in in an +// unspecified state. +extern bool ConsumeDecimalNumber(Slice* in, uint64_t* val); + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_LOGGING_H_ diff --git a/My Mind/Pods/leveldb-library/util/mutexlock.h b/My Mind/Pods/leveldb-library/util/mutexlock.h new file mode 100644 index 0000000..1ff5a9e --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/mutexlock.h @@ -0,0 +1,41 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ +#define STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ + +#include "port/port.h" +#include "port/thread_annotations.h" + +namespace leveldb { + +// Helper class that locks a mutex on construction and unlocks the mutex when +// the destructor of the MutexLock object is invoked. +// +// Typical usage: +// +// void MyClass::MyMethod() { +// MutexLock l(&mu_); // mu_ is an instance variable +// ... some complex code, possibly with multiple return paths ... +// } + +class SCOPED_LOCKABLE MutexLock { + public: + explicit MutexLock(port::Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) + : mu_(mu) { + this->mu_->Lock(); + } + ~MutexLock() UNLOCK_FUNCTION() { this->mu_->Unlock(); } + + private: + port::Mutex *const mu_; + // No copying allowed + MutexLock(const MutexLock&); + void operator=(const MutexLock&); +}; + +} // namespace leveldb + + +#endif // STORAGE_LEVELDB_UTIL_MUTEXLOCK_H_ diff --git a/My Mind/Pods/leveldb-library/util/options.cc b/My Mind/Pods/leveldb-library/util/options.cc new file mode 100644 index 0000000..b5e6227 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/options.cc @@ -0,0 +1,30 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "leveldb/options.h" + +#include "leveldb/comparator.h" +#include "leveldb/env.h" + +namespace leveldb { + +Options::Options() + : comparator(BytewiseComparator()), + create_if_missing(false), + error_if_exists(false), + paranoid_checks(false), + env(Env::Default()), + info_log(NULL), + write_buffer_size(4<<20), + max_open_files(1000), + block_cache(NULL), + block_size(4096), + block_restart_interval(16), + max_file_size(2<<20), + compression(kSnappyCompression), + reuse_logs(false), + filter_policy(NULL) { +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/posix_logger.h b/My Mind/Pods/leveldb-library/util/posix_logger.h new file mode 100644 index 0000000..9741b1a --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/posix_logger.h @@ -0,0 +1,98 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// Logger implementation that can be shared by all environments +// where enough posix functionality is available. + +#ifndef STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_ +#define STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_ + +#include +#include +#include +#include +#include "leveldb/env.h" + +namespace leveldb { + +class PosixLogger : public Logger { + private: + FILE* file_; + uint64_t (*gettid_)(); // Return the thread id for the current thread + public: + PosixLogger(FILE* f, uint64_t (*gettid)()) : file_(f), gettid_(gettid) { } + virtual ~PosixLogger() { + fclose(file_); + } + virtual void Logv(const char* format, va_list ap) { + const uint64_t thread_id = (*gettid_)(); + + // We try twice: the first time with a fixed-size stack allocated buffer, + // and the second time with a much larger dynamically allocated buffer. + char buffer[500]; + for (int iter = 0; iter < 2; iter++) { + char* base; + int bufsize; + if (iter == 0) { + bufsize = sizeof(buffer); + base = buffer; + } else { + bufsize = 30000; + base = new char[bufsize]; + } + char* p = base; + char* limit = base + bufsize; + + struct timeval now_tv; + gettimeofday(&now_tv, NULL); + const time_t seconds = now_tv.tv_sec; + struct tm t; + localtime_r(&seconds, &t); + p += snprintf(p, limit - p, + "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ", + t.tm_year + 1900, + t.tm_mon + 1, + t.tm_mday, + t.tm_hour, + t.tm_min, + t.tm_sec, + static_cast(now_tv.tv_usec), + static_cast(thread_id)); + + // Print the message + if (p < limit) { + va_list backup_ap; + va_copy(backup_ap, ap); + p += vsnprintf(p, limit - p, format, backup_ap); + va_end(backup_ap); + } + + // Truncate to available space if necessary + if (p >= limit) { + if (iter == 0) { + continue; // Try again with larger buffer + } else { + p = limit - 1; + } + } + + // Add newline if necessary + if (p == base || p[-1] != '\n') { + *p++ = '\n'; + } + + assert(p <= limit); + fwrite(base, 1, p - base, file_); + fflush(file_); + if (base != buffer) { + delete[] base; + } + break; + } + } +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_POSIX_LOGGER_H_ diff --git a/My Mind/Pods/leveldb-library/util/random.h b/My Mind/Pods/leveldb-library/util/random.h new file mode 100644 index 0000000..ddd51b1 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/random.h @@ -0,0 +1,64 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_ +#define STORAGE_LEVELDB_UTIL_RANDOM_H_ + +#include + +namespace leveldb { + +// A very simple random number generator. Not especially good at +// generating truly random bits, but good enough for our needs in this +// package. +class Random { + private: + uint32_t seed_; + public: + explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) { + // Avoid bad seeds. + if (seed_ == 0 || seed_ == 2147483647L) { + seed_ = 1; + } + } + uint32_t Next() { + static const uint32_t M = 2147483647L; // 2^31-1 + static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0 + // We are computing + // seed_ = (seed_ * A) % M, where M = 2^31-1 + // + // seed_ must not be zero or M, or else all subsequent computed values + // will be zero or M respectively. For all other values, seed_ will end + // up cycling through every number in [1,M-1] + uint64_t product = seed_ * A; + + // Compute (product % M) using the fact that ((x << 31) % M) == x. + seed_ = static_cast((product >> 31) + (product & M)); + // The first reduction may overflow by 1 bit, so we may need to + // repeat. mod == M is not possible; using > allows the faster + // sign-bit-based test. + if (seed_ > M) { + seed_ -= M; + } + return seed_; + } + // Returns a uniformly distributed value in the range [0..n-1] + // REQUIRES: n > 0 + uint32_t Uniform(int n) { return Next() % n; } + + // Randomly returns true ~"1/n" of the time, and false otherwise. + // REQUIRES: n > 0 + bool OneIn(int n) { return (Next() % n) == 0; } + + // Skewed: pick "base" uniformly from range [0,max_log] and then + // return "base" random bits. The effect is to pick a number in the + // range [0,2^max_log-1] with exponential bias towards smaller numbers. + uint32_t Skewed(int max_log) { + return Uniform(1 << Uniform(max_log + 1)); + } +}; + +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_RANDOM_H_ diff --git a/My Mind/Pods/leveldb-library/util/status.cc b/My Mind/Pods/leveldb-library/util/status.cc new file mode 100644 index 0000000..a44f35b --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/status.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include +#include "port/port.h" +#include "leveldb/status.h" + +namespace leveldb { + +const char* Status::CopyState(const char* state) { + uint32_t size; + memcpy(&size, state, sizeof(size)); + char* result = new char[size + 5]; + memcpy(result, state, size + 5); + return result; +} + +Status::Status(Code code, const Slice& msg, const Slice& msg2) { + assert(code != kOk); + const uint32_t len1 = msg.size(); + const uint32_t len2 = msg2.size(); + const uint32_t size = len1 + (len2 ? (2 + len2) : 0); + char* result = new char[size + 5]; + memcpy(result, &size, sizeof(size)); + result[4] = static_cast(code); + memcpy(result + 5, msg.data(), len1); + if (len2) { + result[5 + len1] = ':'; + result[6 + len1] = ' '; + memcpy(result + 7 + len1, msg2.data(), len2); + } + state_ = result; +} + +std::string Status::ToString() const { + if (state_ == NULL) { + return "OK"; + } else { + char tmp[30]; + const char* type; + switch (code()) { + case kOk: + type = "OK"; + break; + case kNotFound: + type = "NotFound: "; + break; + case kCorruption: + type = "Corruption: "; + break; + case kNotSupported: + type = "Not implemented: "; + break; + case kInvalidArgument: + type = "Invalid argument: "; + break; + case kIOError: + type = "IO error: "; + break; + default: + snprintf(tmp, sizeof(tmp), "Unknown code(%d): ", + static_cast(code())); + type = tmp; + break; + } + std::string result(type); + uint32_t length; + memcpy(&length, state_, sizeof(length)); + result.append(state_ + 5, length); + return result; + } +} + +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/testharness.cc b/My Mind/Pods/leveldb-library/util/testharness.cc new file mode 100644 index 0000000..402fab3 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/testharness.cc @@ -0,0 +1,77 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "util/testharness.h" + +#include +#include +#include +#include + +namespace leveldb { +namespace test { + +namespace { +struct Test { + const char* base; + const char* name; + void (*func)(); +}; +std::vector* tests; +} + +bool RegisterTest(const char* base, const char* name, void (*func)()) { + if (tests == NULL) { + tests = new std::vector; + } + Test t; + t.base = base; + t.name = name; + t.func = func; + tests->push_back(t); + return true; +} + +int RunAllTests() { + const char* matcher = getenv("LEVELDB_TESTS"); + + int num = 0; + if (tests != NULL) { + for (size_t i = 0; i < tests->size(); i++) { + const Test& t = (*tests)[i]; + if (matcher != NULL) { + std::string name = t.base; + name.push_back('.'); + name.append(t.name); + if (strstr(name.c_str(), matcher) == NULL) { + continue; + } + } + fprintf(stderr, "==== Test %s.%s\n", t.base, t.name); + (*t.func)(); + ++num; + } + } + fprintf(stderr, "==== PASSED %d tests\n", num); + return 0; +} + +std::string TmpDir() { + std::string dir; + Status s = Env::Default()->GetTestDirectory(&dir); + ASSERT_TRUE(s.ok()) << s.ToString(); + return dir; +} + +int RandomSeed() { + const char* env = getenv("TEST_RANDOM_SEED"); + int result = (env != NULL ? atoi(env) : 301); + if (result <= 0) { + result = 301; + } + return result; +} + +} // namespace test +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/testharness.h b/My Mind/Pods/leveldb-library/util/testharness.h new file mode 100644 index 0000000..da4fe68 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/testharness.h @@ -0,0 +1,138 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_TESTHARNESS_H_ +#define STORAGE_LEVELDB_UTIL_TESTHARNESS_H_ + +#include +#include +#include +#include "leveldb/env.h" +#include "leveldb/slice.h" +#include "util/random.h" + +namespace leveldb { +namespace test { + +// Run some of the tests registered by the TEST() macro. If the +// environment variable "LEVELDB_TESTS" is not set, runs all tests. +// Otherwise, runs only the tests whose name contains the value of +// "LEVELDB_TESTS" as a substring. E.g., suppose the tests are: +// TEST(Foo, Hello) { ... } +// TEST(Foo, World) { ... } +// LEVELDB_TESTS=Hello will run the first test +// LEVELDB_TESTS=o will run both tests +// LEVELDB_TESTS=Junk will run no tests +// +// Returns 0 if all tests pass. +// Dies or returns a non-zero value if some test fails. +extern int RunAllTests(); + +// Return the directory to use for temporary storage. +extern std::string TmpDir(); + +// Return a randomization seed for this run. Typically returns the +// same number on repeated invocations of this binary, but automated +// runs may be able to vary the seed. +extern int RandomSeed(); + +// An instance of Tester is allocated to hold temporary state during +// the execution of an assertion. +class Tester { + private: + bool ok_; + const char* fname_; + int line_; + std::stringstream ss_; + + public: + Tester(const char* f, int l) + : ok_(true), fname_(f), line_(l) { + } + + ~Tester() { + if (!ok_) { + fprintf(stderr, "%s:%d:%s\n", fname_, line_, ss_.str().c_str()); + exit(1); + } + } + + Tester& Is(bool b, const char* msg) { + if (!b) { + ss_ << " Assertion failure " << msg; + ok_ = false; + } + return *this; + } + + Tester& IsOk(const Status& s) { + if (!s.ok()) { + ss_ << " " << s.ToString(); + ok_ = false; + } + return *this; + } + +#define BINARY_OP(name,op) \ + template \ + Tester& name(const X& x, const Y& y) { \ + if (! (x op y)) { \ + ss_ << " failed: " << x << (" " #op " ") << y; \ + ok_ = false; \ + } \ + return *this; \ + } + + BINARY_OP(IsEq, ==) + BINARY_OP(IsNe, !=) + BINARY_OP(IsGe, >=) + BINARY_OP(IsGt, >) + BINARY_OP(IsLe, <=) + BINARY_OP(IsLt, <) +#undef BINARY_OP + + // Attach the specified value to the error message if an error has occurred + template + Tester& operator<<(const V& value) { + if (!ok_) { + ss_ << " " << value; + } + return *this; + } +}; + +#define ASSERT_TRUE(c) ::leveldb::test::Tester(__FILE__, __LINE__).Is((c), #c) +#define ASSERT_OK(s) ::leveldb::test::Tester(__FILE__, __LINE__).IsOk((s)) +#define ASSERT_EQ(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsEq((a),(b)) +#define ASSERT_NE(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsNe((a),(b)) +#define ASSERT_GE(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsGe((a),(b)) +#define ASSERT_GT(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsGt((a),(b)) +#define ASSERT_LE(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsLe((a),(b)) +#define ASSERT_LT(a,b) ::leveldb::test::Tester(__FILE__, __LINE__).IsLt((a),(b)) + +#define TCONCAT(a,b) TCONCAT1(a,b) +#define TCONCAT1(a,b) a##b + +#define TEST(base,name) \ +class TCONCAT(_Test_,name) : public base { \ + public: \ + void _Run(); \ + static void _RunIt() { \ + TCONCAT(_Test_,name) t; \ + t._Run(); \ + } \ +}; \ +bool TCONCAT(_Test_ignored_,name) = \ + ::leveldb::test::RegisterTest(#base, #name, &TCONCAT(_Test_,name)::_RunIt); \ +void TCONCAT(_Test_,name)::_Run() + +// Register the specified test. Typically not used directly, but +// invoked via the macro expansion of TEST. +extern bool RegisterTest(const char* base, const char* name, void (*func)()); + + +} // namespace test +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_TESTHARNESS_H_ diff --git a/My Mind/Pods/leveldb-library/util/testutil.cc b/My Mind/Pods/leveldb-library/util/testutil.cc new file mode 100644 index 0000000..bee56bf --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/testutil.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#include "util/testutil.h" + +#include "util/random.h" + +namespace leveldb { +namespace test { + +Slice RandomString(Random* rnd, int len, std::string* dst) { + dst->resize(len); + for (int i = 0; i < len; i++) { + (*dst)[i] = static_cast(' ' + rnd->Uniform(95)); // ' ' .. '~' + } + return Slice(*dst); +} + +std::string RandomKey(Random* rnd, int len) { + // Make sure to generate a wide variety of characters so we + // test the boundary conditions for short-key optimizations. + static const char kTestChars[] = { + '\0', '\1', 'a', 'b', 'c', 'd', 'e', '\xfd', '\xfe', '\xff' + }; + std::string result; + for (int i = 0; i < len; i++) { + result += kTestChars[rnd->Uniform(sizeof(kTestChars))]; + } + return result; +} + + +extern Slice CompressibleString(Random* rnd, double compressed_fraction, + size_t len, std::string* dst) { + int raw = static_cast(len * compressed_fraction); + if (raw < 1) raw = 1; + std::string raw_data; + RandomString(rnd, raw, &raw_data); + + // Duplicate the random data until we have filled "len" bytes + dst->clear(); + while (dst->size() < len) { + dst->append(raw_data); + } + dst->resize(len); + return Slice(*dst); +} + +} // namespace test +} // namespace leveldb diff --git a/My Mind/Pods/leveldb-library/util/testutil.h b/My Mind/Pods/leveldb-library/util/testutil.h new file mode 100644 index 0000000..d7e4583 --- /dev/null +++ b/My Mind/Pods/leveldb-library/util/testutil.h @@ -0,0 +1,63 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. + +#ifndef STORAGE_LEVELDB_UTIL_TESTUTIL_H_ +#define STORAGE_LEVELDB_UTIL_TESTUTIL_H_ + +#include "leveldb/env.h" +#include "leveldb/slice.h" +#include "util/random.h" + +namespace leveldb { +namespace test { + +// Store in *dst a random string of length "len" and return a Slice that +// references the generated data. +extern Slice RandomString(Random* rnd, int len, std::string* dst); + +// Return a random key with the specified length that may contain interesting +// characters (e.g. \x00, \xff, etc.). +extern std::string RandomKey(Random* rnd, int len); + +// Store in *dst a string of length "len" that will compress to +// "N*compressed_fraction" bytes and return a Slice that references +// the generated data. +extern Slice CompressibleString(Random* rnd, double compressed_fraction, + size_t len, std::string* dst); + +// A wrapper that allows injection of errors. +class ErrorEnv : public EnvWrapper { + public: + bool writable_file_error_; + int num_writable_file_errors_; + + ErrorEnv() : EnvWrapper(Env::Default()), + writable_file_error_(false), + num_writable_file_errors_(0) { } + + virtual Status NewWritableFile(const std::string& fname, + WritableFile** result) { + if (writable_file_error_) { + ++num_writable_file_errors_; + *result = NULL; + return Status::IOError(fname, "fake error"); + } + return target()->NewWritableFile(fname, result); + } + + virtual Status NewAppendableFile(const std::string& fname, + WritableFile** result) { + if (writable_file_error_) { + ++num_writable_file_errors_; + *result = NULL; + return Status::IOError(fname, "fake error"); + } + return target()->NewAppendableFile(fname, result); + } +}; + +} // namespace test +} // namespace leveldb + +#endif // STORAGE_LEVELDB_UTIL_TESTUTIL_H_ diff --git a/My Mind/Pods/nanopb/LICENSE.txt b/My Mind/Pods/nanopb/LICENSE.txt new file mode 100644 index 0000000..d11c9af --- /dev/null +++ b/My Mind/Pods/nanopb/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2011 Petteri Aimonen + +This software is provided 'as-is', without any express or +implied warranty. In no event will the authors be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. diff --git a/My Mind/Pods/nanopb/README.md b/My Mind/Pods/nanopb/README.md new file mode 100644 index 0000000..07860f0 --- /dev/null +++ b/My Mind/Pods/nanopb/README.md @@ -0,0 +1,71 @@ +Nanopb - Protocol Buffers for Embedded Systems +============================================== + +[![Build Status](https://travis-ci.org/nanopb/nanopb.svg?branch=master)](https://travis-ci.org/nanopb/nanopb) + +Nanopb is a small code-size Protocol Buffers implementation in ansi C. It is +especially suitable for use in microcontrollers, but fits any memory +restricted system. + +* **Homepage:** https://jpa.kapsi.fi/nanopb/ +* **Documentation:** https://jpa.kapsi.fi/nanopb/docs/ +* **Downloads:** https://jpa.kapsi.fi/nanopb/download/ +* **Forum:** https://groups.google.com/forum/#!forum/nanopb + + + +Using the nanopb library +------------------------ +To use the nanopb library, you need to do two things: + +1. Compile your .proto files for nanopb, using protoc. +2. Include pb_encode.c, pb_decode.c and pb_common.c in your project. + +The easiest way to get started is to study the project in "examples/simple". +It contains a Makefile, which should work directly under most Linux systems. +However, for any other kind of build system, see the manual steps in +README.txt in that folder. + + + +Using the Protocol Buffers compiler (protoc) +-------------------------------------------- +The nanopb generator is implemented as a plugin for the Google's own protoc +compiler. This has the advantage that there is no need to reimplement the +basic parsing of .proto files. However, it does mean that you need the +Google's protobuf library in order to run the generator. + +If you have downloaded a binary package for nanopb (either Windows, Linux or +Mac OS X version), the 'protoc' binary is included in the 'generator-bin' +folder. In this case, you are ready to go. Simply run this command: + + generator-bin/protoc --nanopb_out=. myprotocol.proto + +However, if you are using a git checkout or a plain source distribution, you +need to provide your own version of protoc and the Google's protobuf library. +On Linux, the necessary packages are protobuf-compiler and python-protobuf. +On Windows, you can either build Google's protobuf library from source or use +one of the binary distributions of it. In either case, if you use a separate +protoc, you need to manually give the path to nanopb generator: + + protoc --plugin=protoc-gen-nanopb=nanopb/generator/protoc-gen-nanopb ... + + + +Running the tests +----------------- +If you want to perform further development of the nanopb core, or to verify +its functionality using your compiler and platform, you'll want to run the +test suite. The build rules for the test suite are implemented using Scons, +so you need to have that installed. To run the tests: + + cd tests + scons + +This will show the progress of various test cases. If the output does not +end in an error, the test cases were successful. + +Note: Mac OS X by default aliases 'clang' as 'gcc', while not actually +supporting the same command line options as gcc does. To run tests on +Mac OS X, use: "scons CC=clang CXX=clang". Same way can be used to run +tests with different compilers on any platform. diff --git a/My Mind/Pods/nanopb/pb.h b/My Mind/Pods/nanopb/pb.h new file mode 100644 index 0000000..174a84b --- /dev/null +++ b/My Mind/Pods/nanopb/pb.h @@ -0,0 +1,593 @@ +/* Common parts of the nanopb library. Most of these are quite low-level + * stuff. For the high-level interface, see pb_encode.h and pb_decode.h. + */ + +#ifndef PB_H_INCLUDED +#define PB_H_INCLUDED + +/***************************************************************** + * Nanopb compilation time options. You can change these here by * + * uncommenting the lines, or on the compiler command line. * + *****************************************************************/ + +/* Enable support for dynamically allocated fields */ +/* #define PB_ENABLE_MALLOC 1 */ + +/* Define this if your CPU / compiler combination does not support + * unaligned memory access to packed structures. */ +/* #define PB_NO_PACKED_STRUCTS 1 */ + +/* Increase the number of required fields that are tracked. + * A compiler warning will tell if you need this. */ +/* #define PB_MAX_REQUIRED_FIELDS 256 */ + +/* Add support for tag numbers > 255 and fields larger than 255 bytes. */ +/* #define PB_FIELD_16BIT 1 */ + +/* Add support for tag numbers > 65536 and fields larger than 65536 bytes. */ +/* #define PB_FIELD_32BIT 1 */ + +/* Disable support for error messages in order to save some code space. */ +/* #define PB_NO_ERRMSG 1 */ + +/* Disable support for custom streams (support only memory buffers). */ +/* #define PB_BUFFER_ONLY 1 */ + +/* Switch back to the old-style callback function signature. + * This was the default until nanopb-0.2.1. */ +/* #define PB_OLD_CALLBACK_STYLE */ + + +/****************************************************************** + * You usually don't need to change anything below this line. * + * Feel free to look around and use the defined macros, though. * + ******************************************************************/ + + +/* Version of the nanopb library. Just in case you want to check it in + * your own program. */ +#define NANOPB_VERSION nanopb-0.3.9.1 + +/* Include all the system headers needed by nanopb. You will need the + * definitions of the following: + * - strlen, memcpy, memset functions + * - [u]int_least8_t, uint_fast8_t, [u]int_least16_t, [u]int32_t, [u]int64_t + * - size_t + * - bool + * + * If you don't have the standard header files, you can instead provide + * a custom header that defines or includes all this. In that case, + * define PB_SYSTEM_HEADER to the path of this file. + */ +#ifdef PB_SYSTEM_HEADER +#include PB_SYSTEM_HEADER +#else +#include +#include +#include +#include + +#ifdef PB_ENABLE_MALLOC +#include +#endif +#endif + +/* Macro for defining packed structures (compiler dependent). + * This just reduces memory requirements, but is not required. + */ +#if defined(PB_NO_PACKED_STRUCTS) + /* Disable struct packing */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed +#elif defined(__GNUC__) || defined(__clang__) + /* For GCC and clang */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed __attribute__((packed)) +#elif defined(__ICCARM__) || defined(__CC_ARM) + /* For IAR ARM and Keil MDK-ARM compilers */ +# define PB_PACKED_STRUCT_START _Pragma("pack(push, 1)") +# define PB_PACKED_STRUCT_END _Pragma("pack(pop)") +# define pb_packed +#elif defined(_MSC_VER) && (_MSC_VER >= 1500) + /* For Microsoft Visual C++ */ +# define PB_PACKED_STRUCT_START __pragma(pack(push, 1)) +# define PB_PACKED_STRUCT_END __pragma(pack(pop)) +# define pb_packed +#else + /* Unknown compiler */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed +#endif + +/* Handly macro for suppressing unreferenced-parameter compiler warnings. */ +#ifndef PB_UNUSED +#define PB_UNUSED(x) (void)(x) +#endif + +/* Compile-time assertion, used for checking compatible compilation options. + * If this does not work properly on your compiler, use + * #define PB_NO_STATIC_ASSERT to disable it. + * + * But before doing that, check carefully the error message / place where it + * comes from to see if the error has a real cause. Unfortunately the error + * message is not always very clear to read, but you can see the reason better + * in the place where the PB_STATIC_ASSERT macro was called. + */ +#ifndef PB_NO_STATIC_ASSERT +#ifndef PB_STATIC_ASSERT +#define PB_STATIC_ASSERT(COND,MSG) typedef char PB_STATIC_ASSERT_MSG(MSG, __LINE__, __COUNTER__)[(COND)?1:-1]; +#define PB_STATIC_ASSERT_MSG(MSG, LINE, COUNTER) PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) +#define PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) pb_static_assertion_##MSG##LINE##COUNTER +#endif +#else +#define PB_STATIC_ASSERT(COND,MSG) +#endif + +/* Number of required fields to keep track of. */ +#ifndef PB_MAX_REQUIRED_FIELDS +#define PB_MAX_REQUIRED_FIELDS 64 +#endif + +#if PB_MAX_REQUIRED_FIELDS < 64 +#error You should not lower PB_MAX_REQUIRED_FIELDS from the default value (64). +#endif + +/* List of possible field types. These are used in the autogenerated code. + * Least-significant 4 bits tell the scalar type + * Most-significant 4 bits specify repeated/required/packed etc. + */ + +typedef uint_least8_t pb_type_t; + +/**** Field data types ****/ + +/* Numeric types */ +#define PB_LTYPE_VARINT 0x00 /* int32, int64, enum, bool */ +#define PB_LTYPE_UVARINT 0x01 /* uint32, uint64 */ +#define PB_LTYPE_SVARINT 0x02 /* sint32, sint64 */ +#define PB_LTYPE_FIXED32 0x03 /* fixed32, sfixed32, float */ +#define PB_LTYPE_FIXED64 0x04 /* fixed64, sfixed64, double */ + +/* Marker for last packable field type. */ +#define PB_LTYPE_LAST_PACKABLE 0x04 + +/* Byte array with pre-allocated buffer. + * data_size is the length of the allocated PB_BYTES_ARRAY structure. */ +#define PB_LTYPE_BYTES 0x05 + +/* String with pre-allocated buffer. + * data_size is the maximum length. */ +#define PB_LTYPE_STRING 0x06 + +/* Submessage + * submsg_fields is pointer to field descriptions */ +#define PB_LTYPE_SUBMESSAGE 0x07 + +/* Extension pseudo-field + * The field contains a pointer to pb_extension_t */ +#define PB_LTYPE_EXTENSION 0x08 + +/* Byte array with inline, pre-allocated byffer. + * data_size is the length of the inline, allocated buffer. + * This differs from PB_LTYPE_BYTES by defining the element as + * pb_byte_t[data_size] rather than pb_bytes_array_t. */ +#define PB_LTYPE_FIXED_LENGTH_BYTES 0x09 + +/* Number of declared LTYPES */ +#define PB_LTYPES_COUNT 0x0A +#define PB_LTYPE_MASK 0x0F + +/**** Field repetition rules ****/ + +#define PB_HTYPE_REQUIRED 0x00 +#define PB_HTYPE_OPTIONAL 0x10 +#define PB_HTYPE_REPEATED 0x20 +#define PB_HTYPE_ONEOF 0x30 +#define PB_HTYPE_MASK 0x30 + +/**** Field allocation types ****/ + +#define PB_ATYPE_STATIC 0x00 +#define PB_ATYPE_POINTER 0x80 +#define PB_ATYPE_CALLBACK 0x40 +#define PB_ATYPE_MASK 0xC0 + +#define PB_ATYPE(x) ((x) & PB_ATYPE_MASK) +#define PB_HTYPE(x) ((x) & PB_HTYPE_MASK) +#define PB_LTYPE(x) ((x) & PB_LTYPE_MASK) + +/* Data type used for storing sizes of struct fields + * and array counts. + */ +#if defined(PB_FIELD_32BIT) + typedef uint32_t pb_size_t; + typedef int32_t pb_ssize_t; +#elif defined(PB_FIELD_16BIT) + typedef uint_least16_t pb_size_t; + typedef int_least16_t pb_ssize_t; +#else + typedef uint_least8_t pb_size_t; + typedef int_least8_t pb_ssize_t; +#endif +#define PB_SIZE_MAX ((pb_size_t)-1) + +/* Data type for storing encoded data and other byte streams. + * This typedef exists to support platforms where uint8_t does not exist. + * You can regard it as equivalent on uint8_t on other platforms. + */ +typedef uint_least8_t pb_byte_t; + +/* This structure is used in auto-generated constants + * to specify struct fields. + * You can change field sizes if you need structures + * larger than 256 bytes or field tags larger than 256. + * The compiler should complain if your .proto has such + * structures. Fix that by defining PB_FIELD_16BIT or + * PB_FIELD_32BIT. + */ +PB_PACKED_STRUCT_START +typedef struct pb_field_s pb_field_t; +struct pb_field_s { + pb_size_t tag; + pb_type_t type; + pb_size_t data_offset; /* Offset of field data, relative to previous field. */ + pb_ssize_t size_offset; /* Offset of array size or has-boolean, relative to data */ + pb_size_t data_size; /* Data size in bytes for a single item */ + pb_size_t array_size; /* Maximum number of entries in array */ + + /* Field definitions for submessage + * OR default value for all other non-array, non-callback types + * If null, then field will zeroed. */ + const void *ptr; +} pb_packed; +PB_PACKED_STRUCT_END + +/* Make sure that the standard integer types are of the expected sizes. + * Otherwise fixed32/fixed64 fields can break. + * + * If you get errors here, it probably means that your stdint.h is not + * correct for your platform. + */ +#ifndef PB_WITHOUT_64BIT +PB_STATIC_ASSERT(sizeof(int64_t) == 2 * sizeof(int32_t), INT64_T_WRONG_SIZE) +PB_STATIC_ASSERT(sizeof(uint64_t) == 2 * sizeof(uint32_t), UINT64_T_WRONG_SIZE) +#endif + +/* This structure is used for 'bytes' arrays. + * It has the number of bytes in the beginning, and after that an array. + * Note that actual structs used will have a different length of bytes array. + */ +#define PB_BYTES_ARRAY_T(n) struct { pb_size_t size; pb_byte_t bytes[n]; } +#define PB_BYTES_ARRAY_T_ALLOCSIZE(n) ((size_t)n + offsetof(pb_bytes_array_t, bytes)) + +struct pb_bytes_array_s { + pb_size_t size; + pb_byte_t bytes[1]; +}; +typedef struct pb_bytes_array_s pb_bytes_array_t; + +/* This structure is used for giving the callback function. + * It is stored in the message structure and filled in by the method that + * calls pb_decode. + * + * The decoding callback will be given a limited-length stream + * If the wire type was string, the length is the length of the string. + * If the wire type was a varint/fixed32/fixed64, the length is the length + * of the actual value. + * The function may be called multiple times (especially for repeated types, + * but also otherwise if the message happens to contain the field multiple + * times.) + * + * The encoding callback will receive the actual output stream. + * It should write all the data in one call, including the field tag and + * wire type. It can write multiple fields. + * + * The callback can be null if you want to skip a field. + */ +typedef struct pb_istream_s pb_istream_t; +typedef struct pb_ostream_s pb_ostream_t; +typedef struct pb_callback_s pb_callback_t; +struct pb_callback_s { +#ifdef PB_OLD_CALLBACK_STYLE + /* Deprecated since nanopb-0.2.1 */ + union { + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg); + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg); + } funcs; +#else + /* New function signature, which allows modifying arg contents in callback. */ + union { + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg); + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg); + } funcs; +#endif + + /* Free arg for use by callback */ + void *arg; +}; + +/* Wire types. Library user needs these only in encoder callbacks. */ +typedef enum { + PB_WT_VARINT = 0, + PB_WT_64BIT = 1, + PB_WT_STRING = 2, + PB_WT_32BIT = 5 +} pb_wire_type_t; + +/* Structure for defining the handling of unknown/extension fields. + * Usually the pb_extension_type_t structure is automatically generated, + * while the pb_extension_t structure is created by the user. However, + * if you want to catch all unknown fields, you can also create a custom + * pb_extension_type_t with your own callback. + */ +typedef struct pb_extension_type_s pb_extension_type_t; +typedef struct pb_extension_s pb_extension_t; +struct pb_extension_type_s { + /* Called for each unknown field in the message. + * If you handle the field, read off all of its data and return true. + * If you do not handle the field, do not read anything and return true. + * If you run into an error, return false. + * Set to NULL for default handler. + */ + bool (*decode)(pb_istream_t *stream, pb_extension_t *extension, + uint32_t tag, pb_wire_type_t wire_type); + + /* Called once after all regular fields have been encoded. + * If you have something to write, do so and return true. + * If you do not have anything to write, just return true. + * If you run into an error, return false. + * Set to NULL for default handler. + */ + bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension); + + /* Free field for use by the callback. */ + const void *arg; +}; + +struct pb_extension_s { + /* Type describing the extension field. Usually you'll initialize + * this to a pointer to the automatically generated structure. */ + const pb_extension_type_t *type; + + /* Destination for the decoded data. This must match the datatype + * of the extension field. */ + void *dest; + + /* Pointer to the next extension handler, or NULL. + * If this extension does not match a field, the next handler is + * automatically called. */ + pb_extension_t *next; + + /* The decoder sets this to true if the extension was found. + * Ignored for encoding. */ + bool found; +}; + +/* Memory allocation functions to use. You can define pb_realloc and + * pb_free to custom functions if you want. */ +#ifdef PB_ENABLE_MALLOC +# ifndef pb_realloc +# define pb_realloc(ptr, size) realloc(ptr, size) +# endif +# ifndef pb_free +# define pb_free(ptr) free(ptr) +# endif +#endif + +/* This is used to inform about need to regenerate .pb.h/.pb.c files. */ +#define PB_PROTO_HEADER_VERSION 30 + +/* These macros are used to declare pb_field_t's in the constant array. */ +/* Size of a structure member, in bytes. */ +#define pb_membersize(st, m) (sizeof ((st*)0)->m) +/* Number of entries in an array. */ +#define pb_arraysize(st, m) (pb_membersize(st, m) / pb_membersize(st, m[0])) +/* Delta from start of one member to the start of another member. */ +#define pb_delta(st, m1, m2) ((int)offsetof(st, m1) - (int)offsetof(st, m2)) +/* Marks the end of the field list */ +#define PB_LAST_FIELD {0,(pb_type_t) 0,0,0,0,0,0} + +/* Macros for filling in the data_offset field */ +/* data_offset for first field in a message */ +#define PB_DATAOFFSET_FIRST(st, m1, m2) (offsetof(st, m1)) +/* data_offset for subsequent fields */ +#define PB_DATAOFFSET_OTHER(st, m1, m2) (offsetof(st, m1) - offsetof(st, m2) - pb_membersize(st, m2)) +/* data offset for subsequent fields inside an union (oneof) */ +#define PB_DATAOFFSET_UNION(st, m1, m2) (PB_SIZE_MAX) +/* Choose first/other based on m1 == m2 (deprecated, remains for backwards compatibility) */ +#define PB_DATAOFFSET_CHOOSE(st, m1, m2) (int)(offsetof(st, m1) == offsetof(st, m2) \ + ? PB_DATAOFFSET_FIRST(st, m1, m2) \ + : PB_DATAOFFSET_OTHER(st, m1, m2)) + +/* Required fields are the simplest. They just have delta (padding) from + * previous field end, and the size of the field. Pointer is used for + * submessages and default values. + */ +#define PB_REQUIRED_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Optional fields add the delta to the has_ variable. */ +#define PB_OPTIONAL_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \ + fd, \ + pb_delta(st, has_ ## m, m), \ + pb_membersize(st, m), 0, ptr} + +#define PB_SINGULAR_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Repeated fields have a _count field and also the maximum number of entries. */ +#define PB_REPEATED_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REPEATED | ltype, \ + fd, \ + pb_delta(st, m ## _count, m), \ + pb_membersize(st, m[0]), \ + pb_arraysize(st, m), ptr} + +/* Allocated fields carry the size of the actual data, not the pointer */ +#define PB_REQUIRED_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Optional fields don't need a has_ variable, as information would be redundant */ +#define PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Same as optional fields*/ +#define PB_SINGULAR_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Repeated fields have a _count field and a pointer to array of pointers */ +#define PB_REPEATED_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_REPEATED | ltype, \ + fd, pb_delta(st, m ## _count, m), \ + pb_membersize(st, m[0]), 0, ptr} + +/* Callbacks are much like required fields except with special datatype. */ +#define PB_REQUIRED_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_SINGULAR_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_REPEATED_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REPEATED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Optional extensions don't have the has_ field, as that would be redundant. + * Furthermore, the combination of OPTIONAL without has_ field is used + * for indicating proto3 style fields. Extensions exist in proto2 mode only, + * so they should be encoded according to proto2 rules. To avoid the conflict, + * extensions are marked as REQUIRED instead. + */ +#define PB_OPTEXT_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \ + 0, \ + 0, \ + pb_membersize(st, m), 0, ptr} + +#define PB_OPTEXT_POINTER(tag, st, m, fd, ltype, ptr) \ + PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) + +#define PB_OPTEXT_CALLBACK(tag, st, m, fd, ltype, ptr) \ + PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) + +/* The mapping from protobuf types to LTYPEs is done using these macros. */ +#define PB_LTYPE_MAP_BOOL PB_LTYPE_VARINT +#define PB_LTYPE_MAP_BYTES PB_LTYPE_BYTES +#define PB_LTYPE_MAP_DOUBLE PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_ENUM PB_LTYPE_VARINT +#define PB_LTYPE_MAP_UENUM PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_FIXED32 PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_FIXED64 PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_FLOAT PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_INT32 PB_LTYPE_VARINT +#define PB_LTYPE_MAP_INT64 PB_LTYPE_VARINT +#define PB_LTYPE_MAP_MESSAGE PB_LTYPE_SUBMESSAGE +#define PB_LTYPE_MAP_SFIXED32 PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_SFIXED64 PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_SINT32 PB_LTYPE_SVARINT +#define PB_LTYPE_MAP_SINT64 PB_LTYPE_SVARINT +#define PB_LTYPE_MAP_STRING PB_LTYPE_STRING +#define PB_LTYPE_MAP_UINT32 PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_UINT64 PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_EXTENSION PB_LTYPE_EXTENSION +#define PB_LTYPE_MAP_FIXED_LENGTH_BYTES PB_LTYPE_FIXED_LENGTH_BYTES + +/* This is the actual macro used in field descriptions. + * It takes these arguments: + * - Field tag number + * - Field type: BOOL, BYTES, DOUBLE, ENUM, UENUM, FIXED32, FIXED64, + * FLOAT, INT32, INT64, MESSAGE, SFIXED32, SFIXED64 + * SINT32, SINT64, STRING, UINT32, UINT64 or EXTENSION + * - Field rules: REQUIRED, OPTIONAL or REPEATED + * - Allocation: STATIC, CALLBACK or POINTER + * - Placement: FIRST or OTHER, depending on if this is the first field in structure. + * - Message name + * - Field name + * - Previous field name (or field name again for first field) + * - Pointer to default value or submsg fields. + */ + +#define PB_FIELD(tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ ## rules ## _ ## allocation(tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +/* Field description for repeated static fixed count fields.*/ +#define PB_REPEATED_FIXED_COUNT(tag, type, placement, message, field, prevfield, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REPEATED | PB_LTYPE_MAP_ ## type, \ + PB_DATAOFFSET_ ## placement(message, field, prevfield), \ + 0, \ + pb_membersize(message, field[0]), \ + pb_arraysize(message, field), ptr} + +/* Field description for oneof fields. This requires taking into account the + * union name also, that's why a separate set of macros is needed. + */ +#define PB_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, u.m), \ + pb_membersize(st, u.m), 0, ptr} + +#define PB_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, u.m), \ + pb_membersize(st, u.m[0]), 0, ptr} + +#define PB_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ONEOF_ ## allocation(union_name, tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, union_name.field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +#define PB_ANONYMOUS_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, m), \ + pb_membersize(st, m), 0, ptr} + +#define PB_ANONYMOUS_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, m), \ + pb_membersize(st, m[0]), 0, ptr} + +#define PB_ANONYMOUS_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ANONYMOUS_ONEOF_ ## allocation(union_name, tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +/* These macros are used for giving out error messages. + * They are mostly a debugging aid; the main error information + * is the true/false return value from functions. + * Some code space can be saved by disabling the error + * messages if not used. + * + * PB_SET_ERROR() sets the error message if none has been set yet. + * msg must be a constant string literal. + * PB_GET_ERROR() always returns a pointer to a string. + * PB_RETURN_ERROR() sets the error and returns false from current + * function. + */ +#ifdef PB_NO_ERRMSG +#define PB_SET_ERROR(stream, msg) PB_UNUSED(stream) +#define PB_GET_ERROR(stream) "(errmsg disabled)" +#else +#define PB_SET_ERROR(stream, msg) (stream->errmsg = (stream)->errmsg ? (stream)->errmsg : (msg)) +#define PB_GET_ERROR(stream) ((stream)->errmsg ? (stream)->errmsg : "(none)") +#endif + +#define PB_RETURN_ERROR(stream, msg) return PB_SET_ERROR(stream, msg), false + +#endif diff --git a/My Mind/Pods/nanopb/pb_common.c b/My Mind/Pods/nanopb/pb_common.c new file mode 100644 index 0000000..4fb7186 --- /dev/null +++ b/My Mind/Pods/nanopb/pb_common.c @@ -0,0 +1,97 @@ +/* pb_common.c: Common support functions for pb_encode.c and pb_decode.c. + * + * 2014 Petteri Aimonen + */ + +#include "pb_common.h" + +bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct) +{ + iter->start = fields; + iter->pos = fields; + iter->required_field_index = 0; + iter->dest_struct = dest_struct; + iter->pData = (char*)dest_struct + iter->pos->data_offset; + iter->pSize = (char*)iter->pData + iter->pos->size_offset; + + return (iter->pos->tag != 0); +} + +bool pb_field_iter_next(pb_field_iter_t *iter) +{ + const pb_field_t *prev_field = iter->pos; + + if (prev_field->tag == 0) + { + /* Handle empty message types, where the first field is already the terminator. + * In other cases, the iter->pos never points to the terminator. */ + return false; + } + + iter->pos++; + + if (iter->pos->tag == 0) + { + /* Wrapped back to beginning, reinitialize */ + (void)pb_field_iter_begin(iter, iter->start, iter->dest_struct); + return false; + } + else + { + /* Increment the pointers based on previous field size */ + size_t prev_size = prev_field->data_size; + + if (PB_HTYPE(prev_field->type) == PB_HTYPE_ONEOF && + PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF && + iter->pos->data_offset == PB_SIZE_MAX) + { + /* Don't advance pointers inside unions */ + return true; + } + else if (PB_ATYPE(prev_field->type) == PB_ATYPE_STATIC && + PB_HTYPE(prev_field->type) == PB_HTYPE_REPEATED) + { + /* In static arrays, the data_size tells the size of a single entry and + * array_size is the number of entries */ + prev_size *= prev_field->array_size; + } + else if (PB_ATYPE(prev_field->type) == PB_ATYPE_POINTER) + { + /* Pointer fields always have a constant size in the main structure. + * The data_size only applies to the dynamically allocated area. */ + prev_size = sizeof(void*); + } + + if (PB_HTYPE(prev_field->type) == PB_HTYPE_REQUIRED) + { + /* Count the required fields, in order to check their presence in the + * decoder. */ + iter->required_field_index++; + } + + iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset; + iter->pSize = (char*)iter->pData + iter->pos->size_offset; + return true; + } +} + +bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag) +{ + const pb_field_t *start = iter->pos; + + do { + if (iter->pos->tag == tag && + PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION) + { + /* Found the wanted field */ + return true; + } + + (void)pb_field_iter_next(iter); + } while (iter->pos != start); + + /* Searched all the way back to start, and found nothing. */ + return false; +} + + diff --git a/My Mind/Pods/nanopb/pb_common.h b/My Mind/Pods/nanopb/pb_common.h new file mode 100644 index 0000000..60b3d37 --- /dev/null +++ b/My Mind/Pods/nanopb/pb_common.h @@ -0,0 +1,42 @@ +/* pb_common.h: Common support functions for pb_encode.c and pb_decode.c. + * These functions are rarely needed by applications directly. + */ + +#ifndef PB_COMMON_H_INCLUDED +#define PB_COMMON_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Iterator for pb_field_t list */ +struct pb_field_iter_s { + const pb_field_t *start; /* Start of the pb_field_t array */ + const pb_field_t *pos; /* Current position of the iterator */ + unsigned required_field_index; /* Zero-based index that counts only the required fields */ + void *dest_struct; /* Pointer to start of the structure */ + void *pData; /* Pointer to current field value */ + void *pSize; /* Pointer to count/has field */ +}; +typedef struct pb_field_iter_s pb_field_iter_t; + +/* Initialize the field iterator structure to beginning. + * Returns false if the message type is empty. */ +bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct); + +/* Advance the iterator to the next field. + * Returns false when the iterator wraps back to the first field. */ +bool pb_field_iter_next(pb_field_iter_t *iter); + +/* Advance the iterator until it points at a field with the given tag. + * Returns false if no such field exists. */ +bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif + diff --git a/My Mind/Pods/nanopb/pb_decode.c b/My Mind/Pods/nanopb/pb_decode.c new file mode 100644 index 0000000..4b80e81 --- /dev/null +++ b/My Mind/Pods/nanopb/pb_decode.c @@ -0,0 +1,1508 @@ +/* pb_decode.c -- decode a protobuf using minimal resources + * + * 2011 Petteri Aimonen + */ + +/* Use the GCC warn_unused_result attribute to check that all return values + * are propagated correctly. On other compilers and gcc before 3.4.0 just + * ignore the annotation. + */ +#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) + #define checkreturn +#else + #define checkreturn __attribute__((warn_unused_result)) +#endif + +#include "pb.h" +#include "pb_decode.h" +#include "pb_common.h" + +/************************************** + * Declarations internal to this file * + **************************************/ + +typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn; + +static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); +static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size); +static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension); +static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); +static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn find_extension_field(pb_field_iter_t *iter); +static void pb_field_set_to_default(pb_field_iter_t *iter); +static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct); +static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof); +static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_skip_varint(pb_istream_t *stream); +static bool checkreturn pb_skip_string(pb_istream_t *stream); + +#ifdef PB_ENABLE_MALLOC +static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size); +static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter); +static void pb_release_single_field(const pb_field_iter_t *iter); +#endif + +#ifdef PB_WITHOUT_64BIT +#define pb_int64_t int32_t +#define pb_uint64_t uint32_t +#else +#define pb_int64_t int64_t +#define pb_uint64_t uint64_t +#endif + +/* --- Function pointers to field decoders --- + * Order in the array must match pb_action_t LTYPE numbering. + */ +static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = { + &pb_dec_varint, + &pb_dec_uvarint, + &pb_dec_svarint, + &pb_dec_fixed32, + &pb_dec_fixed64, + + &pb_dec_bytes, + &pb_dec_string, + &pb_dec_submessage, + NULL, /* extensions */ + &pb_dec_fixed_length_bytes +}; + +/******************************* + * pb_istream_t implementation * + *******************************/ + +static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) +{ + size_t i; + const pb_byte_t *source = (const pb_byte_t*)stream->state; + stream->state = (pb_byte_t*)stream->state + count; + + if (buf != NULL) + { + for (i = 0; i < count; i++) + buf[i] = source[i]; + } + + return true; +} + +bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) +{ +#ifndef PB_BUFFER_ONLY + if (buf == NULL && stream->callback != buf_read) + { + /* Skip input bytes */ + pb_byte_t tmp[16]; + while (count > 16) + { + if (!pb_read(stream, tmp, 16)) + return false; + + count -= 16; + } + + return pb_read(stream, tmp, count); + } +#endif + + if (stream->bytes_left < count) + PB_RETURN_ERROR(stream, "end-of-stream"); + +#ifndef PB_BUFFER_ONLY + if (!stream->callback(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#else + if (!buf_read(stream, buf, count)) + return false; +#endif + + stream->bytes_left -= count; + return true; +} + +/* Read a single byte from input stream. buf may not be NULL. + * This is an optimization for the varint decoding. */ +static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf) +{ + if (stream->bytes_left == 0) + PB_RETURN_ERROR(stream, "end-of-stream"); + +#ifndef PB_BUFFER_ONLY + if (!stream->callback(stream, buf, 1)) + PB_RETURN_ERROR(stream, "io error"); +#else + *buf = *(const pb_byte_t*)stream->state; + stream->state = (pb_byte_t*)stream->state + 1; +#endif + + stream->bytes_left--; + + return true; +} + +pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize) +{ + pb_istream_t stream; + /* Cast away the const from buf without a compiler error. We are + * careful to use it only in a const manner in the callbacks. + */ + union { + void *state; + const void *c_state; + } state; +#ifdef PB_BUFFER_ONLY + stream.callback = NULL; +#else + stream.callback = &buf_read; +#endif + state.c_state = buf; + stream.state = state.state; + stream.bytes_left = bufsize; +#ifndef PB_NO_ERRMSG + stream.errmsg = NULL; +#endif + return stream; +} + +/******************** + * Helper functions * + ********************/ + +static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof) +{ + pb_byte_t byte; + uint32_t result; + + if (!pb_readbyte(stream, &byte)) + { + if (stream->bytes_left == 0) + { + if (eof) + { + *eof = true; + } + } + + return false; + } + + if ((byte & 0x80) == 0) + { + /* Quick case, 1 byte value */ + result = byte; + } + else + { + /* Multibyte case */ + uint_fast8_t bitpos = 7; + result = byte & 0x7F; + + do + { + if (!pb_readbyte(stream, &byte)) + return false; + + if (bitpos >= 32) + { + /* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */ + uint8_t sign_extension = (bitpos < 63) ? 0xFF : 0x01; + + if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension)) + { + PB_RETURN_ERROR(stream, "varint overflow"); + } + } + else + { + result |= (uint32_t)(byte & 0x7F) << bitpos; + } + bitpos = (uint_fast8_t)(bitpos + 7); + } while (byte & 0x80); + + if (bitpos == 35 && (byte & 0x70) != 0) + { + /* The last byte was at bitpos=28, so only bottom 4 bits fit. */ + PB_RETURN_ERROR(stream, "varint overflow"); + } + } + + *dest = result; + return true; +} + +bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest) +{ + return pb_decode_varint32_eof(stream, dest, NULL); +} + +#ifndef PB_WITHOUT_64BIT +bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest) +{ + pb_byte_t byte; + uint_fast8_t bitpos = 0; + uint64_t result = 0; + + do + { + if (bitpos >= 64) + PB_RETURN_ERROR(stream, "varint overflow"); + + if (!pb_readbyte(stream, &byte)) + return false; + + result |= (uint64_t)(byte & 0x7F) << bitpos; + bitpos = (uint_fast8_t)(bitpos + 7); + } while (byte & 0x80); + + *dest = result; + return true; +} +#endif + +bool checkreturn pb_skip_varint(pb_istream_t *stream) +{ + pb_byte_t byte; + do + { + if (!pb_read(stream, &byte, 1)) + return false; + } while (byte & 0x80); + return true; +} + +bool checkreturn pb_skip_string(pb_istream_t *stream) +{ + uint32_t length; + if (!pb_decode_varint32(stream, &length)) + return false; + + return pb_read(stream, NULL, length); +} + +bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof) +{ + uint32_t temp; + *eof = false; + *wire_type = (pb_wire_type_t) 0; + *tag = 0; + + if (!pb_decode_varint32_eof(stream, &temp, eof)) + { + return false; + } + + if (temp == 0) + { + *eof = true; /* Special feature: allow 0-terminated messages. */ + return false; + } + + *tag = temp >> 3; + *wire_type = (pb_wire_type_t)(temp & 7); + return true; +} + +bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type) +{ + switch (wire_type) + { + case PB_WT_VARINT: return pb_skip_varint(stream); + case PB_WT_64BIT: return pb_read(stream, NULL, 8); + case PB_WT_STRING: return pb_skip_string(stream); + case PB_WT_32BIT: return pb_read(stream, NULL, 4); + default: PB_RETURN_ERROR(stream, "invalid wire_type"); + } +} + +/* Read a raw value to buffer, for the purpose of passing it to callback as + * a substream. Size is maximum size on call, and actual size on return. + */ +static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size) +{ + size_t max_size = *size; + switch (wire_type) + { + case PB_WT_VARINT: + *size = 0; + do + { + (*size)++; + if (*size > max_size) return false; + if (!pb_read(stream, buf, 1)) return false; + } while (*buf++ & 0x80); + return true; + + case PB_WT_64BIT: + *size = 8; + return pb_read(stream, buf, 8); + + case PB_WT_32BIT: + *size = 4; + return pb_read(stream, buf, 4); + + case PB_WT_STRING: + /* Calling read_raw_value with a PB_WT_STRING is an error. + * Explicitly handle this case and fallthrough to default to avoid + * compiler warnings. + */ + + default: PB_RETURN_ERROR(stream, "invalid wire_type"); + } +} + +/* Decode string length from stream and return a substream with limited length. + * Remember to close the substream using pb_close_string_substream(). + */ +bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream) +{ + uint32_t size; + if (!pb_decode_varint32(stream, &size)) + return false; + + *substream = *stream; + if (substream->bytes_left < size) + PB_RETURN_ERROR(stream, "parent stream too short"); + + substream->bytes_left = size; + stream->bytes_left -= size; + return true; +} + +bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream) +{ + if (substream->bytes_left) { + if (!pb_read(substream, NULL, substream->bytes_left)) + return false; + } + + stream->state = substream->state; + +#ifndef PB_NO_ERRMSG + stream->errmsg = substream->errmsg; +#endif + return true; +} + +/************************* + * Decode a single field * + *************************/ + +static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_type_t type; + pb_decoder_t func; + + type = iter->pos->type; + func = PB_DECODERS[PB_LTYPE(type)]; + + switch (PB_HTYPE(type)) + { + case PB_HTYPE_REQUIRED: + return func(stream, iter->pos, iter->pData); + + case PB_HTYPE_OPTIONAL: + if (iter->pSize != iter->pData) + *(bool*)iter->pSize = true; + return func(stream, iter->pos, iter->pData); + + case PB_HTYPE_REPEATED: + if (wire_type == PB_WT_STRING + && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) + { + /* Packed array */ + bool status = true; + pb_size_t *size = (pb_size_t*)iter->pSize; + + pb_istream_t substream; + if (!pb_make_string_substream(stream, &substream)) + return false; + + while (substream.bytes_left > 0 && *size < iter->pos->array_size) + { + void *pItem = (char*)iter->pData + iter->pos->data_size * (*size); + if (!func(&substream, iter->pos, pItem)) + { + status = false; + break; + } + (*size)++; + } + + if (substream.bytes_left != 0) + PB_RETURN_ERROR(stream, "array overflow"); + if (!pb_close_string_substream(stream, &substream)) + return false; + + return status; + } + else + { + /* Repeated field */ + pb_size_t *size = (pb_size_t*)iter->pSize; + char *pItem = (char*)iter->pData + iter->pos->data_size * (*size); + + if ((*size)++ >= iter->pos->array_size) + PB_RETURN_ERROR(stream, "array overflow"); + + return func(stream, iter->pos, pItem); + } + + case PB_HTYPE_ONEOF: + *(pb_size_t*)iter->pSize = iter->pos->tag; + if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* We memset to zero so that any callbacks are set to NULL. + * Then set any default values. */ + memset(iter->pData, 0, iter->pos->data_size); + pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData); + } + return func(stream, iter->pos, iter->pData); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +#ifdef PB_ENABLE_MALLOC +/* Allocate storage for the field and store the pointer at iter->pData. + * array_size is the number of entries to reserve in an array. + * Zero size is not allowed, use pb_free() for releasing. + */ +static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size) +{ + void *ptr = *(void**)pData; + + if (data_size == 0 || array_size == 0) + PB_RETURN_ERROR(stream, "invalid size"); + + /* Check for multiplication overflows. + * This code avoids the costly division if the sizes are small enough. + * Multiplication is safe as long as only half of bits are set + * in either multiplicand. + */ + { + const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4); + if (data_size >= check_limit || array_size >= check_limit) + { + const size_t size_max = (size_t)-1; + if (size_max / array_size < data_size) + { + PB_RETURN_ERROR(stream, "size too large"); + } + } + } + + /* Allocate new or expand previous allocation */ + /* Note: on failure the old pointer will remain in the structure, + * the message must be freed by caller also on error return. */ + ptr = pb_realloc(ptr, array_size * data_size); + if (ptr == NULL) + PB_RETURN_ERROR(stream, "realloc failed"); + + *(void**)pData = ptr; + return true; +} + +/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */ +static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter) +{ + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING || + PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES) + { + *(void**)pItem = NULL; + } + else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) + { + /* We memset to zero so that any callbacks are set to NULL. + * Then set any default values. */ + memset(pItem, 0, iter->pos->data_size); + pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem); + } +} +#endif + +static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ +#ifndef PB_ENABLE_MALLOC + PB_UNUSED(wire_type); + PB_UNUSED(iter); + PB_RETURN_ERROR(stream, "no malloc support"); +#else + pb_type_t type; + pb_decoder_t func; + + type = iter->pos->type; + func = PB_DECODERS[PB_LTYPE(type)]; + + switch (PB_HTYPE(type)) + { + case PB_HTYPE_REQUIRED: + case PB_HTYPE_OPTIONAL: + case PB_HTYPE_ONEOF: + if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && + *(void**)iter->pData != NULL) + { + /* Duplicate field, have to release the old allocation first. */ + pb_release_single_field(iter); + } + + if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + *(pb_size_t*)iter->pSize = iter->pos->tag; + } + + if (PB_LTYPE(type) == PB_LTYPE_STRING || + PB_LTYPE(type) == PB_LTYPE_BYTES) + { + return func(stream, iter->pos, iter->pData); + } + else + { + if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) + return false; + + initialize_pointer_field(*(void**)iter->pData, iter); + return func(stream, iter->pos, *(void**)iter->pData); + } + + case PB_HTYPE_REPEATED: + if (wire_type == PB_WT_STRING + && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) + { + /* Packed array, multiple items come in at once. */ + bool status = true; + pb_size_t *size = (pb_size_t*)iter->pSize; + size_t allocated_size = *size; + void *pItem; + pb_istream_t substream; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + while (substream.bytes_left) + { + if ((size_t)*size + 1 > allocated_size) + { + /* Allocate more storage. This tries to guess the + * number of remaining entries. Round the division + * upwards. */ + allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; + + if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) + { + status = false; + break; + } + } + + /* Decode the array entry */ + pItem = *(char**)iter->pData + iter->pos->data_size * (*size); + initialize_pointer_field(pItem, iter); + if (!func(&substream, iter->pos, pItem)) + { + status = false; + break; + } + + if (*size == PB_SIZE_MAX) + { +#ifndef PB_NO_ERRMSG + stream->errmsg = "too many array entries"; +#endif + status = false; + break; + } + + (*size)++; + } + if (!pb_close_string_substream(stream, &substream)) + return false; + + return status; + } + else + { + /* Normal repeated field, i.e. only one item at a time. */ + pb_size_t *size = (pb_size_t*)iter->pSize; + void *pItem; + + if (*size == PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "too many array entries"); + + (*size)++; + if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size)) + return false; + + pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1); + initialize_pointer_field(pItem, iter); + return func(stream, iter->pos, pItem); + } + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +#endif +} + +static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_callback_t *pCallback = (pb_callback_t*)iter->pData; + +#ifdef PB_OLD_CALLBACK_STYLE + void *arg = pCallback->arg; +#else + void **arg = &(pCallback->arg); +#endif + + if (pCallback == NULL || pCallback->funcs.decode == NULL) + return pb_skip_field(stream, wire_type); + + if (wire_type == PB_WT_STRING) + { + pb_istream_t substream; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + do + { + if (!pCallback->funcs.decode(&substream, iter->pos, arg)) + PB_RETURN_ERROR(stream, "callback failed"); + } while (substream.bytes_left); + + if (!pb_close_string_substream(stream, &substream)) + return false; + + return true; + } + else + { + /* Copy the single scalar value to stack. + * This is required so that we can limit the stream length, + * which in turn allows to use same callback for packed and + * not-packed fields. */ + pb_istream_t substream; + pb_byte_t buffer[10]; + size_t size = sizeof(buffer); + + if (!read_raw_value(stream, wire_type, buffer, &size)) + return false; + substream = pb_istream_from_buffer(buffer, size); + + return pCallback->funcs.decode(&substream, iter->pos, arg); + } +} + +static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ +#ifdef PB_ENABLE_MALLOC + /* When decoding an oneof field, check if there is old data that must be + * released first. */ + if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF) + { + if (!pb_release_union_field(stream, iter)) + return false; + } +#endif + + switch (PB_ATYPE(iter->pos->type)) + { + case PB_ATYPE_STATIC: + return decode_static_field(stream, wire_type, iter); + + case PB_ATYPE_POINTER: + return decode_pointer_field(stream, wire_type, iter); + + case PB_ATYPE_CALLBACK: + return decode_callback_field(stream, wire_type, iter); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension) +{ + /* Fake a field iterator for the extension field. + * It is not actually safe to advance this iterator, but decode_field + * will not even try to. */ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + (void)pb_field_iter_begin(iter, field, extension->dest); + iter->pData = extension->dest; + iter->pSize = &extension->found; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* For pointer extensions, the pointer is stored directly + * in the extension structure. This avoids having an extra + * indirection. */ + iter->pData = &extension->dest; + } +} + +/* Default handler for extension fields. Expects a pb_field_t structure + * in extension->type->arg. */ +static bool checkreturn default_extension_decoder(pb_istream_t *stream, + pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type) +{ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + pb_field_iter_t iter; + + if (field->tag != tag) + return true; + + iter_from_extension(&iter, extension); + extension->found = true; + return decode_field(stream, wire_type, &iter); +} + +/* Try to decode an unknown field as an extension field. Tries each extension + * decoder in turn, until one of them handles the field or loop ends. */ +static bool checkreturn decode_extension(pb_istream_t *stream, + uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_extension_t *extension = *(pb_extension_t* const *)iter->pData; + size_t pos = stream->bytes_left; + + while (extension != NULL && pos == stream->bytes_left) + { + bool status; + if (extension->type->decode) + status = extension->type->decode(stream, extension, tag, wire_type); + else + status = default_extension_decoder(stream, extension, tag, wire_type); + + if (!status) + return false; + + extension = extension->next; + } + + return true; +} + +/* Step through the iterator until an extension field is found or until all + * entries have been checked. There can be only one extension field per + * message. Returns false if no extension field is found. */ +static bool checkreturn find_extension_field(pb_field_iter_t *iter) +{ + const pb_field_t *start = iter->pos; + + do { + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION) + return true; + (void)pb_field_iter_next(iter); + } while (iter->pos != start); + + return false; +} + +/* Initialize message fields to default values, recursively */ +static void pb_field_set_to_default(pb_field_iter_t *iter) +{ + pb_type_t type; + type = iter->pos->type; + + if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) + { + pb_extension_t *ext = *(pb_extension_t* const *)iter->pData; + while (ext != NULL) + { + pb_field_iter_t ext_iter; + ext->found = false; + iter_from_extension(&ext_iter, ext); + pb_field_set_to_default(&ext_iter); + ext = ext->next; + } + } + else if (PB_ATYPE(type) == PB_ATYPE_STATIC) + { + bool init_data = true; + if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData) + { + /* Set has_field to false. Still initialize the optional field + * itself also. */ + *(bool*)iter->pSize = false; + } + else if (PB_HTYPE(type) == PB_HTYPE_REPEATED || + PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + /* REPEATED: Set array count to 0, no need to initialize contents. + ONEOF: Set which_field to 0. */ + *(pb_size_t*)iter->pSize = 0; + init_data = false; + } + + if (init_data) + { + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) + { + /* Initialize submessage to defaults */ + pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData); + } + else if (iter->pos->ptr != NULL) + { + /* Initialize to default value */ + memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size); + } + else + { + /* Initialize to zeros */ + memset(iter->pData, 0, iter->pos->data_size); + } + } + } + else if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + /* Initialize the pointer to NULL. */ + *(void**)iter->pData = NULL; + + /* Initialize array count to 0. */ + if (PB_HTYPE(type) == PB_HTYPE_REPEATED || + PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + *(pb_size_t*)iter->pSize = 0; + } + } + else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK) + { + /* Don't overwrite callback */ + } +} + +static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct) +{ + pb_field_iter_t iter; + + if (!pb_field_iter_begin(&iter, fields, dest_struct)) + return; /* Empty message type */ + + do + { + pb_field_set_to_default(&iter); + } while (pb_field_iter_next(&iter)); +} + +/********************* + * Decode all fields * + *********************/ + +bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0}; + const uint32_t allbits = ~(uint32_t)0; + uint32_t extension_range_start = 0; + pb_field_iter_t iter; + + /* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed + * count field. This can only handle _one_ repeated fixed count field that + * is unpacked and unordered among other (non repeated fixed count) fields. + */ + const pb_field_t *fixed_count_field = NULL; + pb_size_t fixed_count_size = 0; + + /* Return value ignored, as empty message types will be correctly handled by + * pb_field_iter_find() anyway. */ + (void)pb_field_iter_begin(&iter, fields, dest_struct); + + while (stream->bytes_left) + { + uint32_t tag; + pb_wire_type_t wire_type; + bool eof; + + if (!pb_decode_tag(stream, &wire_type, &tag, &eof)) + { + if (eof) + break; + else + return false; + } + + if (!pb_field_iter_find(&iter, tag)) + { + /* No match found, check if it matches an extension. */ + if (tag >= extension_range_start) + { + if (!find_extension_field(&iter)) + extension_range_start = (uint32_t)-1; + else + extension_range_start = iter.pos->tag; + + if (tag >= extension_range_start) + { + size_t pos = stream->bytes_left; + + if (!decode_extension(stream, tag, wire_type, &iter)) + return false; + + if (pos != stream->bytes_left) + { + /* The field was handled */ + continue; + } + } + } + + /* No match found, skip data */ + if (!pb_skip_field(stream, wire_type)) + return false; + continue; + } + + /* If a repeated fixed count field was found, get size from + * 'fixed_count_field' as there is no counter contained in the struct. + */ + if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED + && iter.pSize == iter.pData) + { + if (fixed_count_field != iter.pos) { + /* If the new fixed count field does not match the previous one, + * check that the previous one is NULL or that it finished + * receiving all the expected data. + */ + if (fixed_count_field != NULL && + fixed_count_size != fixed_count_field->array_size) + { + PB_RETURN_ERROR(stream, "wrong size for fixed count field"); + } + + fixed_count_field = iter.pos; + fixed_count_size = 0; + } + + iter.pSize = &fixed_count_size; + } + + if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED + && iter.required_field_index < PB_MAX_REQUIRED_FIELDS) + { + uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31)); + fields_seen[iter.required_field_index >> 5] |= tmp; + } + + if (!decode_field(stream, wire_type, &iter)) + return false; + } + + /* Check that all elements of the last decoded fixed count field were present. */ + if (fixed_count_field != NULL && + fixed_count_size != fixed_count_field->array_size) + { + PB_RETURN_ERROR(stream, "wrong size for fixed count field"); + } + + /* Check that all required fields were present. */ + { + /* First figure out the number of required fields by + * seeking to the end of the field array. Usually we + * are already close to end after decoding. + */ + unsigned req_field_count; + pb_type_t last_type; + unsigned i; + do { + req_field_count = iter.required_field_index; + last_type = iter.pos->type; + } while (pb_field_iter_next(&iter)); + + /* Fixup if last field was also required. */ + if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0) + req_field_count++; + + if (req_field_count > PB_MAX_REQUIRED_FIELDS) + req_field_count = PB_MAX_REQUIRED_FIELDS; + + if (req_field_count > 0) + { + /* Check the whole words */ + for (i = 0; i < (req_field_count >> 5); i++) + { + if (fields_seen[i] != allbits) + PB_RETURN_ERROR(stream, "missing required field"); + } + + /* Check the remaining bits (if any) */ + if ((req_field_count & 31) != 0) + { + if (fields_seen[req_field_count >> 5] != + (allbits >> (32 - (req_field_count & 31)))) + { + PB_RETURN_ERROR(stream, "missing required field"); + } + } + } + } + + return true; +} + +bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + bool status; + pb_message_set_to_defaults(fields, dest_struct); + status = pb_decode_noinit(stream, fields, dest_struct); + +#ifdef PB_ENABLE_MALLOC + if (!status) + pb_release(fields, dest_struct); +#endif + + return status; +} + +bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + pb_istream_t substream; + bool status; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + status = pb_decode_noinit(&substream, fields, dest_struct); + + if (!pb_close_string_substream(stream, &substream)) + return false; + return status; +} + +bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + pb_istream_t substream; + bool status; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + status = pb_decode(&substream, fields, dest_struct); + + if (!pb_close_string_substream(stream, &substream)) + return false; + return status; +} + +bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + /* This behaviour will be separated in nanopb-0.4.0, see issue #278. */ + return pb_decode(stream, fields, dest_struct); +} + +#ifdef PB_ENABLE_MALLOC +/* Given an oneof field, if there has already been a field inside this oneof, + * release it before overwriting with a different one. */ +static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter) +{ + pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */ + pb_size_t new_tag = iter->pos->tag; /* New which_ value */ + + if (old_tag == 0) + return true; /* Ok, no old data in union */ + + if (old_tag == new_tag) + return true; /* Ok, old data is of same type => merge */ + + /* Release old data. The find can fail if the message struct contains + * invalid data. */ + if (!pb_field_iter_find(iter, old_tag)) + PB_RETURN_ERROR(stream, "invalid union tag"); + + pb_release_single_field(iter); + + /* Restore iterator to where it should be. + * This shouldn't fail unless the pb_field_t structure is corrupted. */ + if (!pb_field_iter_find(iter, new_tag)) + PB_RETURN_ERROR(stream, "iterator error"); + + return true; +} + +static void pb_release_single_field(const pb_field_iter_t *iter) +{ + pb_type_t type; + type = iter->pos->type; + + if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + if (*(pb_size_t*)iter->pSize != iter->pos->tag) + return; /* This is not the current field in the union */ + } + + /* Release anything contained inside an extension or submsg. + * This has to be done even if the submsg itself is statically + * allocated. */ + if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) + { + /* Release fields from all extensions in the linked list */ + pb_extension_t *ext = *(pb_extension_t**)iter->pData; + while (ext != NULL) + { + pb_field_iter_t ext_iter; + iter_from_extension(&ext_iter, ext); + pb_release_single_field(&ext_iter); + ext = ext->next; + } + } + else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* Release fields in submessage or submsg array */ + void *pItem = iter->pData; + pb_size_t count = 1; + + if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + pItem = *(void**)iter->pData; + } + + if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + if (PB_ATYPE(type) == PB_ATYPE_STATIC && iter->pSize == iter->pData) { + /* No _count field so use size of the array */ + count = iter->pos->array_size; + } else { + count = *(pb_size_t*)iter->pSize; + } + + if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size) + { + /* Protect against corrupted _count fields */ + count = iter->pos->array_size; + } + } + + if (pItem) + { + while (count--) + { + pb_release((const pb_field_t*)iter->pos->ptr, pItem); + pItem = (char*)pItem + iter->pos->data_size; + } + } + } + + if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + if (PB_HTYPE(type) == PB_HTYPE_REPEATED && + (PB_LTYPE(type) == PB_LTYPE_STRING || + PB_LTYPE(type) == PB_LTYPE_BYTES)) + { + /* Release entries in repeated string or bytes array */ + void **pItem = *(void***)iter->pData; + pb_size_t count = *(pb_size_t*)iter->pSize; + while (count--) + { + pb_free(*pItem); + *pItem++ = NULL; + } + } + + if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + /* We are going to release the array, so set the size to 0 */ + *(pb_size_t*)iter->pSize = 0; + } + + /* Release main item */ + pb_free(*(void**)iter->pData); + *(void**)iter->pData = NULL; + } +} + +void pb_release(const pb_field_t fields[], void *dest_struct) +{ + pb_field_iter_t iter; + + if (!dest_struct) + return; /* Ignore NULL pointers, similar to free() */ + + if (!pb_field_iter_begin(&iter, fields, dest_struct)) + return; /* Empty message type */ + + do + { + pb_release_single_field(&iter); + } while (pb_field_iter_next(&iter)); +} +#endif + +/* Field decoders */ + +bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest) +{ + pb_uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + if (value & 1) + *dest = (pb_int64_t)(~(value >> 1)); + else + *dest = (pb_int64_t)(value >> 1); + + return true; +} + +bool pb_decode_fixed32(pb_istream_t *stream, void *dest) +{ + pb_byte_t bytes[4]; + + if (!pb_read(stream, bytes, 4)) + return false; + + *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) | + ((uint32_t)bytes[1] << 8) | + ((uint32_t)bytes[2] << 16) | + ((uint32_t)bytes[3] << 24); + return true; +} + +#ifndef PB_WITHOUT_64BIT +bool pb_decode_fixed64(pb_istream_t *stream, void *dest) +{ + pb_byte_t bytes[8]; + + if (!pb_read(stream, bytes, 8)) + return false; + + *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) | + ((uint64_t)bytes[1] << 8) | + ((uint64_t)bytes[2] << 16) | + ((uint64_t)bytes[3] << 24) | + ((uint64_t)bytes[4] << 32) | + ((uint64_t)bytes[5] << 40) | + ((uint64_t)bytes[6] << 48) | + ((uint64_t)bytes[7] << 56); + + return true; +} +#endif + +static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + pb_uint64_t value; + pb_int64_t svalue; + pb_int64_t clamped; + if (!pb_decode_varint(stream, &value)) + return false; + + /* See issue 97: Google's C++ protobuf allows negative varint values to + * be cast as int32_t, instead of the int64_t that should be used when + * encoding. Previous nanopb versions had a bug in encoding. In order to + * not break decoding of such messages, we cast <=32 bit fields to + * int32_t first to get the sign correct. + */ + if (field->data_size == sizeof(pb_int64_t)) + svalue = (pb_int64_t)value; + else + svalue = (int32_t)value; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(pb_int64_t)) + clamped = *(pb_int64_t*)dest = svalue; + else if (field->data_size == sizeof(int32_t)) + clamped = *(int32_t*)dest = (int32_t)svalue; + else if (field->data_size == sizeof(int_least16_t)) + clamped = *(int_least16_t*)dest = (int_least16_t)svalue; + else if (field->data_size == sizeof(int_least8_t)) + clamped = *(int_least8_t*)dest = (int_least8_t)svalue; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != svalue) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + pb_uint64_t value, clamped; + if (!pb_decode_varint(stream, &value)) + return false; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(pb_uint64_t)) + clamped = *(pb_uint64_t*)dest = value; + else if (field->data_size == sizeof(uint32_t)) + clamped = *(uint32_t*)dest = (uint32_t)value; + else if (field->data_size == sizeof(uint_least16_t)) + clamped = *(uint_least16_t*)dest = (uint_least16_t)value; + else if (field->data_size == sizeof(uint_least8_t)) + clamped = *(uint_least8_t*)dest = (uint_least8_t)value; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != value) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + pb_int64_t value, clamped; + if (!pb_decode_svarint(stream, &value)) + return false; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(pb_int64_t)) + clamped = *(pb_int64_t*)dest = value; + else if (field->data_size == sizeof(int32_t)) + clamped = *(int32_t*)dest = (int32_t)value; + else if (field->data_size == sizeof(int_least16_t)) + clamped = *(int_least16_t*)dest = (int_least16_t)value; + else if (field->data_size == sizeof(int_least8_t)) + clamped = *(int_least8_t*)dest = (int_least8_t)value; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != value) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + PB_UNUSED(field); + return pb_decode_fixed32(stream, dest); +} + +static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + PB_UNUSED(field); +#ifndef PB_WITHOUT_64BIT + return pb_decode_fixed64(stream, dest); +#else + PB_UNUSED(dest); + PB_RETURN_ERROR(stream, "no 64bit support"); +#endif +} + +static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + size_t alloc_size; + pb_bytes_array_t *bdest; + + if (!pb_decode_varint32(stream, &size)) + return false; + + if (size > PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "bytes overflow"); + + alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size); + if (size > alloc_size) + PB_RETURN_ERROR(stream, "size too large"); + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { +#ifndef PB_ENABLE_MALLOC + PB_RETURN_ERROR(stream, "no malloc support"); +#else + if (!allocate_field(stream, dest, alloc_size, 1)) + return false; + bdest = *(pb_bytes_array_t**)dest; +#endif + } + else + { + if (alloc_size > field->data_size) + PB_RETURN_ERROR(stream, "bytes overflow"); + bdest = (pb_bytes_array_t*)dest; + } + + bdest->size = (pb_size_t)size; + return pb_read(stream, bdest->bytes, size); +} + +static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + size_t alloc_size; + bool status; + if (!pb_decode_varint32(stream, &size)) + return false; + + /* Space for null terminator */ + alloc_size = size + 1; + + if (alloc_size < size) + PB_RETURN_ERROR(stream, "size too large"); + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { +#ifndef PB_ENABLE_MALLOC + PB_RETURN_ERROR(stream, "no malloc support"); +#else + if (!allocate_field(stream, dest, alloc_size, 1)) + return false; + dest = *(void**)dest; +#endif + } + else + { + if (alloc_size > field->data_size) + PB_RETURN_ERROR(stream, "string overflow"); + } + + status = pb_read(stream, (pb_byte_t*)dest, size); + *((pb_byte_t*)dest + size) = 0; + return status; +} + +static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + bool status; + pb_istream_t substream; + const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + if (field->ptr == NULL) + PB_RETURN_ERROR(stream, "invalid field descriptor"); + + /* New array entries need to be initialized, while required and optional + * submessages have already been initialized in the top-level pb_decode. */ + if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED) + status = pb_decode(&substream, submsg_fields, dest); + else + status = pb_decode_noinit(&substream, submsg_fields, dest); + + if (!pb_close_string_substream(stream, &substream)) + return false; + return status; +} + +static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + + if (!pb_decode_varint32(stream, &size)) + return false; + + if (size > PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "bytes overflow"); + + if (size == 0) + { + /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */ + memset(dest, 0, field->data_size); + return true; + } + + if (size != field->data_size) + PB_RETURN_ERROR(stream, "incorrect fixed length bytes size"); + + return pb_read(stream, (pb_byte_t*)dest, field->data_size); +} diff --git a/My Mind/Pods/nanopb/pb_decode.h b/My Mind/Pods/nanopb/pb_decode.h new file mode 100644 index 0000000..398b24a --- /dev/null +++ b/My Mind/Pods/nanopb/pb_decode.h @@ -0,0 +1,175 @@ +/* pb_decode.h: Functions to decode protocol buffers. Depends on pb_decode.c. + * The main function is pb_decode. You also need an input stream, and the + * field descriptions created by nanopb_generator.py. + */ + +#ifndef PB_DECODE_H_INCLUDED +#define PB_DECODE_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structure for defining custom input streams. You will need to provide + * a callback function to read the bytes from your storage, which can be + * for example a file or a network socket. + * + * The callback must conform to these rules: + * + * 1) Return false on IO errors. This will cause decoding to abort. + * 2) You can use state to store your own data (e.g. buffer pointer), + * and rely on pb_read to verify that no-body reads past bytes_left. + * 3) Your callback may be used with substreams, in which case bytes_left + * is different than from the main stream. Don't use bytes_left to compute + * any pointers. + */ +struct pb_istream_s +{ +#ifdef PB_BUFFER_ONLY + /* Callback pointer is not used in buffer-only configuration. + * Having an int pointer here allows binary compatibility but + * gives an error if someone tries to assign callback function. + */ + int *callback; +#else + bool (*callback)(pb_istream_t *stream, pb_byte_t *buf, size_t count); +#endif + + void *state; /* Free field for use by callback implementation */ + size_t bytes_left; + +#ifndef PB_NO_ERRMSG + const char *errmsg; +#endif +}; + +/*************************** + * Main decoding functions * + ***************************/ + +/* Decode a single protocol buffers message from input stream into a C structure. + * Returns true on success, false on any failure. + * The actual struct pointed to by dest must match the description in fields. + * Callback fields of the destination structure must be initialized by caller. + * All other fields will be initialized by this function. + * + * Example usage: + * MyMessage msg = {}; + * uint8_t buffer[64]; + * pb_istream_t stream; + * + * // ... read some data into buffer ... + * + * stream = pb_istream_from_buffer(buffer, count); + * pb_decode(&stream, MyMessage_fields, &msg); + */ +bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode, except does not initialize the destination structure + * to default values. This is slightly faster if you need no default values + * and just do memset(struct, 0, sizeof(struct)) yourself. + * + * This can also be used for 'merging' two messages, i.e. update only the + * fields that exist in the new message. + * + * Note: If this function returns with an error, it will not release any + * dynamically allocated fields. You will need to call pb_release() yourself. + */ +bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode, except expects the stream to start with the message size + * encoded as varint. Corresponds to parseDelimitedFrom() in Google's + * protobuf API. + */ +bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode_delimited, except that it does not initialize the destination structure. + * See pb_decode_noinit + */ +bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode, except allows the message to be terminated with a null byte. + * NOTE: Until nanopb-0.4.0, pb_decode() also allows null-termination. This behaviour + * is not supported in most other protobuf implementations, so pb_decode_delimited() + * is a better option for compatibility. + */ +bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +#ifdef PB_ENABLE_MALLOC +/* Release any allocated pointer fields. If you use dynamic allocation, you should + * call this for any successfully decoded message when you are done with it. If + * pb_decode() returns with an error, the message is already released. + */ +void pb_release(const pb_field_t fields[], void *dest_struct); +#endif + + +/************************************** + * Functions for manipulating streams * + **************************************/ + +/* Create an input stream for reading from a memory buffer. + * + * Alternatively, you can use a custom stream that reads directly from e.g. + * a file or a network socket. + */ +pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize); + +/* Function to read from a pb_istream_t. You can use this if you need to + * read some custom header data, or to read data in field callbacks. + */ +bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); + + +/************************************************ + * Helper functions for writing field callbacks * + ************************************************/ + +/* Decode the tag for the next field in the stream. Gives the wire type and + * field tag. At end of the message, returns false and sets eof to true. */ +bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof); + +/* Skip the field payload data, given the wire type. */ +bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type); + +/* Decode an integer in the varint format. This works for bool, enum, int32, + * int64, uint32 and uint64 field types. */ +#ifndef PB_WITHOUT_64BIT +bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest); +#else +#define pb_decode_varint pb_decode_varint32 +#endif + +/* Decode an integer in the varint format. This works for bool, enum, int32, + * and uint32 field types. */ +bool pb_decode_varint32(pb_istream_t *stream, uint32_t *dest); + +/* Decode an integer in the zig-zagged svarint format. This works for sint32 + * and sint64. */ +#ifndef PB_WITHOUT_64BIT +bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest); +#else +bool pb_decode_svarint(pb_istream_t *stream, int32_t *dest); +#endif + +/* Decode a fixed32, sfixed32 or float value. You need to pass a pointer to + * a 4-byte wide C variable. */ +bool pb_decode_fixed32(pb_istream_t *stream, void *dest); + +#ifndef PB_WITHOUT_64BIT +/* Decode a fixed64, sfixed64 or double value. You need to pass a pointer to + * a 8-byte wide C variable. */ +bool pb_decode_fixed64(pb_istream_t *stream, void *dest); +#endif + +/* Make a limited-length substream for reading a PB_WT_STRING field. */ +bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream); +bool pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/My Mind/Pods/nanopb/pb_encode.c b/My Mind/Pods/nanopb/pb_encode.c new file mode 100644 index 0000000..089172c --- /dev/null +++ b/My Mind/Pods/nanopb/pb_encode.c @@ -0,0 +1,869 @@ +/* pb_encode.c -- encode a protobuf using minimal resources + * + * 2011 Petteri Aimonen + */ + +#include "pb.h" +#include "pb_encode.h" +#include "pb_common.h" + +/* Use the GCC warn_unused_result attribute to check that all return values + * are propagated correctly. On other compilers and gcc before 3.4.0 just + * ignore the annotation. + */ +#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) + #define checkreturn +#else + #define checkreturn __attribute__((warn_unused_result)) +#endif + +/************************************** + * Declarations internal to this file * + **************************************/ +typedef bool (*pb_encoder_t)(pb_ostream_t *stream, const pb_field_t *field, const void *src) checkreturn; + +static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); +static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, const void *pData, size_t count, pb_encoder_t func); +static bool checkreturn encode_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData); +static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension); +static bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData); +static void *pb_const_cast(const void *p); +static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src); + +#ifdef PB_WITHOUT_64BIT +#define pb_int64_t int32_t +#define pb_uint64_t uint32_t + +static bool checkreturn pb_encode_negative_varint(pb_ostream_t *stream, pb_uint64_t value); +#else +#define pb_int64_t int64_t +#define pb_uint64_t uint64_t +#endif + +/* --- Function pointers to field encoders --- + * Order in the array must match pb_action_t LTYPE numbering. + */ +static const pb_encoder_t PB_ENCODERS[PB_LTYPES_COUNT] = { + &pb_enc_varint, + &pb_enc_uvarint, + &pb_enc_svarint, + &pb_enc_fixed32, + &pb_enc_fixed64, + + &pb_enc_bytes, + &pb_enc_string, + &pb_enc_submessage, + NULL, /* extensions */ + &pb_enc_fixed_length_bytes +}; + +/******************************* + * pb_ostream_t implementation * + *******************************/ + +static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count) +{ + size_t i; + pb_byte_t *dest = (pb_byte_t*)stream->state; + stream->state = dest + count; + + for (i = 0; i < count; i++) + dest[i] = buf[i]; + + return true; +} + +pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize) +{ + pb_ostream_t stream; +#ifdef PB_BUFFER_ONLY + stream.callback = (void*)1; /* Just a marker value */ +#else + stream.callback = &buf_write; +#endif + stream.state = buf; + stream.max_size = bufsize; + stream.bytes_written = 0; +#ifndef PB_NO_ERRMSG + stream.errmsg = NULL; +#endif + return stream; +} + +bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count) +{ + if (stream->callback != NULL) + { + if (stream->bytes_written + count > stream->max_size) + PB_RETURN_ERROR(stream, "stream full"); + +#ifdef PB_BUFFER_ONLY + if (!buf_write(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#else + if (!stream->callback(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#endif + } + + stream->bytes_written += count; + return true; +} + +/************************* + * Encode a single field * + *************************/ + +/* Encode a static array. Handles the size calculations and possible packing. */ +static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, + const void *pData, size_t count, pb_encoder_t func) +{ + size_t i; + const void *p; + size_t size; + + if (count == 0) + return true; + + if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size) + PB_RETURN_ERROR(stream, "array max size exceeded"); + + /* We always pack arrays if the datatype allows it. */ + if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE) + { + if (!pb_encode_tag(stream, PB_WT_STRING, field->tag)) + return false; + + /* Determine the total size of packed array. */ + if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32) + { + size = 4 * count; + } + else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64) + { + size = 8 * count; + } + else + { + pb_ostream_t sizestream = PB_OSTREAM_SIZING; + p = pData; + for (i = 0; i < count; i++) + { + if (!func(&sizestream, field, p)) + return false; + p = (const char*)p + field->data_size; + } + size = sizestream.bytes_written; + } + + if (!pb_encode_varint(stream, (pb_uint64_t)size)) + return false; + + if (stream->callback == NULL) + return pb_write(stream, NULL, size); /* Just sizing.. */ + + /* Write the data */ + p = pData; + for (i = 0; i < count; i++) + { + if (!func(stream, field, p)) + return false; + p = (const char*)p + field->data_size; + } + } + else + { + p = pData; + for (i = 0; i < count; i++) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + /* Normally the data is stored directly in the array entries, but + * for pointer-type string and bytes fields, the array entries are + * actually pointers themselves also. So we have to dereference once + * more to get to the actual data. */ + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER && + (PB_LTYPE(field->type) == PB_LTYPE_STRING || + PB_LTYPE(field->type) == PB_LTYPE_BYTES)) + { + if (!func(stream, field, *(const void* const*)p)) + return false; + } + else + { + if (!func(stream, field, p)) + return false; + } + p = (const char*)p + field->data_size; + } + } + + return true; +} + +/* In proto3, all fields are optional and are only encoded if their value is "non-zero". + * This function implements the check for the zero value. */ +static bool pb_check_proto3_default_value(const pb_field_t *field, const void *pData) +{ + pb_type_t type = field->type; + const void *pSize = (const char*)pData + field->size_offset; + + if (PB_HTYPE(type) == PB_HTYPE_REQUIRED) + { + /* Required proto2 fields inside proto3 submessage, pretty rare case */ + return false; + } + else if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + /* Repeated fields inside proto3 submessage: present if count != 0 */ + return *(const pb_size_t*)pSize == 0; + } + else if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + /* Oneof fields */ + return *(const pb_size_t*)pSize == 0; + } + else if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->size_offset) + { + /* Proto2 optional fields inside proto3 submessage */ + return *(const bool*)pSize == false; + } + + /* Rest is proto3 singular fields */ + + if (PB_ATYPE(type) == PB_ATYPE_STATIC) + { + if (PB_LTYPE(type) == PB_LTYPE_BYTES) + { + const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)pData; + return bytes->size == 0; + } + else if (PB_LTYPE(type) == PB_LTYPE_STRING) + { + return *(const char*)pData == '\0'; + } + else if (PB_LTYPE(type) == PB_LTYPE_FIXED_LENGTH_BYTES) + { + /* Fixed length bytes is only empty if its length is fixed + * as 0. Which would be pretty strange, but we can check + * it anyway. */ + return field->data_size == 0; + } + else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* Check all fields in the submessage to find if any of them + * are non-zero. The comparison cannot be done byte-per-byte + * because the C struct may contain padding bytes that must + * be skipped. + */ + pb_field_iter_t iter; + if (pb_field_iter_begin(&iter, (const pb_field_t*)field->ptr, pb_const_cast(pData))) + { + do + { + if (!pb_check_proto3_default_value(iter.pos, iter.pData)) + { + return false; + } + } while (pb_field_iter_next(&iter)); + } + return true; + } + } + + { + /* Catch-all branch that does byte-per-byte comparison for zero value. + * + * This is for all pointer fields, and for static PB_LTYPE_VARINT, + * UVARINT, SVARINT, FIXED32, FIXED64, EXTENSION fields, and also + * callback fields. These all have integer or pointer value which + * can be compared with 0. + */ + pb_size_t i; + const char *p = (const char*)pData; + for (i = 0; i < field->data_size; i++) + { + if (p[i] != 0) + { + return false; + } + } + + return true; + } +} + +/* Encode a field with static or pointer allocation, i.e. one whose data + * is available to the encoder directly. */ +static bool checkreturn encode_basic_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + pb_encoder_t func; + bool implicit_has; + const void *pSize = &implicit_has; + + func = PB_ENCODERS[PB_LTYPE(field->type)]; + + if (field->size_offset) + { + /* Static optional, repeated or oneof field */ + pSize = (const char*)pData + field->size_offset; + } + else if (PB_HTYPE(field->type) == PB_HTYPE_OPTIONAL) + { + /* Proto3 style field, optional but without explicit has_ field. */ + implicit_has = !pb_check_proto3_default_value(field, pData); + } + else + { + /* Required field, always present */ + implicit_has = true; + } + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* pData is a pointer to the field, which contains pointer to + * the data. If the 2nd pointer is NULL, it is interpreted as if + * the has_field was false. + */ + pData = *(const void* const*)pData; + implicit_has = (pData != NULL); + } + + switch (PB_HTYPE(field->type)) + { + case PB_HTYPE_REQUIRED: + if (!pData) + PB_RETURN_ERROR(stream, "missing required field"); + if (!pb_encode_tag_for_field(stream, field)) + return false; + if (!func(stream, field, pData)) + return false; + break; + + case PB_HTYPE_OPTIONAL: + if (*(const bool*)pSize) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!func(stream, field, pData)) + return false; + } + break; + + case PB_HTYPE_REPEATED: { + pb_size_t count; + if (field->size_offset != 0) { + count = *(const pb_size_t*)pSize; + } else { + count = field->array_size; + } + if (!encode_array(stream, field, pData, count, func)) + return false; + break; + } + + case PB_HTYPE_ONEOF: + if (*(const pb_size_t*)pSize == field->tag) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!func(stream, field, pData)) + return false; + } + break; + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } + + return true; +} + +/* Encode a field with callback semantics. This means that a user function is + * called to provide and encode the actual data. */ +static bool checkreturn encode_callback_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + const pb_callback_t *callback = (const pb_callback_t*)pData; + +#ifdef PB_OLD_CALLBACK_STYLE + const void *arg = callback->arg; +#else + void * const *arg = &(callback->arg); +#endif + + if (callback->funcs.encode != NULL) + { + if (!callback->funcs.encode(stream, field, arg)) + PB_RETURN_ERROR(stream, "callback error"); + } + return true; +} + +/* Encode a single field of any callback or static type. */ +static bool checkreturn encode_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + switch (PB_ATYPE(field->type)) + { + case PB_ATYPE_STATIC: + case PB_ATYPE_POINTER: + return encode_basic_field(stream, field, pData); + + case PB_ATYPE_CALLBACK: + return encode_callback_field(stream, field, pData); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +/* Default handler for extension fields. Expects to have a pb_field_t + * pointer in the extension->type->arg field. */ +static bool checkreturn default_extension_encoder(pb_ostream_t *stream, + const pb_extension_t *extension) +{ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* For pointer extensions, the pointer is stored directly + * in the extension structure. This avoids having an extra + * indirection. */ + return encode_field(stream, field, &extension->dest); + } + else + { + return encode_field(stream, field, extension->dest); + } +} + +/* Walk through all the registered extensions and give them a chance + * to encode themselves. */ +static bool checkreturn encode_extension_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + const pb_extension_t *extension = *(const pb_extension_t* const *)pData; + PB_UNUSED(field); + + while (extension) + { + bool status; + if (extension->type->encode) + status = extension->type->encode(stream, extension); + else + status = default_extension_encoder(stream, extension); + + if (!status) + return false; + + extension = extension->next; + } + + return true; +} + +/********************* + * Encode all fields * + *********************/ + +static void *pb_const_cast(const void *p) +{ + /* Note: this casts away const, in order to use the common field iterator + * logic for both encoding and decoding. */ + union { + void *p1; + const void *p2; + } t; + t.p2 = p; + return t.p1; +} + +bool checkreturn pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + pb_field_iter_t iter; + if (!pb_field_iter_begin(&iter, fields, pb_const_cast(src_struct))) + return true; /* Empty message type */ + + do { + if (PB_LTYPE(iter.pos->type) == PB_LTYPE_EXTENSION) + { + /* Special case for the extension field placeholder */ + if (!encode_extension_field(stream, iter.pos, iter.pData)) + return false; + } + else + { + /* Regular field */ + if (!encode_field(stream, iter.pos, iter.pData)) + return false; + } + } while (pb_field_iter_next(&iter)); + + return true; +} + +bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + return pb_encode_submessage(stream, fields, src_struct); +} + +bool pb_encode_nullterminated(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + const pb_byte_t zero = 0; + + if (!pb_encode(stream, fields, src_struct)) + return false; + + return pb_write(stream, &zero, 1); +} + +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct) +{ + pb_ostream_t stream = PB_OSTREAM_SIZING; + + if (!pb_encode(&stream, fields, src_struct)) + return false; + + *size = stream.bytes_written; + return true; +} + +/******************** + * Helper functions * + ********************/ + +#ifdef PB_WITHOUT_64BIT +bool checkreturn pb_encode_negative_varint(pb_ostream_t *stream, pb_uint64_t value) +{ + pb_byte_t buffer[10]; + size_t i = 0; + size_t compensation = 32;/* we need to compensate 32 bits all set to 1 */ + + while (value) + { + buffer[i] = (pb_byte_t)((value & 0x7F) | 0x80); + value >>= 7; + if (compensation) + { + /* re-set all the compensation bits we can or need */ + size_t bits = compensation > 7 ? 7 : compensation; + value ^= (pb_uint64_t)((0xFFu >> (8 - bits)) << 25); /* set the number of bits needed on the lowest of the most significant 7 bits */ + compensation -= bits; + } + i++; + } + buffer[i - 1] &= 0x7F; /* Unset top bit on last byte */ + + return pb_write(stream, buffer, i); +} +#endif + +bool checkreturn pb_encode_varint(pb_ostream_t *stream, pb_uint64_t value) +{ + pb_byte_t buffer[10]; + size_t i = 0; + + if (value <= 0x7F) + { + pb_byte_t v = (pb_byte_t)value; + return pb_write(stream, &v, 1); + } + + while (value) + { + buffer[i] = (pb_byte_t)((value & 0x7F) | 0x80); + value >>= 7; + i++; + } + buffer[i-1] &= 0x7F; /* Unset top bit on last byte */ + + return pb_write(stream, buffer, i); +} + +bool checkreturn pb_encode_svarint(pb_ostream_t *stream, pb_int64_t value) +{ + pb_uint64_t zigzagged; + if (value < 0) + zigzagged = ~((pb_uint64_t)value << 1); + else + zigzagged = (pb_uint64_t)value << 1; + + return pb_encode_varint(stream, zigzagged); +} + +bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value) +{ + uint32_t val = *(const uint32_t*)value; + pb_byte_t bytes[4]; + bytes[0] = (pb_byte_t)(val & 0xFF); + bytes[1] = (pb_byte_t)((val >> 8) & 0xFF); + bytes[2] = (pb_byte_t)((val >> 16) & 0xFF); + bytes[3] = (pb_byte_t)((val >> 24) & 0xFF); + return pb_write(stream, bytes, 4); +} + +#ifndef PB_WITHOUT_64BIT +bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value) +{ + uint64_t val = *(const uint64_t*)value; + pb_byte_t bytes[8]; + bytes[0] = (pb_byte_t)(val & 0xFF); + bytes[1] = (pb_byte_t)((val >> 8) & 0xFF); + bytes[2] = (pb_byte_t)((val >> 16) & 0xFF); + bytes[3] = (pb_byte_t)((val >> 24) & 0xFF); + bytes[4] = (pb_byte_t)((val >> 32) & 0xFF); + bytes[5] = (pb_byte_t)((val >> 40) & 0xFF); + bytes[6] = (pb_byte_t)((val >> 48) & 0xFF); + bytes[7] = (pb_byte_t)((val >> 56) & 0xFF); + return pb_write(stream, bytes, 8); +} +#endif + +bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number) +{ + pb_uint64_t tag = ((pb_uint64_t)field_number << 3) | wiretype; + return pb_encode_varint(stream, tag); +} + +bool checkreturn pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field) +{ + pb_wire_type_t wiretype; + switch (PB_LTYPE(field->type)) + { + case PB_LTYPE_VARINT: + case PB_LTYPE_UVARINT: + case PB_LTYPE_SVARINT: + wiretype = PB_WT_VARINT; + break; + + case PB_LTYPE_FIXED32: + wiretype = PB_WT_32BIT; + break; + + case PB_LTYPE_FIXED64: + wiretype = PB_WT_64BIT; + break; + + case PB_LTYPE_BYTES: + case PB_LTYPE_STRING: + case PB_LTYPE_SUBMESSAGE: + case PB_LTYPE_FIXED_LENGTH_BYTES: + wiretype = PB_WT_STRING; + break; + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } + + return pb_encode_tag(stream, wiretype, field->tag); +} + +bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size) +{ + if (!pb_encode_varint(stream, (pb_uint64_t)size)) + return false; + + return pb_write(stream, buffer, size); +} + +bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + /* First calculate the message size using a non-writing substream. */ + pb_ostream_t substream = PB_OSTREAM_SIZING; + size_t size; + bool status; + + if (!pb_encode(&substream, fields, src_struct)) + { +#ifndef PB_NO_ERRMSG + stream->errmsg = substream.errmsg; +#endif + return false; + } + + size = substream.bytes_written; + + if (!pb_encode_varint(stream, (pb_uint64_t)size)) + return false; + + if (stream->callback == NULL) + return pb_write(stream, NULL, size); /* Just sizing */ + + if (stream->bytes_written + size > stream->max_size) + PB_RETURN_ERROR(stream, "stream full"); + + /* Use a substream to verify that a callback doesn't write more than + * what it did the first time. */ + substream.callback = stream->callback; + substream.state = stream->state; + substream.max_size = size; + substream.bytes_written = 0; +#ifndef PB_NO_ERRMSG + substream.errmsg = NULL; +#endif + + status = pb_encode(&substream, fields, src_struct); + + stream->bytes_written += substream.bytes_written; + stream->state = substream.state; +#ifndef PB_NO_ERRMSG + stream->errmsg = substream.errmsg; +#endif + + if (substream.bytes_written != size) + PB_RETURN_ERROR(stream, "submsg size changed"); + + return status; +} + +/* Field encoders */ + +static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + pb_int64_t value = 0; + + if (field->data_size == sizeof(int_least8_t)) + value = *(const int_least8_t*)src; + else if (field->data_size == sizeof(int_least16_t)) + value = *(const int_least16_t*)src; + else if (field->data_size == sizeof(int32_t)) + value = *(const int32_t*)src; + else if (field->data_size == sizeof(pb_int64_t)) + value = *(const pb_int64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + +#ifdef PB_WITHOUT_64BIT + if (value < 0) + return pb_encode_negative_varint(stream, (pb_uint64_t)value); + else +#endif + return pb_encode_varint(stream, (pb_uint64_t)value); +} + +static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + pb_uint64_t value = 0; + + if (field->data_size == sizeof(uint_least8_t)) + value = *(const uint_least8_t*)src; + else if (field->data_size == sizeof(uint_least16_t)) + value = *(const uint_least16_t*)src; + else if (field->data_size == sizeof(uint32_t)) + value = *(const uint32_t*)src; + else if (field->data_size == sizeof(pb_uint64_t)) + value = *(const pb_uint64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + return pb_encode_varint(stream, value); +} + +static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + pb_int64_t value = 0; + + if (field->data_size == sizeof(int_least8_t)) + value = *(const int_least8_t*)src; + else if (field->data_size == sizeof(int_least16_t)) + value = *(const int_least16_t*)src; + else if (field->data_size == sizeof(int32_t)) + value = *(const int32_t*)src; + else if (field->data_size == sizeof(pb_int64_t)) + value = *(const pb_int64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + return pb_encode_svarint(stream, value); +} + +static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + PB_UNUSED(field); +#ifndef PB_WITHOUT_64BIT + return pb_encode_fixed64(stream, src); +#else + PB_UNUSED(src); + PB_RETURN_ERROR(stream, "no 64bit support"); +#endif +} + +static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + PB_UNUSED(field); + return pb_encode_fixed32(stream, src); +} + +static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + const pb_bytes_array_t *bytes = NULL; + + bytes = (const pb_bytes_array_t*)src; + + if (src == NULL) + { + /* Treat null pointer as an empty bytes field */ + return pb_encode_string(stream, NULL, 0); + } + + if (PB_ATYPE(field->type) == PB_ATYPE_STATIC && + PB_BYTES_ARRAY_T_ALLOCSIZE(bytes->size) > field->data_size) + { + PB_RETURN_ERROR(stream, "bytes size exceeded"); + } + + return pb_encode_string(stream, bytes->bytes, bytes->size); +} + +static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + size_t size = 0; + size_t max_size = field->data_size; + const char *p = (const char*)src; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + max_size = (size_t)-1; + + if (src == NULL) + { + size = 0; /* Treat null pointer as an empty string */ + } + else + { + /* strnlen() is not always available, so just use a loop */ + while (size < max_size && *p != '\0') + { + size++; + p++; + } + } + + return pb_encode_string(stream, (const pb_byte_t*)src, size); +} + +static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + if (field->ptr == NULL) + PB_RETURN_ERROR(stream, "invalid field descriptor"); + + return pb_encode_submessage(stream, (const pb_field_t*)field->ptr, src); +} + +static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + return pb_encode_string(stream, (const pb_byte_t*)src, field->data_size); +} + diff --git a/My Mind/Pods/nanopb/pb_encode.h b/My Mind/Pods/nanopb/pb_encode.h new file mode 100644 index 0000000..8bf78dd --- /dev/null +++ b/My Mind/Pods/nanopb/pb_encode.h @@ -0,0 +1,170 @@ +/* pb_encode.h: Functions to encode protocol buffers. Depends on pb_encode.c. + * The main function is pb_encode. You also need an output stream, and the + * field descriptions created by nanopb_generator.py. + */ + +#ifndef PB_ENCODE_H_INCLUDED +#define PB_ENCODE_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structure for defining custom output streams. You will need to provide + * a callback function to write the bytes to your storage, which can be + * for example a file or a network socket. + * + * The callback must conform to these rules: + * + * 1) Return false on IO errors. This will cause encoding to abort. + * 2) You can use state to store your own data (e.g. buffer pointer). + * 3) pb_write will update bytes_written after your callback runs. + * 4) Substreams will modify max_size and bytes_written. Don't use them + * to calculate any pointers. + */ +struct pb_ostream_s +{ +#ifdef PB_BUFFER_ONLY + /* Callback pointer is not used in buffer-only configuration. + * Having an int pointer here allows binary compatibility but + * gives an error if someone tries to assign callback function. + * Also, NULL pointer marks a 'sizing stream' that does not + * write anything. + */ + int *callback; +#else + bool (*callback)(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); +#endif + void *state; /* Free field for use by callback implementation. */ + size_t max_size; /* Limit number of output bytes written (or use SIZE_MAX). */ + size_t bytes_written; /* Number of bytes written so far. */ + +#ifndef PB_NO_ERRMSG + const char *errmsg; +#endif +}; + +/*************************** + * Main encoding functions * + ***************************/ + +/* Encode a single protocol buffers message from C structure into a stream. + * Returns true on success, false on any failure. + * The actual struct pointed to by src_struct must match the description in fields. + * All required fields in the struct are assumed to have been filled in. + * + * Example usage: + * MyMessage msg = {}; + * uint8_t buffer[64]; + * pb_ostream_t stream; + * + * msg.field1 = 42; + * stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + * pb_encode(&stream, MyMessage_fields, &msg); + */ +bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +/* Same as pb_encode, but prepends the length of the message as a varint. + * Corresponds to writeDelimitedTo() in Google's protobuf API. + */ +bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +/* Same as pb_encode, but appends a null byte to the message for termination. + * NOTE: This behaviour is not supported in most other protobuf implementations, so pb_encode_delimited() + * is a better option for compatibility. + */ +bool pb_encode_nullterminated(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +/* Encode the message to get the size of the encoded data, but do not store + * the data. */ +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct); + +/************************************** + * Functions for manipulating streams * + **************************************/ + +/* Create an output stream for writing into a memory buffer. + * The number of bytes written can be found in stream.bytes_written after + * encoding the message. + * + * Alternatively, you can use a custom stream that writes directly to e.g. + * a file or a network socket. + */ +pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize); + +/* Pseudo-stream for measuring the size of a message without actually storing + * the encoded data. + * + * Example usage: + * MyMessage msg = {}; + * pb_ostream_t stream = PB_OSTREAM_SIZING; + * pb_encode(&stream, MyMessage_fields, &msg); + * printf("Message size is %d\n", stream.bytes_written); + */ +#ifndef PB_NO_ERRMSG +#define PB_OSTREAM_SIZING {0,0,0,0,0} +#else +#define PB_OSTREAM_SIZING {0,0,0,0} +#endif + +/* Function to write into a pb_ostream_t stream. You can use this if you need + * to append or prepend some custom headers to the message. + */ +bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); + + +/************************************************ + * Helper functions for writing field callbacks * + ************************************************/ + +/* Encode field header based on type and field number defined in the field + * structure. Call this from the callback before writing out field contents. */ +bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field); + +/* Encode field header by manually specifing wire type. You need to use this + * if you want to write out packed arrays from a callback field. */ +bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number); + +/* Encode an integer in the varint format. + * This works for bool, enum, int32, int64, uint32 and uint64 field types. */ +#ifndef PB_WITHOUT_64BIT +bool pb_encode_varint(pb_ostream_t *stream, uint64_t value); +#else +bool pb_encode_varint(pb_ostream_t *stream, uint32_t value); +#endif + +/* Encode an integer in the zig-zagged svarint format. + * This works for sint32 and sint64. */ +#ifndef PB_WITHOUT_64BIT +bool pb_encode_svarint(pb_ostream_t *stream, int64_t value); +#else +bool pb_encode_svarint(pb_ostream_t *stream, int32_t value); +#endif + +/* Encode a string or bytes type field. For strings, pass strlen(s) as size. */ +bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size); + +/* Encode a fixed32, sfixed32 or float value. + * You need to pass a pointer to a 4-byte wide C variable. */ +bool pb_encode_fixed32(pb_ostream_t *stream, const void *value); + +#ifndef PB_WITHOUT_64BIT +/* Encode a fixed64, sfixed64 or double value. + * You need to pass a pointer to a 8-byte wide C variable. */ +bool pb_encode_fixed64(pb_ostream_t *stream, const void *value); +#endif + +/* Encode a submessage field. + * You need to pass the pb_field_t array and pointer to struct, just like + * with pb_encode(). This internally encodes the submessage twice, first to + * calculate message size and then to actually write it out. + */ +bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/My Mind/cartfile b/My Mind/cartfile new file mode 100644 index 0000000..409f0b4 --- /dev/null +++ b/My Mind/cartfile @@ -0,0 +1 @@ +github "ortuman/SwiftForms" diff --git a/My Mind/prodfile b/My Mind/prodfile new file mode 100644 index 0000000..e2eac41 --- /dev/null +++ b/My Mind/prodfile @@ -0,0 +1,10 @@ +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '12.1' +use_frameworks! + +pod 'SwiftForms' +pod 'Firebase/Core' +pod 'Firebase/Auth' +pod 'Firebase/Messaging' +pod 'Firebase/Database' +pod 'Firebase/Storage'