From 6f6bc80500664503cdcea5da58f68ce3aff3249d Mon Sep 17 00:00:00 2001 From: Sean-Wang Date: Thu, 18 Apr 2013 10:34:50 +0800 Subject: [PATCH 1/2] Add some demo dependent libraries. --- .../project.pbxproj | 406 +++++ PSCollectionViewDemo/AppDelegate.h | 19 + PSCollectionViewDemo/AppDelegate.m | 52 + .../NSAlert+MKNetworkKitAdditions.h | 32 + .../NSAlert+MKNetworkKitAdditions.m | 39 + .../Categories/NSData+Base64.h | 42 + .../Categories/NSData+Base64.m | 312 ++++ .../Categories/NSDate+RFC1123.h | 25 + .../Categories/NSDate+RFC1123.m | 79 + .../Categories/NSDictionary+RequestEncoding.h | 31 + .../Categories/NSDictionary+RequestEncoding.m | 74 + .../NSString+MKNetworkKitAdditions.h | 32 + .../NSString+MKNetworkKitAdditions.m | 81 + .../UIAlertView+MKNetworkKitAdditions.h | 31 + .../UIAlertView+MKNetworkKitAdditions.m | 41 + PSCollectionViewDemo/Default-568h@2x.png | Bin 0 -> 18594 bytes PSCollectionViewDemo/Default.png | Bin 0 -> 6540 bytes PSCollectionViewDemo/Default@2x.png | Bin 0 -> 16107 bytes PSCollectionViewDemo/MKNetworkEngine.h | 335 +++++ PSCollectionViewDemo/MKNetworkEngine.m | 689 +++++++++ PSCollectionViewDemo/MKNetworkKit.h | 92 ++ PSCollectionViewDemo/MKNetworkOperation.h | 575 +++++++ PSCollectionViewDemo/MKNetworkOperation.m | 1332 +++++++++++++++++ PSCollectionViewDemo/PSCollectionView.h | 82 + PSCollectionViewDemo/PSCollectionView.m | 434 ++++++ PSCollectionViewDemo/PSCollectionViewCell.h | 38 + PSCollectionViewDemo/PSCollectionViewCell.m | 53 + .../PSCollectionViewDemo-Info.plist | 38 + .../PSCollectionViewDemo-Prefix.pch | 14 + .../Reachability/Reachability.h | 115 ++ .../Reachability/Reachability.m | 492 ++++++ PSCollectionViewDemo/ViewController.h | 13 + PSCollectionViewDemo/ViewController.m | 29 + .../en.lproj/InfoPlist.strings | 2 + .../en.lproj/ViewController.xib | 138 ++ PSCollectionViewDemo/main.m | 18 + 36 files changed, 5785 insertions(+) create mode 100644 PSCollectionViewDemo.xcodeproj/project.pbxproj create mode 100644 PSCollectionViewDemo/AppDelegate.h create mode 100644 PSCollectionViewDemo/AppDelegate.m create mode 100644 PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.h create mode 100644 PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.m create mode 100644 PSCollectionViewDemo/Categories/NSData+Base64.h create mode 100644 PSCollectionViewDemo/Categories/NSData+Base64.m create mode 100644 PSCollectionViewDemo/Categories/NSDate+RFC1123.h create mode 100644 PSCollectionViewDemo/Categories/NSDate+RFC1123.m create mode 100644 PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.h create mode 100644 PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.m create mode 100644 PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.h create mode 100644 PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.m create mode 100644 PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.h create mode 100644 PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.m create mode 100644 PSCollectionViewDemo/Default-568h@2x.png create mode 100644 PSCollectionViewDemo/Default.png create mode 100644 PSCollectionViewDemo/Default@2x.png create mode 100644 PSCollectionViewDemo/MKNetworkEngine.h create mode 100644 PSCollectionViewDemo/MKNetworkEngine.m create mode 100644 PSCollectionViewDemo/MKNetworkKit.h create mode 100644 PSCollectionViewDemo/MKNetworkOperation.h create mode 100644 PSCollectionViewDemo/MKNetworkOperation.m create mode 100644 PSCollectionViewDemo/PSCollectionView.h create mode 100644 PSCollectionViewDemo/PSCollectionView.m create mode 100644 PSCollectionViewDemo/PSCollectionViewCell.h create mode 100644 PSCollectionViewDemo/PSCollectionViewCell.m create mode 100644 PSCollectionViewDemo/PSCollectionViewDemo-Info.plist create mode 100644 PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch create mode 100644 PSCollectionViewDemo/Reachability/Reachability.h create mode 100644 PSCollectionViewDemo/Reachability/Reachability.m create mode 100644 PSCollectionViewDemo/ViewController.h create mode 100644 PSCollectionViewDemo/ViewController.m create mode 100644 PSCollectionViewDemo/en.lproj/InfoPlist.strings create mode 100644 PSCollectionViewDemo/en.lproj/ViewController.xib create mode 100644 PSCollectionViewDemo/main.m diff --git a/PSCollectionViewDemo.xcodeproj/project.pbxproj b/PSCollectionViewDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..a3204fb --- /dev/null +++ b/PSCollectionViewDemo.xcodeproj/project.pbxproj @@ -0,0 +1,406 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 8A35E142171F8F0C00F4D64C /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E141171F8F0C00F4D64C /* UIKit.framework */; }; + 8A35E144171F8F0C00F4D64C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E143171F8F0C00F4D64C /* Foundation.framework */; }; + 8A35E146171F8F0C00F4D64C /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E145171F8F0C00F4D64C /* CoreGraphics.framework */; }; + 8A35E14C171F8F0C00F4D64C /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E14A171F8F0C00F4D64C /* InfoPlist.strings */; }; + 8A35E14E171F8F0C00F4D64C /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E14D171F8F0C00F4D64C /* main.m */; }; + 8A35E152171F8F0C00F4D64C /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E151171F8F0C00F4D64C /* AppDelegate.m */; }; + 8A35E154171F8F0C00F4D64C /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E153171F8F0C00F4D64C /* Default.png */; }; + 8A35E156171F8F0C00F4D64C /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E155171F8F0C00F4D64C /* Default@2x.png */; }; + 8A35E158171F8F0C00F4D64C /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E157171F8F0C00F4D64C /* Default-568h@2x.png */; }; + 8A35E15B171F8F0C00F4D64C /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E15A171F8F0C00F4D64C /* ViewController.m */; }; + 8A35E15E171F8F0D00F4D64C /* ViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E15C171F8F0D00F4D64C /* ViewController.xib */; }; + 8A35E169171F901200F4D64C /* PSCollectionView.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E166171F901200F4D64C /* PSCollectionView.m */; }; + 8A35E16A171F901200F4D64C /* PSCollectionViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E168171F901200F4D64C /* PSCollectionViewCell.m */; }; + 8A35E181171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E16E171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.m */; }; + 8A35E182171F911400F4D64C /* NSData+Base64.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E170171F911400F4D64C /* NSData+Base64.m */; }; + 8A35E183171F911400F4D64C /* NSDate+RFC1123.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E172171F911400F4D64C /* NSDate+RFC1123.m */; }; + 8A35E184171F911400F4D64C /* NSDictionary+RequestEncoding.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E174171F911400F4D64C /* NSDictionary+RequestEncoding.m */; }; + 8A35E185171F911400F4D64C /* NSString+MKNetworkKitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E176171F911400F4D64C /* NSString+MKNetworkKitAdditions.m */; }; + 8A35E186171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E178171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.m */; }; + 8A35E187171F911400F4D64C /* MKNetworkEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E17A171F911400F4D64C /* MKNetworkEngine.m */; }; + 8A35E188171F911400F4D64C /* MKNetworkOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E17D171F911400F4D64C /* MKNetworkOperation.m */; }; + 8A35E189171F911400F4D64C /* Reachability.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E180171F911400F4D64C /* Reachability.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 8A35E13E171F8F0C00F4D64C /* PSCollectionViewDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PSCollectionViewDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 8A35E141171F8F0C00F4D64C /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 8A35E143171F8F0C00F4D64C /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 8A35E145171F8F0C00F4D64C /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 8A35E149171F8F0C00F4D64C /* PSCollectionViewDemo-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PSCollectionViewDemo-Info.plist"; sourceTree = ""; }; + 8A35E14B171F8F0C00F4D64C /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + 8A35E14D171F8F0C00F4D64C /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 8A35E14F171F8F0C00F4D64C /* PSCollectionViewDemo-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PSCollectionViewDemo-Prefix.pch"; sourceTree = ""; }; + 8A35E150171F8F0C00F4D64C /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + 8A35E151171F8F0C00F4D64C /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + 8A35E153171F8F0C00F4D64C /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = ""; }; + 8A35E155171F8F0C00F4D64C /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = ""; }; + 8A35E157171F8F0C00F4D64C /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; + 8A35E159171F8F0C00F4D64C /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; + 8A35E15A171F8F0C00F4D64C /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; + 8A35E15D171F8F0D00F4D64C /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/ViewController.xib; sourceTree = ""; }; + 8A35E165171F901200F4D64C /* PSCollectionView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PSCollectionView.h; sourceTree = ""; }; + 8A35E166171F901200F4D64C /* PSCollectionView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PSCollectionView.m; sourceTree = ""; }; + 8A35E167171F901200F4D64C /* PSCollectionViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PSCollectionViewCell.h; sourceTree = ""; }; + 8A35E168171F901200F4D64C /* PSCollectionViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PSCollectionViewCell.m; sourceTree = ""; }; + 8A35E16D171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSAlert+MKNetworkKitAdditions.h"; sourceTree = ""; }; + 8A35E16E171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSAlert+MKNetworkKitAdditions.m"; sourceTree = ""; }; + 8A35E16F171F911400F4D64C /* NSData+Base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+Base64.h"; sourceTree = ""; }; + 8A35E170171F911400F4D64C /* NSData+Base64.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+Base64.m"; sourceTree = ""; }; + 8A35E171171F911400F4D64C /* NSDate+RFC1123.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSDate+RFC1123.h"; sourceTree = ""; }; + 8A35E172171F911400F4D64C /* NSDate+RFC1123.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSDate+RFC1123.m"; sourceTree = ""; }; + 8A35E173171F911400F4D64C /* NSDictionary+RequestEncoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSDictionary+RequestEncoding.h"; sourceTree = ""; }; + 8A35E174171F911400F4D64C /* NSDictionary+RequestEncoding.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSDictionary+RequestEncoding.m"; sourceTree = ""; }; + 8A35E175171F911400F4D64C /* NSString+MKNetworkKitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+MKNetworkKitAdditions.h"; sourceTree = ""; }; + 8A35E176171F911400F4D64C /* NSString+MKNetworkKitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+MKNetworkKitAdditions.m"; sourceTree = ""; }; + 8A35E177171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIAlertView+MKNetworkKitAdditions.h"; sourceTree = ""; }; + 8A35E178171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIAlertView+MKNetworkKitAdditions.m"; sourceTree = ""; }; + 8A35E179171F911400F4D64C /* MKNetworkEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MKNetworkEngine.h; sourceTree = ""; }; + 8A35E17A171F911400F4D64C /* MKNetworkEngine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MKNetworkEngine.m; sourceTree = ""; }; + 8A35E17B171F911400F4D64C /* MKNetworkKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MKNetworkKit.h; sourceTree = ""; }; + 8A35E17C171F911400F4D64C /* MKNetworkOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MKNetworkOperation.h; sourceTree = ""; }; + 8A35E17D171F911400F4D64C /* MKNetworkOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MKNetworkOperation.m; sourceTree = ""; }; + 8A35E17F171F911400F4D64C /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Reachability.h; sourceTree = ""; }; + 8A35E180171F911400F4D64C /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Reachability.m; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 8A35E13B171F8F0C00F4D64C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8A35E142171F8F0C00F4D64C /* UIKit.framework in Frameworks */, + 8A35E144171F8F0C00F4D64C /* Foundation.framework in Frameworks */, + 8A35E146171F8F0C00F4D64C /* CoreGraphics.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 8A35E135171F8F0C00F4D64C = { + isa = PBXGroup; + children = ( + 8A35E147171F8F0C00F4D64C /* PSCollectionViewDemo */, + 8A35E140171F8F0C00F4D64C /* Frameworks */, + 8A35E13F171F8F0C00F4D64C /* Products */, + ); + sourceTree = ""; + }; + 8A35E13F171F8F0C00F4D64C /* Products */ = { + isa = PBXGroup; + children = ( + 8A35E13E171F8F0C00F4D64C /* PSCollectionViewDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + 8A35E140171F8F0C00F4D64C /* Frameworks */ = { + isa = PBXGroup; + children = ( + 8A35E141171F8F0C00F4D64C /* UIKit.framework */, + 8A35E143171F8F0C00F4D64C /* Foundation.framework */, + 8A35E145171F8F0C00F4D64C /* CoreGraphics.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 8A35E147171F8F0C00F4D64C /* PSCollectionViewDemo */ = { + isa = PBXGroup; + children = ( + 8A35E16B171F902000F4D64C /* MKNetworkKit */, + 8A35E164171F8FB400F4D64C /* PSCollectionView */, + 8A35E150171F8F0C00F4D64C /* AppDelegate.h */, + 8A35E151171F8F0C00F4D64C /* AppDelegate.m */, + 8A35E159171F8F0C00F4D64C /* ViewController.h */, + 8A35E15A171F8F0C00F4D64C /* ViewController.m */, + 8A35E15C171F8F0D00F4D64C /* ViewController.xib */, + 8A35E148171F8F0C00F4D64C /* Supporting Files */, + ); + path = PSCollectionViewDemo; + sourceTree = ""; + }; + 8A35E148171F8F0C00F4D64C /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 8A35E149171F8F0C00F4D64C /* PSCollectionViewDemo-Info.plist */, + 8A35E14A171F8F0C00F4D64C /* InfoPlist.strings */, + 8A35E14D171F8F0C00F4D64C /* main.m */, + 8A35E14F171F8F0C00F4D64C /* PSCollectionViewDemo-Prefix.pch */, + 8A35E153171F8F0C00F4D64C /* Default.png */, + 8A35E155171F8F0C00F4D64C /* Default@2x.png */, + 8A35E157171F8F0C00F4D64C /* Default-568h@2x.png */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 8A35E164171F8FB400F4D64C /* PSCollectionView */ = { + isa = PBXGroup; + children = ( + 8A35E165171F901200F4D64C /* PSCollectionView.h */, + 8A35E166171F901200F4D64C /* PSCollectionView.m */, + 8A35E167171F901200F4D64C /* PSCollectionViewCell.h */, + 8A35E168171F901200F4D64C /* PSCollectionViewCell.m */, + ); + name = PSCollectionView; + sourceTree = ""; + }; + 8A35E16B171F902000F4D64C /* MKNetworkKit */ = { + isa = PBXGroup; + children = ( + 8A35E16C171F911400F4D64C /* Categories */, + 8A35E179171F911400F4D64C /* MKNetworkEngine.h */, + 8A35E17A171F911400F4D64C /* MKNetworkEngine.m */, + 8A35E17B171F911400F4D64C /* MKNetworkKit.h */, + 8A35E17C171F911400F4D64C /* MKNetworkOperation.h */, + 8A35E17D171F911400F4D64C /* MKNetworkOperation.m */, + 8A35E17E171F911400F4D64C /* Reachability */, + ); + name = MKNetworkKit; + sourceTree = ""; + }; + 8A35E16C171F911400F4D64C /* Categories */ = { + isa = PBXGroup; + children = ( + 8A35E16D171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.h */, + 8A35E16E171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.m */, + 8A35E16F171F911400F4D64C /* NSData+Base64.h */, + 8A35E170171F911400F4D64C /* NSData+Base64.m */, + 8A35E171171F911400F4D64C /* NSDate+RFC1123.h */, + 8A35E172171F911400F4D64C /* NSDate+RFC1123.m */, + 8A35E173171F911400F4D64C /* NSDictionary+RequestEncoding.h */, + 8A35E174171F911400F4D64C /* NSDictionary+RequestEncoding.m */, + 8A35E175171F911400F4D64C /* NSString+MKNetworkKitAdditions.h */, + 8A35E176171F911400F4D64C /* NSString+MKNetworkKitAdditions.m */, + 8A35E177171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.h */, + 8A35E178171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.m */, + ); + path = Categories; + sourceTree = ""; + }; + 8A35E17E171F911400F4D64C /* Reachability */ = { + isa = PBXGroup; + children = ( + 8A35E17F171F911400F4D64C /* Reachability.h */, + 8A35E180171F911400F4D64C /* Reachability.m */, + ); + path = Reachability; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 8A35E13D171F8F0C00F4D64C /* PSCollectionViewDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8A35E161171F8F0D00F4D64C /* Build configuration list for PBXNativeTarget "PSCollectionViewDemo" */; + buildPhases = ( + 8A35E13A171F8F0C00F4D64C /* Sources */, + 8A35E13B171F8F0C00F4D64C /* Frameworks */, + 8A35E13C171F8F0C00F4D64C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PSCollectionViewDemo; + productName = PSCollectionViewDemo; + productReference = 8A35E13E171F8F0C00F4D64C /* PSCollectionViewDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 8A35E136171F8F0C00F4D64C /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0460; + ORGANIZATIONNAME = opomelo; + }; + buildConfigurationList = 8A35E139171F8F0C00F4D64C /* Build configuration list for PBXProject "PSCollectionViewDemo" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 8A35E135171F8F0C00F4D64C; + productRefGroup = 8A35E13F171F8F0C00F4D64C /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8A35E13D171F8F0C00F4D64C /* PSCollectionViewDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8A35E13C171F8F0C00F4D64C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8A35E14C171F8F0C00F4D64C /* InfoPlist.strings in Resources */, + 8A35E154171F8F0C00F4D64C /* Default.png in Resources */, + 8A35E156171F8F0C00F4D64C /* Default@2x.png in Resources */, + 8A35E158171F8F0C00F4D64C /* Default-568h@2x.png in Resources */, + 8A35E15E171F8F0D00F4D64C /* ViewController.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 8A35E13A171F8F0C00F4D64C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8A35E14E171F8F0C00F4D64C /* main.m in Sources */, + 8A35E152171F8F0C00F4D64C /* AppDelegate.m in Sources */, + 8A35E15B171F8F0C00F4D64C /* ViewController.m in Sources */, + 8A35E169171F901200F4D64C /* PSCollectionView.m in Sources */, + 8A35E16A171F901200F4D64C /* PSCollectionViewCell.m in Sources */, + 8A35E181171F911400F4D64C /* NSAlert+MKNetworkKitAdditions.m in Sources */, + 8A35E182171F911400F4D64C /* NSData+Base64.m in Sources */, + 8A35E183171F911400F4D64C /* NSDate+RFC1123.m in Sources */, + 8A35E184171F911400F4D64C /* NSDictionary+RequestEncoding.m in Sources */, + 8A35E185171F911400F4D64C /* NSString+MKNetworkKitAdditions.m in Sources */, + 8A35E186171F911400F4D64C /* UIAlertView+MKNetworkKitAdditions.m in Sources */, + 8A35E187171F911400F4D64C /* MKNetworkEngine.m in Sources */, + 8A35E188171F911400F4D64C /* MKNetworkOperation.m in Sources */, + 8A35E189171F911400F4D64C /* Reachability.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 8A35E14A171F8F0C00F4D64C /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + 8A35E14B171F8F0C00F4D64C /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; + 8A35E15C171F8F0D00F4D64C /* ViewController.xib */ = { + isa = PBXVariantGroup; + children = ( + 8A35E15D171F8F0D00F4D64C /* en */, + ); + name = ViewController.xib; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 8A35E15F171F8F0D00F4D64C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 6.1; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 8A35E160171F8F0D00F4D64C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 6.1; + OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 8A35E162171F8F0D00F4D64C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch"; + INFOPLIST_FILE = "PSCollectionViewDemo/PSCollectionViewDemo-Info.plist"; + PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; + }; + name = Debug; + }; + 8A35E163171F8F0D00F4D64C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch"; + INFOPLIST_FILE = "PSCollectionViewDemo/PSCollectionViewDemo-Info.plist"; + PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 8A35E139171F8F0C00F4D64C /* Build configuration list for PBXProject "PSCollectionViewDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8A35E15F171F8F0D00F4D64C /* Debug */, + 8A35E160171F8F0D00F4D64C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8A35E161171F8F0D00F4D64C /* Build configuration list for PBXNativeTarget "PSCollectionViewDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8A35E162171F8F0D00F4D64C /* Debug */, + 8A35E163171F8F0D00F4D64C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 8A35E136171F8F0C00F4D64C /* Project object */; +} diff --git a/PSCollectionViewDemo/AppDelegate.h b/PSCollectionViewDemo/AppDelegate.h new file mode 100644 index 0000000..5d80363 --- /dev/null +++ b/PSCollectionViewDemo/AppDelegate.h @@ -0,0 +1,19 @@ +// +// AppDelegate.h +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import + +@class ViewController; + +@interface AppDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + +@property (strong, nonatomic) ViewController *viewController; + +@end diff --git a/PSCollectionViewDemo/AppDelegate.m b/PSCollectionViewDemo/AppDelegate.m new file mode 100644 index 0000000..2695d3d --- /dev/null +++ b/PSCollectionViewDemo/AppDelegate.m @@ -0,0 +1,52 @@ +// +// AppDelegate.m +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import "AppDelegate.h" + +#import "ViewController.h" + +@implementation AppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; + // Override point for customization after application launch. + self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; + self.window.rootViewController = self.viewController; + [self.window makeKeyAndVisible]; + return YES; +} + +- (void)applicationWillResignActive:(UIApplication *)application +{ + // 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. +} + +- (void)applicationDidEnterBackground:(UIApplication *)application +{ + // 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. +} + +- (void)applicationWillEnterForeground:(UIApplication *)application +{ + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. +} + +- (void)applicationDidBecomeActive:(UIApplication *)application +{ + // 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. +} + +- (void)applicationWillTerminate:(UIApplication *)application +{ + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. +} + +@end diff --git a/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.h b/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.h new file mode 100644 index 0000000..6cfd724 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.h @@ -0,0 +1,32 @@ +// +// NSAlert+MKNetworkKitAdditions.h +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !TARGET_OS_IPHONE +#import + +@interface NSAlert (MKNetworkKitAdditions) ++(NSAlert*) showWithError:(NSError*) networkError; +@end +#endif \ No newline at end of file diff --git a/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.m b/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.m new file mode 100644 index 0000000..ab1dac8 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSAlert+MKNetworkKitAdditions.m @@ -0,0 +1,39 @@ +// +// NSAlert+MKNetworkKitAdditions.m +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +#if !TARGET_OS_IPHONE +#import "NSAlert+MKNetworkKitAdditions.h" + +@implementation NSAlert (MKNetworkKitAdditions) + ++(NSAlert*) showWithError:(NSError*) networkError { + + DLog(@"%@", [networkError userInfo]); + + NSAlert *alert = [NSAlert alertWithError:networkError]; + [alert runModal]; + return alert; +} +@end +#endif \ No newline at end of file diff --git a/PSCollectionViewDemo/Categories/NSData+Base64.h b/PSCollectionViewDemo/Categories/NSData+Base64.h new file mode 100644 index 0000000..118c4e1 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSData+Base64.h @@ -0,0 +1,42 @@ +// +// NSData+Base64.h +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// 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. +// + +#import + +void *NewBase64Decode( + const char *inputBuffer, + size_t length, + size_t *outputLength); + +char *NewBase64Encode( + const void *inputBuffer, + size_t length, + bool separateLines, + size_t *outputLength); + +@interface NSData (Base64) + ++ (NSData *)dataFromBase64String:(NSString *)aString; +- (NSString *)base64EncodedString; + +@end diff --git a/PSCollectionViewDemo/Categories/NSData+Base64.m b/PSCollectionViewDemo/Categories/NSData+Base64.m new file mode 100644 index 0000000..aac39dc --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSData+Base64.m @@ -0,0 +1,312 @@ +// +// NSData+Base64.m +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// 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. +// + +#import "NSData+Base64.h" + +// +// Mapping from 6 bit pattern to ASCII character. +// +static unsigned char base64EncodeLookup[65] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// +// Definition for "masked-out" areas of the base64DecodeLookup mapping +// +#define xx 65 + +// +// Mapping from ASCII character to 6 bit pattern. +// +static unsigned char base64DecodeLookup[256] = +{ + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, 62, xx, xx, xx, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, xx, xx, xx, xx, xx, xx, + xx, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, xx, xx, xx, xx, xx, + xx, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, +}; + +// +// Fundamental sizes of the binary and base64 encode/decode units in bytes +// +#define BINARY_UNIT_SIZE 3 +#define BASE64_UNIT_SIZE 4 + +// +// NewBase64Decode +// +// Decodes the base64 ASCII string in the inputBuffer to a newly malloced +// output buffer. +// +// inputBuffer - the source ASCII string for the decode +// length - the length of the string or -1 (to specify strlen should be used) +// outputLength - if not-NULL, on output will contain the decoded length +// +// returns the decoded buffer. Must be free'd by caller. Length is given by +// outputLength. +// +void *NewBase64Decode( + const char *inputBuffer, + size_t length, + size_t *outputLength) +{ + if (length == -1) + { + length = strlen(inputBuffer); + } + + size_t outputBufferSize = + ((length+BASE64_UNIT_SIZE-1) / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE; + unsigned char *outputBuffer = (unsigned char *)malloc(outputBufferSize); + + size_t i = 0; + size_t j = 0; + while (i < length) + { + // + // Accumulate 4 valid characters (ignore everything else) + // + unsigned char accumulated[BASE64_UNIT_SIZE]; + size_t accumulateIndex = 0; + while (i < length) + { + unsigned char decode = base64DecodeLookup[inputBuffer[i++]]; + if (decode != xx) + { + accumulated[accumulateIndex] = decode; + accumulateIndex++; + + if (accumulateIndex == BASE64_UNIT_SIZE) + { + break; + } + } + } + + // + // Store the 6 bits from each of the 4 characters as 3 bytes + // + // (Uses improved bounds checking suggested by Alexandre Colucci) + // + if(accumulateIndex >= 2) + outputBuffer[j] = (accumulated[0] << 2) | (accumulated[1] >> 4); + if(accumulateIndex >= 3) + outputBuffer[j + 1] = (accumulated[1] << 4) | (accumulated[2] >> 2); + if(accumulateIndex >= 4) + outputBuffer[j + 2] = (accumulated[2] << 6) | accumulated[3]; + j += accumulateIndex - 1; + } + + if (outputLength) + { + *outputLength = j; + } + return outputBuffer; +} + +// +// NewBase64Encode +// +// Encodes the arbitrary data in the inputBuffer as base64 into a newly malloced +// output buffer. +// +// inputBuffer - the source data for the encode +// length - the length of the input in bytes +// separateLines - if zero, no CR/LF characters will be added. Otherwise +// a CR/LF pair will be added every 64 encoded chars. +// outputLength - if not-NULL, on output will contain the encoded length +// (not including terminating 0 char) +// +// returns the encoded buffer. Must be free'd by caller. Length is given by +// outputLength. +// +char *NewBase64Encode( + const void *buffer, + size_t length, + bool separateLines, + size_t *outputLength) +{ + const unsigned char *inputBuffer = (const unsigned char *)buffer; + + #define MAX_NUM_PADDING_CHARS 2 + #define OUTPUT_LINE_LENGTH 64 + #define INPUT_LINE_LENGTH ((OUTPUT_LINE_LENGTH / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE) + #define CR_LF_SIZE 2 + + // + // Byte accurate calculation of final buffer size + // + size_t outputBufferSize = + ((length / BINARY_UNIT_SIZE) + + ((length % BINARY_UNIT_SIZE) ? 1 : 0)) + * BASE64_UNIT_SIZE; + if (separateLines) + { + outputBufferSize += + (outputBufferSize / OUTPUT_LINE_LENGTH) * CR_LF_SIZE; + } + + // + // Include space for a terminating zero + // + outputBufferSize += 1; + + // + // Allocate the output buffer + // + char *outputBuffer = (char *)malloc(outputBufferSize); + if (!outputBuffer) + { + return NULL; + } + + size_t i = 0; + size_t j = 0; + const size_t lineLength = separateLines ? INPUT_LINE_LENGTH : length; + size_t lineEnd = lineLength; + + while (true) + { + if (lineEnd > length) + { + lineEnd = length; + } + + for (; i + BINARY_UNIT_SIZE - 1 < lineEnd; i += BINARY_UNIT_SIZE) + { + // + // Inner loop: turn 48 bytes into 64 base64 characters + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i + 1] & 0x0F) << 2) + | ((inputBuffer[i + 2] & 0xC0) >> 6)]; + outputBuffer[j++] = base64EncodeLookup[inputBuffer[i + 2] & 0x3F]; + } + + if (lineEnd == length) + { + break; + } + + // + // Add the newline + // + outputBuffer[j++] = '\r'; + outputBuffer[j++] = '\n'; + lineEnd += lineLength; + } + + if (i + 1 < length) + { + // + // Handle the single '=' case + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i + 1] & 0x0F) << 2]; + outputBuffer[j++] = '='; + } + else if (i < length) + { + // + // Handle the double '=' case + // + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0x03) << 4]; + outputBuffer[j++] = '='; + outputBuffer[j++] = '='; + } + outputBuffer[j] = 0; + + // + // Set the output length and return the buffer + // + if (outputLength) + { + *outputLength = j; + } + return outputBuffer; +} + +@implementation NSData (Base64) + +// +// dataFromBase64String: +// +// Creates an NSData object containing the base64 decoded representation of +// the base64 string 'aString' +// +// Parameters: +// aString - the base64 string to decode +// +// returns the autoreleased NSData representation of the base64 string +// ++ (NSData *)dataFromBase64String:(NSString *)aString +{ + NSData *data = [aString dataUsingEncoding:NSASCIIStringEncoding]; + size_t outputLength; + void *outputBuffer = NewBase64Decode([data bytes], [data length], &outputLength); + NSData *result = [NSData dataWithBytes:outputBuffer length:outputLength]; + free(outputBuffer); + return result; +} + +// +// base64EncodedString +// +// Creates an NSString object that contains the base 64 encoding of the +// receiver's data. Lines are broken at 64 characters long. +// +// returns an autoreleased NSString being the base 64 representation of the +// receiver. +// +- (NSString *)base64EncodedString +{ + size_t outputLength; + char *outputBuffer = + NewBase64Encode([self bytes], [self length], false, &outputLength); + + NSString *result = + [[NSString alloc] + initWithBytes:outputBuffer + length:outputLength + encoding:NSASCIIStringEncoding]; + free(outputBuffer); + return result; +} + +@end diff --git a/PSCollectionViewDemo/Categories/NSDate+RFC1123.h b/PSCollectionViewDemo/Categories/NSDate+RFC1123.h new file mode 100644 index 0000000..02ba774 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSDate+RFC1123.h @@ -0,0 +1,25 @@ +// +// NSDate+RFC1123.h +// MKNetworkKit +// +// Created by Marcus Rohrmoser +// http://blog.mro.name/2009/08/nsdateformatter-http-header/ +// http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + +// No obvious license attached + +@interface NSDate (RFC1123) +/** + Convert a RFC1123 'Full-Date' string + (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1) + into NSDate. + */ ++(NSDate*)dateFromRFC1123:(NSString*)value_; + +/** + Convert NSDate into a RFC1123 'Full-Date' string + (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1). + */ +-(NSString*)rfc1123String; + +@end diff --git a/PSCollectionViewDemo/Categories/NSDate+RFC1123.m b/PSCollectionViewDemo/Categories/NSDate+RFC1123.m new file mode 100644 index 0000000..f9071b4 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSDate+RFC1123.m @@ -0,0 +1,79 @@ +// +// NSDate+RFC1123.m +// MKNetworkKit +// +// Created by Marcus Rohrmoser +// http://blog.mro.name/2009/08/nsdateformatter-http-header/ +// +// No obvious license attached + +#import "NSDate+RFC1123.h" + +@implementation NSDate (RFC1123) + ++(NSDate*)dateFromRFC1123:(NSString*)value_ +{ + if(value_ == nil) + return nil; + + __strong static NSDateFormatter *rfc1123 = nil; + if (!rfc1123) { + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + rfc1123 = [[NSDateFormatter alloc] init]; + rfc1123.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; + rfc1123.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; + rfc1123.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z"; + }); + } + NSDate *ret = [rfc1123 dateFromString:value_]; + if(ret != nil) + return ret; + + static NSDateFormatter *rfc850 = nil; + if(!rfc850) + { + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + rfc850 = [[NSDateFormatter alloc] init]; + rfc850.locale = rfc1123.locale; + rfc850.timeZone = rfc1123.timeZone; + rfc850.dateFormat = @"EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z"; + }); + } + ret = [rfc850 dateFromString:value_]; + if(ret != nil) + return ret; + + static NSDateFormatter *asctime = nil; + if(!asctime) + { + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + + asctime = [[NSDateFormatter alloc] init]; + asctime.locale = rfc1123.locale; + asctime.timeZone = rfc1123.timeZone; + asctime.dateFormat = @"EEE MMM d HH':'mm':'ss yyyy"; + }); + } + return [asctime dateFromString:value_]; +} + +-(NSString*)rfc1123String +{ + static NSDateFormatter *df = nil; + if(!df) + { + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + df = [[NSDateFormatter alloc] init]; + df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; + df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; + df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"; + }); + } + return [df stringFromDate:self]; +} + +@end diff --git a/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.h b/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.h new file mode 100644 index 0000000..f7db868 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.h @@ -0,0 +1,31 @@ +// +// NSDictionary+RequestEncoding.h +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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. + +@interface NSDictionary (RequestEncoding) + +-(NSString*) urlEncodedKeyValueString; +-(NSString*) jsonEncodedKeyValueString; +-(NSString*) plistEncodedKeyValueString; +@end diff --git a/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.m b/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.m new file mode 100644 index 0000000..bf1e50f --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSDictionary+RequestEncoding.m @@ -0,0 +1,74 @@ +// +// NSDictionary+RequestEncoding.m +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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 "MKNetworkKit.h" + +@implementation NSDictionary (RequestEncoding) + +-(NSString*) urlEncodedKeyValueString { + + NSMutableString *string = [NSMutableString string]; + for (NSString *key in self) { + + NSObject *value = [self valueForKey:key]; + if([value isKindOfClass:[NSString class]]) + [string appendFormat:@"%@=%@&", [key urlEncodedString], [((NSString*)value) urlEncodedString]]; + else + [string appendFormat:@"%@=%@&", [key urlEncodedString], value]; + } + + if([string length] > 0) + [string deleteCharactersInRange:NSMakeRange([string length] - 1, 1)]; + + return string; +} + + +-(NSString*) jsonEncodedKeyValueString { + + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:self + options:0 // non-pretty printing + error:&error]; + if(error) + DLog(@"JSON Parsing Error: %@", error); + + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; +} + + +-(NSString*) plistEncodedKeyValueString { + + NSError *error = nil; + NSData *data = [NSPropertyListSerialization dataWithPropertyList:self + format:NSPropertyListXMLFormat_v1_0 + options:0 error:&error]; + if(error) + DLog(@"JSON Parsing Error: %@", error); + + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; +} + +@end diff --git a/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.h b/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.h new file mode 100644 index 0000000..010e703 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.h @@ -0,0 +1,32 @@ +// +// NSString+MKNetworkKitAdditions.h +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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. + +@interface NSString (MKNetworkKitAdditions) + +- (NSString *) md5; ++ (NSString*) uniqueString; +- (NSString*) urlEncodedString; +- (NSString*) urlDecodedString; +@end diff --git a/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.m b/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.m new file mode 100644 index 0000000..9202531 --- /dev/null +++ b/PSCollectionViewDemo/Categories/NSString+MKNetworkKitAdditions.m @@ -0,0 +1,81 @@ +// +// NSString+MKNetworkKitAdditions.m +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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 "NSString+MKNetworkKitAdditions.h" +#import + +@implementation NSString (MKNetworkKitAdditions) + +- (NSString *) md5 +{ + const char *cStr = [self UTF8String]; + unsigned char result[16]; + CC_MD5( cStr, (unsigned int) strlen(cStr), result); + return [NSString stringWithFormat: + @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + result[0], result[1], result[2], result[3], + result[4], result[5], result[6], result[7], + result[8], result[9], result[10], result[11], + result[12], result[13], result[14], result[15] + ]; +} + ++ (NSString*) uniqueString +{ + CFUUIDRef uuidObj = CFUUIDCreate(nil); + NSString *uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(nil, uuidObj); + CFRelease(uuidObj); + return uuidString; +} + +- (NSString*) urlEncodedString { + + CFStringRef encodedCFString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, + (__bridge CFStringRef) self, + nil, + CFSTR("?!@#$^&%*+,:;='\"`<>()[]{}/\\| "), + kCFStringEncodingUTF8); + + NSString *encodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) encodedCFString]; + + if(!encodedString) + encodedString = @""; + + return encodedString; +} + +- (NSString*) urlDecodedString { + + CFStringRef decodedCFString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, + (__bridge CFStringRef) self, + CFSTR(""), + kCFStringEncodingUTF8); + + // We need to replace "+" with " " because the CF method above doesn't do it + NSString *decodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) decodedCFString]; + return (!decodedString) ? @"" : [decodedString stringByReplacingOccurrencesOfString:@"+" withString:@" "]; +} + +@end \ No newline at end of file diff --git a/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.h b/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.h new file mode 100644 index 0000000..913ee40 --- /dev/null +++ b/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.h @@ -0,0 +1,31 @@ +// +// UIAlertView+MKNetworkKitAdditions.h +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +#if TARGET_OS_IPHONE +#import + +@interface UIAlertView (MKNetworkKitAdditions) ++(UIAlertView*) showWithError:(NSError*) networkError; +@end +#endif \ No newline at end of file diff --git a/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.m b/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.m new file mode 100644 index 0000000..9c80f58 --- /dev/null +++ b/PSCollectionViewDemo/Categories/UIAlertView+MKNetworkKitAdditions.m @@ -0,0 +1,41 @@ +// +// UIAlertView+MKNetworkKitAdditions.m +// MKNetworkKitDemo +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +#if TARGET_OS_IPHONE +#import "UIAlertView+MKNetworkKitAdditions.h" + +@implementation UIAlertView (MKNetworkKitAdditions) + ++(UIAlertView*) showWithError:(NSError*) networkError { + + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[networkError localizedDescription] + message:[networkError localizedRecoverySuggestion] + delegate:nil + cancelButtonTitle:NSLocalizedString(@"Dismiss", @"") + otherButtonTitles:nil]; + [alert show]; + return alert; +} +@end +#endif \ No newline at end of file diff --git a/PSCollectionViewDemo/Default-568h@2x.png b/PSCollectionViewDemo/Default-568h@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0891b7aabfcf3422423b109c8beed2bab838c607 GIT binary patch literal 18594 zcmeI4X;f257Jx&9fS`ixvS;&$x8J@slQFSel)6zJN=?13FB7H(lQjRkSy8x_-S~tvu2gzn1oS+dLcF#eqtq$ z%tf9TTvX?`)R@}3uBI;jzS-=ZR-Td&MHaS&;!0?Ni*#$#`n*~CcQK)Q9vAQ~TUpnI!j)a2biYK^R)M~A5wUDZhx?ULMX z3x1P&qt=trOY6P2U67L=m=U?F|5#Uj(eCueNTZaHs_ceWiHeET+j+tp3Jt9g(ekqP z2WOvfR{qV+9r+o4J5?qK>7;;^+I7tGv-i)es$X_D=EoKF+S?zsyj^oRFElP}c}JT< zd8SUs-?O?}2YD#ngKbnHgzHBcboxK_2r9l(?eNCl-pEzkJm}fY?WC*jnS?VBE4EpY zO$fEejz6fU;W2Kl>JeQBZBl-%Irg`obSlg*@4QB;Dd1H7^Oi5wvt4d{RZ!8Og?^aE z)k0$1g+V3fd(gdQ3d&q2q-FL*uy#}|bc^=VhFsl0jBgUGJ+-s3U8MK9A!YJJMxpci z5hJ%|{DwV48fZn0{n5l$N_KcSb#NKE4plB`9I6Zt=Z!~-zw0{9tg$L&Ju1F0X)Cy8 zKF;(&lJ>x)Jw(=;p~sF(Sd9VWGwFE2rnyS9!f^DZ8+aCLq zQ};>lcJ1GDLqjm6Hd>|Eabno@P`~Bn(~6^aD_#yoEH(a?Nm1S<;S+hSxI5d16^<1lEM3NPFi zkqPrpL)+ zgnseFikg`gJVBha1&7C4;O6>h=dt~`ND+;Zd?W(4v2JIb7Pt>Td42%M-Ju-XAH#Pns762L}K3 zDhvsRqN0Ni(1UrishD2YvV?4*h2iFj$+&N||Fn$4n|^NSU+o?~jq`0jVQt8T9l{7b zXiwwODFh2V!Q6sqP9S>WH$oOf$N~=d0-bqTlD61!=`&0eAP-F>XN?*|gtOXX{ zQVTWyYo4ZK0GAw!GHf|pz9`D;-bbb*5LBX*{bnz|+)$@&P9|ORM2o?95{;ejvo&r- zq8cBhTN6nn)7~W>54U)%-F_-b?YKdfk5I8MHcuzBD5)!;yv#Z&R&^y=@=>VTIMy#r zX&U<=BsPkdqcMe<_}2+>H%XKyrr5ZR8_KVe>ZqYN z^=^~TFD};;rHJ$U;{~w^hYojl4hRI@SH$^K{YEo=sg)WY87r!*7blQK&qnpDo0`Vn zkl)9u9g=mCh&ZCJS(L4yN3k0kQ zuvg$h2KEEk51T+O0JQ+r0`R>g{jvqM0Mr6d3qUOZwE!?PI7HY@CE|dr sfw?Q;rAv?G4&^^8-z_>&sWXMxvD*gPOU4CBe-*@OtE+wfmVJNyHv)PfH~;_u literal 0 HcmV?d00001 diff --git a/PSCollectionViewDemo/Default.png b/PSCollectionViewDemo/Default.png new file mode 100644 index 0000000000000000000000000000000000000000..4c8ca6f693f96d511e9113c0eb59eec552354e42 GIT binary patch literal 6540 zcmeAS@N?(olHy`uVBq!ia0y~yU~~ZD2OMlbkt;o0To@QwR5G2N13aCb6#|O#(=u~X z85k@CTSM>X-wqM6>&y>YB4)1;;ojbLbbV-W^iFB1wa3^zCog^LCAReC4K0-?R_2{6 zrP*)4+_uWUy3w5N52M3PW_}MFMP9a~>YLvVZ1D_k*IMQ2QT^fwzoOb(*3gH$%aYWC zkHmcab=va2<#X%jakpJ;<1@F;k__#bwtC&%^D0v(FBh9K&$sK+<}2RJS609D)17$w ztdQP8(eLM8Ka}m_IQ@3wyMKP)l=oM4-?`YS_*P?4V_ORLPxsj&7Ju#kH;>6^Kp?T7~ zl+q?{UOOqV==?+d{=)5s|M~T1mwtH@+Z^$G&eEO9JNP^AX@3jZ*J*!!>lc|1-W%fA z@AOQpXZ_Lt>rxFXrGp*zLPiW@uo_c7C{As>j zWeX)wi+LTp_)@KYZCX{j;H?|1yXT4DnlS(Fr8gyP5|uaX_gLvaW0ScZdnG7o+u{T6 zFI-%d{ls*WuCDa5UJ@|RXv&ejZe}*BMkiWY51&pnRPw(hlykSzvj6e%mYz-GdvzBD zF10?szF_~!jS=?2HyQuPCvARXAe}C}WP|yQ*>5~~=*Nxq8+HHW1~FMDRCP^TcacKuk$ z(U#REVv)D!PhJ*ecH-ELFUrfyV&*)Z)>UCOuS?yd^L@Afk>ihynYPc{^CRwu+JHX+#$@YsC4c|l0tGigsn@jy) zXD($Ouk>H+V(Mr6NQT0S9BFM~V6nkj;1OBOz`zY;a|<&v%$g$sEJPk;hD4M^`1)8S z=jZArrsOB3>Q&?x097+E*i={nnYpPYi3%0DIeEoa6}C!X6;?ntNLXJ<0j#7X+g2&U zH$cHTzbI9~RL@Y)NXd>%K|#T$C?(A*$i)q+9mum)$|xx*u+rBrFE7_CH`dE9O4m2E zw6xSWFw!?N(gmu}Ew0QfNvzP#D^`XW0yD=YwK%ybv!En1KTiQ3|)OBHVcpi zp&D%TL4k-AsNfg_g$9~9p}$+4Ynr|VULLgiakg&)DD)EWO!OHC@snXr}UI${nVUP zpr1>Mf#G6^ng~;pt%^&NvQm>vU@-wn)!_JWN=(;B61LIDR86%A1?G9U(@`={MPdPF zbOKdd`R1o&rd7HmmZaJl85kPr8kp-EnTHsfS{ayIfdU*&4N@e5WSomq6HD@oLh|!- z?7;Dr3*ssm=^5w&a}>G?yzvAH17L|`#|6|0E4}QvA~xC{V_*wu2^AHZU}H9f($4F$btFf{}TLQXUhF5fht1@YV$^ z9BUdFV+73^nIsvRXRM40U}6b7z_6}kHbY}i1LK(xT@6Mi?F5GKBfbp|ZU-3BR*6kv zXcRSQ(0-)mprD+wTr)o_4I;(%zOu)+jEgNB)_SXCVoSa}|F?cfwR!69+L=W3IX z!UiU`0@ph%94Rb33Cpq^IY*r_8XBW%V>G9XmK&p`=xCiXTEmXEH%41uqixaAmicH0 zVYIt6!aI*K%s=kP-v##6IXGZ2Cama>{@)81;C?K-P&M2k<0!GL}5+H~XTq*@SQi|Ft z2*0X`$`8S!qO#)xBeJRkf?;t189=ZB6Imw-h=`q;FP(2UpWZvmJ@=k-@45M(dtb7r zyVEiaLk$=Vw#>zu;st}j6Jf9=m1+nXCFe!$1PrEZ%5Ze_ba8YX_9-*rJujiLuQmJo&2v+Cxes}ec zU|qeux&7*yz#W=X_|wGQskL7*OHNjwFs@sEC+64Hb$Z(#H21Gh$Pe2WzOubdr6fzg z{l{!k%OD?N5Z7j33SoK?YdV6Scm>})U+MIQLNRgIvkZQEc^mP9XBPg%y|S$~Br|;N zk?-!-(Qqh_mQ|6WINQ{hHAjBRV#O#!FkAJ+oxy`L#f8V45*VvWMJFBB5m zG6vOLtDvgoDjHlSq-*h5xM56O>Jjau2f2IxKItIb@coX4XTyf$^{LZG&lI|D95wN1 z!fo0)q>WV7-V;q|A?HR!*bgozJw%j98-~gwBKVV0;=hZIF>7oJSr2YjOWO*rSxz#& z;KXnDrJVZp;Yduiy1-H%s$ZFz6Q=x@$V_B@Tqwl?>6e;EHt|MiK<(#hXQMuj@Jseeh&eN{FxsQ$iw>D1aX1HMMlUbh?Z zmhY4eHffn5&LUbL_}o8|$JYz&$WFiLWmEg0ZPX+;W>@CxQz-%{E5+P7dH9&ey_y$R z@Zzje>2B%z!i!7Brqi{t5Y)~5>vpqRs~2aXD8DVE8vKl=`k(`duI1-k@?!pJ^HA6S zS;3WpuhjQHyoC>X>Xf8gze%_8^#+^RTV>V9&YPAWMjd~%xpSg?ON?kK^X*Pb(o8jR zz;DmaOWMMr6=M~K?MFx4_xDkARTxLJ@W@ohAx z5RD0jGgk?QL@H`VubD2k4}?VtB8@g`%hHBA$2pJ(gK5g1HMNysXEF_BNu-p!&+Qa8_APgopHWnRgg=TZZF*sXWTMQPD z!Q(Au5|+F;7M~`tWbsU98~NA{h0Y7%GB|t&n}w9OOABU4^X*V5xuN;rY(M#ouuqm) zyt!e?28fY!FgP?8GvBsMl_aM^UUVKiGFsleFN?t^<46kO#pF-cX0;sIOb(aM z)^jQgX^Z6pKA9mC@N)_aiHj9HxD2|?A@Y9B_h}(*v3%ek8CXc1Qy^jFPF&zrMa1OZ zSVaF{&ZY|(|H0XE&X>-XQz1`=fF2n@VKC_|h3jlKVM&-jmyMavllcYr`6LVtfq2ou zd+8zkkCB+2)rxq0Lkq_&Ad@g(O8;pAm96>tu79?81T@Z<;gm^3ZtPG-SR94Mr<3tm z9NrR3u*4I5aMlo(09g@8m_;%Rf+XiSa_KZao9n}7N0JrsV#;5Ucr+F*TTzQ8{%f3O zeIUy?WDS|-$LvMc@Z7320)tr}bfIka5hx9H;8H|%our=C+Do0CSFRWue14o5#r8v2 zw=|&r4*eMX%lgCV(ka?*j%H^UuP4LmBC(ON`)&7>NF-|PDRU{-7o`CU0HNbd&c~))@yl9IKu_ zXA+A-!khpP_yx=f#qt2_0ptmgBf4gF!{Y)MW6R$cC1d7@$Yb?+_j zYwfE^5_e`vhT zX=u3r>4$fsxP&apbm@Rcbyuc2T=giqZiMo9@9=oua6#YH0hO-1ak9^rJTPMM qY4Yr5Cu^v99p{E9VdroUHKlRW;M8#BJ^AOQE?e9wSHJo8(7yq;BYKSh literal 0 HcmV?d00001 diff --git a/PSCollectionViewDemo/MKNetworkEngine.h b/PSCollectionViewDemo/MKNetworkEngine.h new file mode 100644 index 0000000..b33737e --- /dev/null +++ b/PSCollectionViewDemo/MKNetworkEngine.h @@ -0,0 +1,335 @@ +// +// MKNetworkEngine.h +// MKNetworkKit +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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 "MKNetworkKit.h" +/*! + @header MKNetworkEngine.h + @abstract Represents a subclassable Network Engine for your app + */ + +/*! + * @class MKNetworkEngine + * @abstract Represents a subclassable Network Engine for your app + * + * @discussion + * This class is the heart of MKNetworkEngine + * You create network operations and enqueue them here + * MKNetworkEngine encapsulates a Reachability object that relieves you of managing network connectivity losses + * MKNetworkEngine also allows you to provide custom header fields that gets appended automatically to every request + */ +@interface MKNetworkEngine : NSObject + +/*! + * @abstract Initializes your network engine with a hostname + * + * @discussion + * Creates an engine for a given host name + * The hostname parameter is optional + * The hostname, if not null, initializes a Reachability notifier. + * Network reachability notifications are automatically taken care of by MKNetworkEngine + * + */ +- (id) initWithHostName:(NSString*) hostName; +/*! + * @abstract Initializes your network engine with a hostname and custom header fields + * + * @discussion + * Creates an engine for a given host name + * The default headers you specify here will be appened to every operation created in this engine + * The hostname, if not null, initializes a Reachability notifier. + * Network reachability notifications are automatically taken care of by MKNetworkEngine + * Both parameters are optional + * + */ +- (id) initWithHostName:(NSString*) hostName customHeaderFields:(NSDictionary*) headers; + +/*! + * @abstract Initializes your network engine with a hostname + * + * @discussion + * Creates an engine for a given host name + * The hostname parameter is optional + * The apiPath paramter is optional + * The apiPath is prefixed to every call to operationWithPath: You can use this method if your server's API location is not at the root (/) + * The hostname, if not null, initializes a Reachability notifier. + * Network reachability notifications are automatically taken care of by MKNetworkEngine + * + */ +- (id) initWithHostName:(NSString*) hostName apiPath:(NSString*) apiPath customHeaderFields:(NSDictionary*) headers; +/*! + * @abstract Creates a simple GET Operation with a request URL + * + * @discussion + * Creates an operation with the given URL path. + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The HTTP Method is implicitly assumed to be GET + * + */ + +-(MKNetworkOperation*) operationWithPath:(NSString*) path; + +/*! + * @abstract Creates a simple GET Operation with a request URL and parameters + * + * @discussion + * Creates an operation with the given URL path. + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The body dictionary in this method gets attached to the URL as query parameters + * The HTTP Method is implicitly assumed to be GET + * + */ +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body; + +/*! + * @abstract Creates a simple GET Operation with a request URL, parameters and HTTP Method + * + * @discussion + * Creates an operation with the given URL path. + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The params dictionary in this method gets attached to the URL as query parameters if the HTTP Method is GET/DELETE + * The params dictionary is attached to the body if the HTTP Method is POST/PUT + * The HTTP Method is implicitly assumed to be GET + */ +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body + httpMethod:(NSString*)method; + +/*! + * @abstract Creates a simple GET Operation with a request URL, parameters, HTTP Method and the SSL switch + * + * @discussion + * Creates an operation with the given URL path. + * The ssl option when true changes the URL to https. + * The ssl option when false changes the URL to http. + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The params dictionary in this method gets attached to the URL as query parameters if the HTTP Method is GET/DELETE + * The params dictionary is attached to the body if the HTTP Method is POST/PUT + * The previously mentioned methods operationWithPath: and operationWithPath:params: call this internally + */ +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body + httpMethod:(NSString*)method + ssl:(BOOL) useSSL; + + +/*! + * @abstract Creates a simple GET Operation with a request URL + * + * @discussion + * Creates an operation with the given absolute URL. + * The hostname of the engine is *NOT* prefixed + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The HTTP method is implicitly assumed to be GET. + */ +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString; + +/*! + * @abstract Creates a simple GET Operation with a request URL and parameters + * + * @discussion + * Creates an operation with the given absolute URL. + * The hostname of the engine is *NOT* prefixed + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The body dictionary in this method gets attached to the URL as query parameters + * The HTTP method is implicitly assumed to be GET. + */ +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString + params:(NSDictionary*) body; + +/*! + * @abstract Creates a simple Operation with a request URL, parameters and HTTP Method + * + * @discussion + * Creates an operation with the given absolute URL. + * The hostname of the engine is *NOT* prefixed + * The default headers you specified in your MKNetworkEngine subclass gets added to the headers + * The params dictionary in this method gets attached to the URL as query parameters if the HTTP Method is GET/DELETE + * The params dictionary is attached to the body if the HTTP Method is POST/PUT + * This method can be over-ridden by subclasses to tweak the operation creation mechanism. + * You would typically over-ride this method to create a subclass of MKNetworkOperation (if you have one). After you create it, you should call [super prepareHeaders:operation] to attach any custom headers from super class. + * @seealso + * prepareHeaders: + */ +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString + params:(NSDictionary*) body + httpMethod:(NSString*) method; + +/*! + * @abstract adds the custom default headers + * + * @discussion + * This method adds custom default headers to the factory created MKNetworkOperation. + * This method can be over-ridden by subclasses to add more default headers if necessary. + * You would typically over-ride this method if you have over-ridden operationWithURLString:params:httpMethod:. + * @seealso + * operationWithURLString:params:httpMethod: + */ + +-(void) prepareHeaders:(MKNetworkOperation*) operation; +/*! + * @abstract Handy helper method for fetching images asynchronously in the background + * + * @discussion + * Creates an operation with the given image URL. + * The hostname of the engine is *NOT* prefixed. + * The image is returned to the caller via MKNKImageBlock callback block. This image is resized as per the size and decompressed in background. + * @seealso + * imageAtUrl:onCompletion: + */ +- (MKNetworkOperation*)imageAtURL:(NSURL *)url size:(CGSize) size onCompletion:(MKNKImageBlock) imageFetchedBlock; +/*! + * @abstract Handy helper method for fetching images + * + * @discussion + * Creates an operation with the given image URL. + * The hostname of the engine is *NOT* prefixed. + * The image is returned to the caller via MKNKImageBlock callback block. + */ +- (MKNetworkOperation*)imageAtURL:(NSURL *)url onCompletion:(MKNKImageBlock) imageFetchedBlock; +/*! + * @abstract Enqueues your operation into the shared queue + * + * @discussion + * The operation you created is enqueued to the shared queue. If the response for this operation was previously cached, the cached data will be returned. + * @seealso + * enqueueOperation:forceReload: + */ +-(void) enqueueOperation:(MKNetworkOperation*) request; + +/*! + * @abstract Enqueues your operation into the shared queue. + * + * @discussion + * The operation you created is enqueued to the shared queue. + * When forceReload is NO, this method behaves like enqueueOperation: + * When forceReload is YES, No cached data will be returned even if cached data is available. + * @seealso + * enqueueOperation: + */ +-(void) enqueueOperation:(MKNetworkOperation*) operation forceReload:(BOOL) forceReload; + +/*! + * @abstract HostName of the engine + * @property readonlyHostName + * + * @discussion + * Returns the host name of the engine + * This property is readonly cannot be updated. + * You normally initialize an engine with its hostname using the initWithHostName:customHeaders: method + */ +@property (readonly, strong, nonatomic) NSString *readonlyHostName; + +/*! + * @abstract Port Number that should be used by URL creating factory methods + * @property portNumber + * + * @discussion + * Set a port number for your engine if your remote URL mandates it. + * This property is optional and you DON'T have to specify the default HTTP port 80 + */ +@property (assign, nonatomic) int portNumber; + +/*! + * @abstract Sets an api path if it is different from root URL + * @property apiPath + * + * @discussion + * You can use this method to set a custom path to the API location if your server's API path is different from root (/) + * This property is optional + */ +@property (strong, nonatomic) NSString* apiPath; + +/*! + * @abstract Handler that you implement to monitor reachability changes + * @property reachabilityChangedHandler + * + * @discussion + * The framework calls this handler whenever the reachability of the host changes. + * The default implementation freezes the queued operations and stops network activity + * You normally don't have to implement this unless you need to show a HUD notifying the user of connectivity loss + */ +@property (copy, nonatomic) void (^reachabilityChangedHandler)(NetworkStatus ns); + +/*! + * @abstract Registers an associated operation subclass + * + * @discussion + * When you override both MKNetworkEngine and MKNetworkOperation, you might want the engine's factory method + * to prepare operations of your MKNetworkOperation subclass. To create your own MKNetworkOperation subclasses from the factory method, you can register your MKNetworkOperation subclass using this method. + * This method is optional. If you don't use, factory methods in MKNetworkEngine creates MKNetworkOperation objects. + */ +-(void) registerOperationSubclass:(Class) aClass; +/*! + * @abstract Cache Directory Name + * + * @discussion + * This method can be over-ridden by subclasses to provide an alternative cache directory + * The default directory (MKNetworkKitCache) within the NSCaches directory will be used otherwise + * Overriding this method is optional + */ +-(NSString*) cacheDirectoryName; + +/*! + * @abstract Cache Directory In Memory Cost + * + * @discussion + * This method can be over-ridden by subclasses to provide an alternative in memory cache size. + * By default, MKNetworkKit caches 10 recent requests in memory + * The default size is 10 + * Overriding this method is optional + */ +-(int) cacheMemoryCost; + +/*! + * @abstract Enable Caching + * + * @discussion + * This method should be called explicitly to enable caching for this engine. + * By default, MKNetworkKit doens't cache your requests. + * The cacheMemoryCost and cacheDirectoryName will be used when you turn caching on using this method. + */ +-(void) useCache; + +/*! + * @abstract Empties previously cached data + * + * @discussion + * This method is a handy helper that you can use to clear cached data. + * By default, MKNetworkKit doens't cache your requests. Use this only when you enabled caching + * @seealso + * useCache + */ +-(void) emptyCache; + +/*! + * @abstract Checks current reachable status + * + * @discussion + * This method is a handy helper that you can use to check for network reachability. + */ +-(BOOL) isReachable; + +@end diff --git a/PSCollectionViewDemo/MKNetworkEngine.m b/PSCollectionViewDemo/MKNetworkEngine.m new file mode 100644 index 0000000..93bfb2a --- /dev/null +++ b/PSCollectionViewDemo/MKNetworkEngine.m @@ -0,0 +1,689 @@ +// +// MKNetworkEngine.m +// MKNetworkKit +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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 "MKNetworkKit.h" +#define kFreezableOperationExtension @"mknetworkkitfrozenoperation" + +#ifdef __OBJC_GC__ +#error MKNetworkKit does not support Objective-C Garbage Collection +#endif + +#if TARGET_OS_IPHONE +#ifndef __IPHONE_5_0 +#error MKNetworkKit does not support iOS 4 and lower +#endif +#endif + +#if ! __has_feature(objc_arc) +#error MKNetworkKit is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +@interface MKNetworkEngine (/*Private Methods*/) + +@property (strong, nonatomic) NSString *hostName; +@property (strong, nonatomic) Reachability *reachability; +@property (strong, nonatomic) NSDictionary *customHeaders; +@property (assign, nonatomic) Class customOperationSubclass; + +@property (nonatomic, strong) NSMutableDictionary *memoryCache; +@property (nonatomic, strong) NSMutableArray *memoryCacheKeys; +@property (nonatomic, strong) NSMutableDictionary *cacheInvalidationParams; +@property (assign, nonatomic) dispatch_queue_t backgroundCacheQueue; + +-(void) saveCache; +-(void) saveCacheData:(NSData*) data forKey:(NSString*) cacheDataKey; + +-(void) freezeOperations; +-(void) checkAndRestoreFrozenOperations; + +-(BOOL) isCacheEnabled; +@end + +static NSOperationQueue *_sharedNetworkQueue; + +@implementation MKNetworkEngine + +// Network Queue is a shared singleton object. +// no matter how many instances of MKNetworkEngine is created, there is one and only one network queue +// In theory an app should contain as many network engines as the number of domains it talks to + +#pragma mark - +#pragma mark Initialization + ++(void) initialize { + + if(!_sharedNetworkQueue) { + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedNetworkQueue = [[NSOperationQueue alloc] init]; + [_sharedNetworkQueue addObserver:[self self] forKeyPath:@"operationCount" options:0 context:NULL]; + [_sharedNetworkQueue setMaxConcurrentOperationCount:6]; + + }); + } +} + +- (id) init { + + return [self initWithHostName:nil]; +} + +- (id) initWithHostName:(NSString*) hostName { + + return [self initWithHostName:hostName apiPath:nil customHeaderFields:nil]; +} + +- (id) initWithHostName:(NSString*) hostName apiPath:(NSString*) apiPath customHeaderFields:(NSDictionary*) headers { + + if((self = [super init])) { + + self.apiPath = apiPath; + self.backgroundCacheQueue = dispatch_queue_create("com.mknetworkkit.cachequeue", DISPATCH_QUEUE_SERIAL); + + if(hostName) { + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(reachabilityChanged:) + name:kReachabilityChangedNotification + object:nil]; + + self.hostName = hostName; + self.reachability = [Reachability reachabilityWithHostname:self.hostName]; + [self.reachability startNotifier]; + } + + if(headers[@"User-Agent"] == nil) { + + NSMutableDictionary *newHeadersDict = [headers mutableCopy]; + NSString *userAgentString = [NSString stringWithFormat:@"%@/%@", + [[NSBundle mainBundle] infoDictionary][(NSString *)kCFBundleNameKey], + [[NSBundle mainBundle] infoDictionary][(NSString *)kCFBundleVersionKey]]; + newHeadersDict[@"User-Agent"] = userAgentString; + self.customHeaders = newHeadersDict; + } else { + self.customHeaders = headers; + } + + self.customOperationSubclass = [MKNetworkOperation class]; + } + + return self; +} + +- (id) initWithHostName:(NSString*) hostName customHeaderFields:(NSDictionary*) headers { + + return [self initWithHostName:hostName apiPath:nil customHeaderFields:headers]; +} + +#pragma mark - +#pragma mark Memory Mangement + +-(void) dealloc { + + [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil]; +#if TARGET_OS_IPHONE + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil]; +#elif TARGET_OS_MAC + [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillHideNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillResignActiveNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:nil]; +#endif + +} + ++(void) dealloc { + + [_sharedNetworkQueue removeObserver:[self self] forKeyPath:@"operationCount"]; +} + +#pragma mark - +#pragma mark KVO for network Queue + ++ (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object + change:(NSDictionary *)change context:(void *)context +{ + if (object == _sharedNetworkQueue && [keyPath isEqualToString:@"operationCount"]) { + + [[NSNotificationCenter defaultCenter] postNotificationName:kMKNetworkEngineOperationCountChanged + object:[NSNumber numberWithInteger:[_sharedNetworkQueue operationCount]]]; +#if TARGET_OS_IPHONE + [UIApplication sharedApplication].networkActivityIndicatorVisible = + ([_sharedNetworkQueue.operations count] > 0); +#endif + } + else { + [super observeValueForKeyPath:keyPath ofObject:object + change:change context:context]; + } +} + +#pragma mark - +#pragma mark Reachability related + +-(void) reachabilityChanged:(NSNotification*) notification +{ + if([self.reachability currentReachabilityStatus] == ReachableViaWiFi) + { + DLog(@"Server [%@] is reachable via Wifi", self.hostName); + [_sharedNetworkQueue setMaxConcurrentOperationCount:6]; + + [self checkAndRestoreFrozenOperations]; + } + else if([self.reachability currentReachabilityStatus] == ReachableViaWWAN) + { + DLog(@"Server [%@] is reachable only via cellular data", self.hostName); + [_sharedNetworkQueue setMaxConcurrentOperationCount:2]; + [self checkAndRestoreFrozenOperations]; + } + else if([self.reachability currentReachabilityStatus] == NotReachable) + { + DLog(@"Server [%@] is not reachable", self.hostName); + [self freezeOperations]; + } + + if(self.reachabilityChangedHandler) { + self.reachabilityChangedHandler([self.reachability currentReachabilityStatus]); + } +} + +#pragma mark Freezing operations (Called when network connectivity fails) +-(void) freezeOperations { + + if(![self isCacheEnabled]) return; + + for(MKNetworkOperation *operation in _sharedNetworkQueue.operations) { + + // freeze only freeable operations. + if(![operation freezable]) continue; + + if(!self.hostName) return; + + // freeze only operations that belong to this server + if([[operation url] rangeOfString:self.hostName].location == NSNotFound) continue; + + NSString *archivePath = [[[self cacheDirectoryName] stringByAppendingPathComponent:[operation uniqueIdentifier]] + stringByAppendingPathExtension:kFreezableOperationExtension]; + [NSKeyedArchiver archiveRootObject:operation toFile:archivePath]; + [operation cancel]; + } + +} + +-(void) checkAndRestoreFrozenOperations { + + if(![self isCacheEnabled]) return; + + NSError *error = nil; + NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self cacheDirectoryName] error:&error]; + if(error) + DLog(@"%@", error); + + NSArray *pendingOperations = [files filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { + + NSString *thisFile = (NSString*) evaluatedObject; + return ([thisFile rangeOfString:kFreezableOperationExtension].location != NSNotFound); + }]]; + + for(NSString *pendingOperationFile in pendingOperations) { + + NSString *archivePath = [[self cacheDirectoryName] stringByAppendingPathComponent:pendingOperationFile]; + MKNetworkOperation *pendingOperation = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath]; + [self enqueueOperation:pendingOperation]; + NSError *error = nil; + [[NSFileManager defaultManager] removeItemAtPath:archivePath error:&error]; + if(error) + DLog(@"%@", error); + } +} + +-(NSString*) readonlyHostName { + + return [_hostName copy]; +} + +-(BOOL) isReachable { + + return ([self.reachability currentReachabilityStatus] != NotReachable); +} + +#pragma mark - +#pragma mark Create methods + +-(void) registerOperationSubclass:(Class) aClass { + + self.customOperationSubclass = aClass; +} + +-(MKNetworkOperation*) operationWithPath:(NSString*) path { + + return [self operationWithPath:path params:nil]; +} + +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body { + + return [self operationWithPath:path + params:body + httpMethod:@"GET"]; +} + +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body + httpMethod:(NSString*)method { + + return [self operationWithPath:path params:body httpMethod:method ssl:NO]; +} + +-(MKNetworkOperation*) operationWithPath:(NSString*) path + params:(NSDictionary*) body + httpMethod:(NSString*)method + ssl:(BOOL) useSSL { + + if(self.hostName == nil) { + + DLog(@"Hostname is nil, use operationWithURLString: method to create absolute URL operations"); + return nil; + } + + NSMutableString *urlString = [NSMutableString stringWithFormat:@"%@://%@", useSSL ? @"https" : @"http", self.hostName]; + + if(self.portNumber != 0) + [urlString appendFormat:@":%d", self.portNumber]; + + if(self.apiPath) + [urlString appendFormat:@"/%@", self.apiPath]; + + [urlString appendFormat:@"/%@", path]; + + return [self operationWithURLString:urlString params:body httpMethod:method]; +} + +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString { + + return [self operationWithURLString:urlString params:nil httpMethod:@"GET"]; +} + +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString + params:(NSDictionary*) body { + + return [self operationWithURLString:urlString params:body httpMethod:@"GET"]; +} + + +-(MKNetworkOperation*) operationWithURLString:(NSString*) urlString + params:(NSDictionary*) body + httpMethod:(NSString*)method { + + MKNetworkOperation *operation = [[self.customOperationSubclass alloc] initWithURLString:urlString params:body httpMethod:method]; + + [self prepareHeaders:operation]; + return operation; +} + +-(void) prepareHeaders:(MKNetworkOperation*) operation { + + [operation addHeaders:self.customHeaders]; +} + +-(NSData*) cachedDataForOperation:(MKNetworkOperation*) operation { + + NSData *cachedData = (self.memoryCache)[[operation uniqueIdentifier]]; + if(cachedData) return cachedData; + + NSString *filePath = [[self cacheDirectoryName] stringByAppendingPathComponent:[operation uniqueIdentifier]]; + + if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + + cachedData = [NSData dataWithContentsOfFile:filePath]; + [self saveCacheData:cachedData forKey:[operation uniqueIdentifier]]; // bring it back to the in-memory cache + return cachedData; + } + + return nil; +} + +-(void) enqueueOperation:(MKNetworkOperation*) operation { + + [self enqueueOperation:operation forceReload:NO]; +} + +-(void) enqueueOperation:(MKNetworkOperation*) operation forceReload:(BOOL) forceReload { + + NSParameterAssert(operation != nil); + // Grab on to the current queue (We need it later) + dispatch_queue_t originalQueue = dispatch_get_current_queue(); +#if DO_GCD_RETAIN_RELEASE + dispatch_retain(originalQueue); +#endif + // Jump off the main thread, mainly for disk cache reading purposes + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [operation setCacheHandler:^(MKNetworkOperation* completedCacheableOperation) { + + // if this is not called, the request would have been a non cacheable request + //completedCacheableOperation.cacheHeaders; + NSString *uniqueId = [completedCacheableOperation uniqueIdentifier]; + [self saveCacheData:[completedCacheableOperation responseData] + forKey:uniqueId]; + + (self.cacheInvalidationParams)[uniqueId] = completedCacheableOperation.cacheHeaders; + }]; + + __block double expiryTimeInSeconds = 0.0f; + + if([operation isCacheable]) { + + if(!forceReload) { + NSData *cachedData = [self cachedDataForOperation:operation]; + if(cachedData) { + dispatch_async(originalQueue, ^{ + // Jump back to the original thread here since setCachedData updates the main thread + [operation setCachedData:cachedData]; + }); + + + NSString *uniqueId = [operation uniqueIdentifier]; + NSMutableDictionary *savedCacheHeaders = (self.cacheInvalidationParams)[uniqueId]; + // there is a cached version. + // this means, the current operation is a "GET" + if(savedCacheHeaders) { + NSString *expiresOn = savedCacheHeaders[@"Expires"]; + + dispatch_sync(originalQueue, ^{ + NSDate *expiresOnDate = [NSDate dateFromRFC1123:expiresOn]; + expiryTimeInSeconds = [expiresOnDate timeIntervalSinceNow]; + }); + + [operation updateOperationBasedOnPreviousHeaders:savedCacheHeaders]; + } + } + } + + dispatch_async(originalQueue, ^{ + + NSUInteger index = [_sharedNetworkQueue.operations indexOfObject:operation]; + if(index == NSNotFound) { + + if(expiryTimeInSeconds <= 0) + [_sharedNetworkQueue addOperation:operation]; + else if(forceReload) + [_sharedNetworkQueue addOperation:operation]; + // else don't do anything + } + else { + // This operation is already being processed + MKNetworkOperation *queuedOperation = (MKNetworkOperation*) (_sharedNetworkQueue.operations)[index]; + [queuedOperation updateHandlersFromOperation:operation]; + } + + + }); + } else { + + [_sharedNetworkQueue addOperation:operation]; + } + + if([self.reachability currentReachabilityStatus] == NotReachable) + [self freezeOperations]; +#if DO_GCD_RETAIN_RELEASE + dispatch_release(originalQueue); +#endif + }); +} + +- (MKNetworkOperation*)imageAtURL:(NSURL *)url size:(CGSize) size onCompletion:(MKNKImageBlock) imageFetchedBlock { + +#ifdef DEBUG + // I could enable caching here, but that hits performance and inturn affects table view scrolling + // if imageAtURL is called for loading thumbnails. + if(![self isCacheEnabled]) DLog(@"imageAtURL:size:onCompletion: requires caching to be enabled.") +#endif + + if (url == nil) { + return nil; + } + + MKNetworkOperation *op = [self operationWithURLString:[url absoluteString]]; + + [op addCompletionHandler:^(MKNetworkOperation *completedOperation) { + [completedOperation decompressedResponseImageOfSize:size + completionHandler:^(UIImage *decompressedImage) { + + imageFetchedBlock(decompressedImage, + url, + [completedOperation isCachedResponse]); + }]; + } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) { + + DLog(@"%@", error); + }]; + + [op onNotModified:^{ + + DLog(@"Not modified"); + }]; + + [self enqueueOperation:op]; + + return op; +} + +- (MKNetworkOperation*)imageAtURL:(NSURL *)url onCompletion:(MKNKImageBlock) imageFetchedBlock +{ +#ifdef DEBUG + // I could enable caching here, but that hits performance and inturn affects table view scrolling + // if imageAtURL is called for loading thumbnails. + if(![self isCacheEnabled]) DLog(@"imageAtURL:onCompletion: requires caching to be enabled.") +#endif + + if (url == nil) { + return nil; + } + + MKNetworkOperation *op = [self operationWithURLString:[url absoluteString]]; + + [op addCompletionHandler:^(MKNetworkOperation *completedOperation) { + + imageFetchedBlock([completedOperation responseImage], + url, + [completedOperation isCachedResponse]); + + } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) { + + DLog(@"%@", error); + }]; + + [self enqueueOperation:op]; + + return op; +} + +#pragma mark - +#pragma mark Cache related + +-(NSString*) cacheDirectoryName { + + static NSString *cacheDirectoryName = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = paths[0]; + cacheDirectoryName = [documentsDirectory stringByAppendingPathComponent:MKNETWORKCACHE_DEFAULT_DIRECTORY]; + }); + + return cacheDirectoryName; +} + +-(int) cacheMemoryCost { + + return MKNETWORKCACHE_DEFAULT_COST; +} + +-(void) saveCache { + + for(NSString *cacheKey in [self.memoryCache allKeys]) + { + NSString *filePath = [[self cacheDirectoryName] stringByAppendingPathComponent:cacheKey]; + if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + + NSError *error = nil; + [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; + ELog(error); + } + + [(self.memoryCache)[cacheKey] writeToFile:filePath atomically:YES]; + } + + [self.memoryCache removeAllObjects]; + [self.memoryCacheKeys removeAllObjects]; + + NSString *cacheInvalidationPlistFilePath = [[self cacheDirectoryName] stringByAppendingPathExtension:@"plist"]; + [self.cacheInvalidationParams writeToFile:cacheInvalidationPlistFilePath atomically:YES]; +} + +-(void) saveCacheData:(NSData*) data forKey:(NSString*) cacheDataKey +{ + dispatch_async(self.backgroundCacheQueue, ^{ + + (self.memoryCache)[cacheDataKey] = data; + + NSUInteger index = [self.memoryCacheKeys indexOfObject:cacheDataKey]; + if(index != NSNotFound) + [self.memoryCacheKeys removeObjectAtIndex:index]; + + [self.memoryCacheKeys insertObject:cacheDataKey atIndex:0]; // remove it and insert it at start + + if([self.memoryCacheKeys count] >= [self cacheMemoryCost]) + { + NSString *lastKey = [self.memoryCacheKeys lastObject]; + NSData *data = (self.memoryCache)[lastKey]; + NSString *filePath = [[self cacheDirectoryName] stringByAppendingPathComponent:lastKey]; + + if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + + NSError *error = nil; + [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; + ELog(error); + } + [data writeToFile:filePath atomically:YES]; + + [self.memoryCacheKeys removeLastObject]; + [self.memoryCache removeObjectForKey:lastKey]; + } + }); +} + +/* + - (BOOL) dataOldness:(NSString*) imagePath + { + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:imagePath error:nil]; + NSDate *creationDate = [attributes valueForKey:NSFileCreationDate]; + + return abs([creationDate timeIntervalSinceNow]); + }*/ + +-(BOOL) isCacheEnabled { + + BOOL isDir = NO; + BOOL isCachingEnabled = [[NSFileManager defaultManager] fileExistsAtPath:[self cacheDirectoryName] isDirectory:&isDir]; + return isCachingEnabled; +} + +-(void) useCache { + + self.memoryCache = [NSMutableDictionary dictionaryWithCapacity:[self cacheMemoryCost]]; + self.memoryCacheKeys = [NSMutableArray arrayWithCapacity:[self cacheMemoryCost]]; + self.cacheInvalidationParams = [NSMutableDictionary dictionary]; + + NSString *cacheDirectory = [self cacheDirectoryName]; + BOOL isDirectory = YES; + BOOL folderExists = [[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory isDirectory:&isDirectory] && isDirectory; + + if (!folderExists) + { + NSError *error = nil; + [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&error]; + } + + NSString *cacheInvalidationPlistFilePath = [cacheDirectory stringByAppendingPathExtension:@"plist"]; + + BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:cacheInvalidationPlistFilePath]; + + if (fileExists) + { + self.cacheInvalidationParams = [NSMutableDictionary dictionaryWithContentsOfFile:cacheInvalidationPlistFilePath]; + } + +#if TARGET_OS_IPHONE + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:UIApplicationWillTerminateNotification + object:nil]; + +#elif TARGET_OS_MAC + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:NSApplicationWillHideNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:NSApplicationWillResignActiveNotification + object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveCache) + name:NSApplicationWillTerminateNotification + object:nil]; + +#endif + + +} + +-(void) emptyCache { + + [self saveCache]; // ensures that invalidation params are written to disk properly + NSError *error = nil; + NSArray *directoryContents = [[NSFileManager defaultManager] + contentsOfDirectoryAtPath:[self cacheDirectoryName] error:&error]; + if(error) DLog(@"%@", error); + + error = nil; + for(NSString *fileName in directoryContents) { + + NSString *path = [[self cacheDirectoryName] stringByAppendingPathComponent:fileName]; + [[NSFileManager defaultManager] removeItemAtPath:path error:&error]; + if(error) DLog(@"%@", error); + } + + error = nil; + NSString *cacheInvalidationPlistFilePath = [[self cacheDirectoryName] stringByAppendingPathExtension:@"plist"]; + [[NSFileManager defaultManager] removeItemAtPath:cacheInvalidationPlistFilePath error:&error]; + if(error) DLog(@"%@", error); +} + +@end diff --git a/PSCollectionViewDemo/MKNetworkKit.h b/PSCollectionViewDemo/MKNetworkKit.h new file mode 100644 index 0000000..d94b66f --- /dev/null +++ b/PSCollectionViewDemo/MKNetworkKit.h @@ -0,0 +1,92 @@ +// +// MKNetworkKit.h +// MKNetworkKit +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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. + +#ifndef MKNetworkKit_MKNetworkKit_h +#define MKNetworkKit_MKNetworkKit_h + +#ifndef __IPHONE_4_0 +#error "MKNetworkKit uses features only available in iOS SDK 4.0 and later." +#endif + +#if TARGET_OS_IPHONE +#import +#import +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 +#define DO_GCD_RETAIN_RELEASE 0 +#else +#define DO_GCD_RETAIN_RELEASE 1 +#endif +#elif TARGET_OS_MAC +#import +#import +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 +#define DO_GCD_RETAIN_RELEASE 0 +#else +#define DO_GCD_RETAIN_RELEASE 1 +#endif +#endif + +#ifdef DEBUG +# define DLog(fmt, ...) {NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);} +# define ELog(err) {if(err) DLog(@"%@", err)} +#else +# define DLog(...) +# define ELog(err) +#endif + +// ALog always displays output regardless of the DEBUG setting +#define ALog(fmt, ...) {NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);}; + +#import "Categories/NSString+MKNetworkKitAdditions.h" +#import "Categories/NSDictionary+RequestEncoding.h" +#import "Categories/NSDate+RFC1123.h" +#import "Categories/NSData+Base64.h" + +#if TARGET_OS_IPHONE +#import "Categories/UIAlertView+MKNetworkKitAdditions.h" +#elif TARGET_OS_MAC +#import "Categories/NSAlert+MKNetworkKitAdditions.h" +#endif + +#import "Reachability/Reachability.h" + +#import "MKNetworkOperation.h" +#import "MKNetworkEngine.h" + +#define kMKNetworkEngineOperationCountChanged @"kMKNetworkEngineOperationCountChanged" +#define MKNETWORKCACHE_DEFAULT_COST 10 +#define MKNETWORKCACHE_DEFAULT_DIRECTORY @"MKNetworkKitCache" +#define kMKNetworkKitDefaultCacheDuration 60 // 1 minute +#define kMKNetworkKitDefaultImageHeadRequestDuration 3600*24*1 // 1 day (HEAD requests with eTag are sent only after expiry of this. Not that these are not RFC compliant, but needed for performance tuning) +#define kMKNetworkKitDefaultImageCacheDuration 3600*24*7 // 1 day + +// if your server takes longer than 30 seconds to provide real data, +// you should hire a better server developer. +// on iOS (or any mobile device), 30 seconds is already considered high. + +#define kMKNetworkKitRequestTimeOutInSeconds 30 +#endif + + diff --git a/PSCollectionViewDemo/MKNetworkOperation.h b/PSCollectionViewDemo/MKNetworkOperation.h new file mode 100644 index 0000000..050be6f --- /dev/null +++ b/PSCollectionViewDemo/MKNetworkOperation.h @@ -0,0 +1,575 @@ +// +// MKNetwork.h +// MKNetworkKit +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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. + +@class MKNetworkOperation; + +typedef enum { + MKNetworkOperationStateReady = 1, + MKNetworkOperationStateExecuting = 2, + MKNetworkOperationStateFinished = 3 +} MKNetworkOperationState; + +typedef void (^MKNKVoidBlock)(void); +typedef void (^MKNKProgressBlock)(double progress); +typedef void (^MKNKResponseBlock)(MKNetworkOperation* completedOperation); +#if TARGET_OS_IPHONE +typedef void (^MKNKImageBlock) (UIImage* fetchedImage, NSURL* url, BOOL isInCache); +#elif TARGET_OS_MAC +typedef void (^MKNKImageBlock) (NSImage* fetchedImage, NSURL* url, BOOL isInCache); +#endif +typedef void (^MKNKResponseErrorBlock)(MKNetworkOperation* completedOperation, NSError* error); +typedef void (^MKNKErrorBlock)(NSError* error); + +typedef void (^MKNKAuthBlock)(NSURLAuthenticationChallenge* challenge); + +typedef NSString* (^MKNKEncodingBlock) (NSDictionary* postDataDict); + +typedef enum { + + MKNKPostDataEncodingTypeURL = 0, // default + MKNKPostDataEncodingTypeJSON, + MKNKPostDataEncodingTypePlist, + MKNKPostDataEncodingTypeCustom +} MKNKPostDataEncodingType; +/*! + @header MKNetworkOperation.h + @abstract Represents a single unique network operation. + */ + +/*! + * @class MKNetworkOperation + * @abstract Represents a single unique network operation. + * + * @discussion + * You normally create an instance of this class using the methods exposed by MKNetworkEngine + * Created operations are enqueued into the shared queue on MKNetworkEngine + * MKNetworkOperation encapsulates both request and response + * Printing a MKNetworkOperation prints out a cURL command that can be copied and pasted directly on terminal + * Freezable operations are serialized when network connectivity is lost and performed when connection is restored + */ +@interface MKNetworkOperation : NSOperation { + +@private + int _state; + BOOL _freezable; + MKNKPostDataEncodingType _postDataEncoding; +} + +/*! + * @abstract Request URL Property + * @property url + * + * @discussion + * Returns the operation's URL + * This property is readonly cannot be updated. + * To create an operation with a specific URL, use the operationWithURLString:params:httpMethod: + */ +@property (nonatomic, readonly) NSString *url; + +/*! + * @abstract The internal request object + * @property readonlyRequest + * + * @discussion + * Returns the operation's actual request object + * This property is readonly cannot be modified. + * To create an operation with a new request, use the operationWithURLString:params:httpMethod: + */ +@property (nonatomic, strong, readonly) NSURLRequest *readonlyRequest; + +/*! + * @abstract The internal HTTP Response Object + * @property readonlyResponse + * + * @discussion + * Returns the operation's actual response object + * This property is readonly cannot be updated. + */ +@property (nonatomic, strong, readonly) NSHTTPURLResponse *readonlyResponse; + +/*! + * @abstract The internal HTTP Post data values + * @property readonlyPostDictionary + * + * @discussion + * Returns the operation's post data dictionary + * This property is readonly cannot be updated. + * Rather, updating this post dictionary doesn't have any effect on the MKNetworkOperation. + * Use the addHeaders method to add post data parameters to the operation. + * + * @seealso + * addHeaders: + */ +@property (nonatomic, strong, readonly) NSDictionary *readonlyPostDictionary; + +/*! + * @abstract The internal request object's method type + * @property HTTPMethod + * + * @discussion + * Returns the operation's method type + * This property is readonly cannot be modified. + * To create an operation with a new method type, use the operationWithURLString:params:httpMethod: + */ +@property (nonatomic, strong, readonly) NSString *HTTPMethod; + +/*! + * @abstract The internal response object's status code + * @property HTTPStatusCode + * + * @discussion + * Returns the operation's response's status code. + * Returns 0 when the operation has not yet started and the response is not available. + * This property is readonly cannot be modified. + */ +@property (nonatomic, assign, readonly) NSInteger HTTPStatusCode; + +/*! + * @abstract Post Data Encoding Type Property + * @property postDataEncoding + * + * @discussion + * Specifies which type of encoding should be used to encode post data. + * MKNKPostDataEncodingTypeURL is the default which defaults to application/x-www-form-urlencoded + * MKNKPostDataEncodingTypeJSON uses JSON encoding. + * JSON Encoding is supported only in iOS 5 or Mac OS X 10.7 and above. + * On older operating systems, JSON Encoding reverts back to URL Encoding + * You can use the postDataEncodingHandler to provide a custom postDataEncoding + * For example, JSON encoding using a third party library. + * + * @seealso + * setCustomPostDataEncodingHandler:forType: + * + */ +@property (nonatomic, assign) MKNKPostDataEncodingType postDataEncoding; + +/*! + * @abstract Set a customized Post Data Encoding Handler for a given HTTP Content Type + * + * @discussion + * If you need customized post data encoding support, provide a block method here. + * This block method will be invoked only when your HTTP Method is POST or PUT + * For default URL encoding or JSON encoding, use the property postDataEncoding + * If you change the postData format, it's your responsiblity to provide a correct Content-Type. + * + * @seealso + * postDataEncoding + */ + +-(void) setCustomPostDataEncodingHandler:(MKNKEncodingBlock) postDataEncodingHandler forType:(NSString*) contentType; + +/*! + * @abstract String Encoding Property + * @property stringEncoding + * + * @discussion + * Specifies which type of encoding should be used to encode URL strings + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/*! + * @abstract Freezable request + * @property freezable + * + * @discussion + * Freezable operations are serialized when the network goes down and restored when the connectivity is up again. + * Only POST, PUT and DELETE operations are freezable. + * In short, any operation that changes the state of the server are freezable, creating a tweet, checking into a new location etc., Operations like fetching a list of tweets (think readonly GET operations) are not freezable. + * MKNetworkKit doesn't freeze (readonly) GET operations even if they are marked as freezable + */ +@property (nonatomic, assign) BOOL freezable; + +/*! + * @abstract Error object + * @property error + * + * @discussion + * If the network operation results in an error, this will hold the response error, otherwise it will be nil + */ +@property (nonatomic, readonly, strong) NSError *error; + +/*! + * @abstract Cache headers of the response + * @property cacheHeaders + * + * @discussion + * If the network operation is a GET, this dictionary will be populated with relevant cache related headers + * MKNetworkKit assumes a 7 day cache for images and 1 minute cache for all requests with no-cache set + * This property is internal to MKNetworkKit. Modifying this is not recommended and will result in unexpected behaviour + */ +@property (strong, nonatomic) NSMutableDictionary *cacheHeaders; + +/*! + * @abstract Authentication methods + * + * @discussion + * If your request needs to be authenticated, set your username and password using this method. + */ +-(void) setUsername:(NSString*) name password:(NSString*) password; + +/*! + * @abstract Authentication methods + * + * @discussion + * If your request needs to be authenticated using HTTP Basic, use this method to set your username and password. + * Calling this method with basicAuth:NO is same as calling setUserName:password: + * @seealso + * setUserName:password: + */ +-(void) setUsername:(NSString*) username password:(NSString*) password basicAuth:(BOOL) bYesOrNo; + +/*! + * @abstract Authentication methods (Client Certificate) + * @property clientCertificate + * + * @discussion + * If your request needs to be authenticated using a client certificate, set the certificate path here + */ +@property (strong, nonatomic) NSString *clientCertificate; + +/*! + * @abstract Custom authentication handler + * @property authHandler + * + * @discussion + * If your request needs to be authenticated using a custom method (like a Web page/HTML Form), add a block method here + * and process the NSURLAuthenticationChallenge + */ +@property (nonatomic, copy) MKNKAuthBlock authHandler; + +/*! + * @abstract Handler that you implement to monitor reachability changes + * @property operationStateChangedHandler + * + * @discussion + * The framework calls this handler whenever the operation state changes + */ +@property (copy, nonatomic) void (^operationStateChangedHandler)(MKNetworkOperationState newState); + +/*! + * @abstract controls persistence of authentication credentials + * @property credentialPersistence + * + * @discussion + * The default value is set to NSURLCredentialPersistenceForSession, change it to NSURLCredentialPersistenceNone to avoid caching issues (isse #35) + */ +@property (nonatomic, assign) NSURLCredentialPersistence credentialPersistence; +#if TARGET_OS_IPHONE + +/*! + * @abstract notification that has to be shown when an error occurs and the app is in background + * @property localNotification + * + * @discussion + * The default value nil. No notification is shown when an error occurs. + * To show a notification when the app is in background and the network operation running in background fails, + * set this parameter to a UILocalNotification object + */ +@property (nonatomic, strong) UILocalNotification *localNotification; +/*! + * @abstract Shows a local notification when an error occurs + * @property shouldShowLocalNotificationOnError + * + * @discussion + * The default value NO. No notification is shown when an error occurs. + * When set to YES, MKNetworkKit shows the NSError localizedDescription text as a notification when the app is in background and the network operation ended in error. + * To customize the local notification text, use the property localNotification + + * @seealso + * localNotification + */ +@property (nonatomic, assign) BOOL shouldShowLocalNotificationOnError; +#endif + +/*! + * @abstract Add additional header parameters + * + * @discussion + * If you ever need to set additional headers after creating your operation, you this method. + * You normally set default headers to the engine and they get added to every request you create. + * On specific cases where you need to set a new header parameter for just a single API call, you can use this + */ +-(void) addHeaders:(NSDictionary*) headersDictionary; + +/*! + * @abstract Sets the authorization header after prefixing it with a given auth type + * + * @discussion + * If you need to set the HTTP Authorization header, you can use this convinience method. + * This method internally calls addHeaders: + * The authType parameter is a string that you can prefix to your auth token to tell your server what kind of authentication scheme you want to use. HTTP Basic Authentication uses the string "Basic" for authType + * To use HTTP Basic Authentication, consider using the method setUsername:password:basicAuth: instead. + * + * Example + * [op setToken:@"abracadabra" forAuthType:@"Token"] will set the header value to + * "Authorization: Token abracadabra" + + * @seealso + * setUsername:password:basicAuth: + * addHeaders: + */ +-(void) setAuthorizationHeaderValue:(NSString*) token forAuthType:(NSString*) authType; + +/*! + * @abstract Attaches a file to the request + * + * @discussion + * This method lets you attach a file to the request + * The method has a side effect. It changes the HTTPMethod to "POST" regardless of what it was before. + * It also changes the post format to multipart/form-data + * The mime-type is assumed to be application/octet-stream + */ +-(void) addFile:(NSString*) filePath forKey:(NSString*) key; + +/*! + * @abstract Attaches a file to the request and allows you to specify a mime-type + * + * @discussion + * This method lets you attach a file to the request + * The method has a side effect. It changes the HTTPMethod to "POST" regardless of what it was before. + * It also changes the post format to multipart/form-data + */ +-(void) addFile:(NSString*) filePath forKey:(NSString*) key mimeType:(NSString*) mimeType; + +/*! + * @abstract Attaches a resource to the request from a NSData pointer + * + * @discussion + * This method lets you attach a NSData object to the request. The behaviour is exactly similar to addFile:forKey: + * The method has a side effect. It changes the HTTPMethod to "POST" regardless of what it was before. + * It also changes the post format to multipart/form-data + * The mime-type is assumed to be application/octet-stream + */ +-(void) addData:(NSData*) data forKey:(NSString*) key; + +/*! + * @abstract Attaches a resource to the request from a NSData pointer and allows you to specify a mime-type + * + * @discussion + * This method lets you attach a NSData object to the request. The behaviour is exactly similar to addFile:forKey:mimeType: + * The method has a side effect. It changes the HTTPMethod to "POST" regardless of what it was before. + * It also changes the post format to multipart/form-data + */ +-(void) addData:(NSData*) data forKey:(NSString*) key mimeType:(NSString*) mimeType fileName:(NSString*) fileName; + +/*! + * @abstract Block Handler for completion and error + * + * @discussion + * This method sets your completion and error blocks. If your operation's response data was previously called, + * the completion block will be called almost immediately with the cached response. You can check if the completion + * handler was invoked with a cached data or with real data by calling the isCachedResponse method. + * This method is deprecated in favour of addCompletionHandler:errorHandler: that returns the completedOperation in the error block as well. + * While I will still continue to support this method, I'll remove it completely in a future release. + + * @seealso + * isCachedResponse + * addCompletionHandler:errorHandler: + */ +-(void) onCompletion:(MKNKResponseBlock) response onError:(MKNKErrorBlock) error DEPRECATED_ATTRIBUTE; + +/*! + * @abstract adds a block Handler for completion and error + * + * @discussion + * This method sets your completion and error blocks. If your operation's response data was previously called, + * the completion block will be called almost immediately with the cached response. You can check if the completion + * handler was invoked with a cached data or with real data by calling the isCachedResponse method. + * + * @seealso + * onCompletion:onError: + */ +-(void) addCompletionHandler:(MKNKResponseBlock) response errorHandler:(MKNKResponseErrorBlock) error; + +/*! + * @abstract Block Handler for tracking 304 not modified state + * + * @discussion + * This method will be called if the server sends a 304 HTTP status for your request. + * + */ +-(void) onNotModified:(MKNKVoidBlock) notModifiedBlock; + +/*! + * @abstract Block Handler for tracking upload progress + * + * @discussion + * This method can be used to update your progress bars when an upload is in progress. + * The value range of the progress is 0 to 1. + * + */ +-(void) onUploadProgressChanged:(MKNKProgressBlock) uploadProgressBlock; + +/*! + * @abstract Block Handler for tracking download progress + * + * @discussion + * This method can be used to update your progress bars when a download is in progress. + * The value range of the progress is 0 to 1. + * + */ +-(void) onDownloadProgressChanged:(MKNKProgressBlock) downloadProgressBlock; + +/*! + * @abstract Uploads a resource from a stream + * + * @discussion + * This method can be used to upload a resource for a post body directly from a stream. + * + */ +-(void) setUploadStream:(NSInputStream*) inputStream; + +/*! + * @abstract Downloads a resource directly to a file or any output stream + * + * @discussion + * This method can be used to download a resource directly to a stream (It's normally a file in most cases). + * Calling this method multiple times adds new streams to the same operation. + * A stream cannot be removed after it is added. + * + */ +-(void) addDownloadStream:(NSOutputStream*) outputStream; + +/*! + * @abstract Helper method to check if the response is from cache + * + * @discussion + * This method should be used to check if your response is cached. + * When you enable caching on MKNetworkEngine, your completionHandler will be called with cached data first and then + * with real data, later after fetching. In your handler, you can call this method to check if it is from cache or not + * + */ +-(BOOL) isCachedResponse; + +/*! + * @abstract Helper method to retrieve the contents + * + * @discussion + * This method is used for accessing the downloaded data. If the operation is still in progress, the method returns nil instead of partial data. To access partial data, use a downloadStream. + * + * @seealso + * addDownloadStream: + */ +-(NSData*) responseData; + +/*! + * @abstract Helper method to retrieve the contents as a NSString + * + * @discussion + * This method is used for accessing the downloaded data. If the operation is still in progress, the method returns nil instead of partial data. To access partial data, use a downloadStream. The method also converts the responseData to a NSString using the stringEncoding specified in the operation + * + * @seealso + * addDownloadStream: + * stringEncoding + */ +-(NSString*)responseString; + +/*! + * @abstract Helper method to print the request as a cURL command + * + * @discussion + * This method is used for displaying the request you created as a cURL command + * + */ +-(NSString*) curlCommandLineString; + +/*! + * @abstract Helper method to retrieve the contents as a NSString encoded using a specific string encoding + * + * @discussion + * This method is used for accessing the downloaded data. If the operation is still in progress, the method returns nil instead of partial data. To access partial data, use a downloadStream. The method also converts the responseData to a NSString using the stringEncoding specified in the parameter + * + * @seealso + * addDownloadStream: + * stringEncoding + */ +-(NSString*) responseStringWithEncoding:(NSStringEncoding) encoding; + +/*! + * @abstract Helper method to retrieve the contents as a UIImage + * + * @discussion + * This method is used for accessing the downloaded data as a UIImage. If the operation is still in progress, the method returns nil instead of a partial image. To access partial data, use a downloadStream. If the response is not a valid image, this method returns nil. This method doesn't obey the response mime type property. If the server response with a proper image data but set the mime type incorrectly, this method will still be able access the response as an image. + * + * @seealso + * addDownloadStream: + */ +#if TARGET_OS_IPHONE +-(UIImage*) responseImage; +-(void) decompressedResponseImageOfSize:(CGSize) size completionHandler:(void (^)(UIImage *decompressedImage)) imageDecompressionHandler; +#elif TARGET_OS_MAC +-(NSImage*) responseImage; +-(NSXMLDocument*) responseXML; +#endif + +/*! + * @abstract Helper method to retrieve the contents as a NSDictionary or NSArray depending on the JSON contents + * + * @discussion + * This method is used for accessing the downloaded data as a NSDictionary or an NSArray. If the operation is still in progress, the method returns nil. If the response is not a valid JSON, this method returns nil. + * + * @availability + * iOS 5 and above or Mac OS 10.7 and above + */ +-(id) responseJSON; + +/*! + * @abstract Overridable custom method where you can add your custom business logic error handling + * + * @discussion + * This optional method can be overridden to do custom error handling. Be sure to call [super operationSucceeded] at the last. + * For example, a valid HTTP response (200) like "Item not found in database" might have a custom business error code + * You can override this method and called [super failWithError:customError]; to notify that HTTP call was successful but the method + * ended as a failed call + * + */ +-(void) operationSucceeded; + +/*! + * @abstract Overridable custom method where you can add your custom business logic error handling + * + * @discussion + * This optional method can be overridden to do custom error handling. Be sure to call [super operationSucceeded] at the last. + * For example, a invalid HTTP response (401) like "Unauthorized" might be a valid case in your app. + * You can override this method and called [super operationSucceeded]; to notify that HTTP call failed but the method + * ended as a success call. For example, Facebook login failed, but to your business implementation, it's not a problem as you + * are going to try alternative login mechanisms. + * + */ +-(void) operationFailedWithError:(NSError*) error; + +// internal methods called by MKNetworkEngine only. +// Don't touch +-(BOOL) isCacheable; +-(void) setCachedData:(NSData*) cachedData; +-(void) setCacheHandler:(MKNKResponseBlock) cacheHandler; +-(void) updateHandlersFromOperation:(MKNetworkOperation*) operation; +-(void) updateOperationBasedOnPreviousHeaders:(NSMutableDictionary*) headers; +-(NSString*) uniqueIdentifier; + +- (id)initWithURLString:(NSString *)aURLString + params:(NSDictionary *)params + httpMethod:(NSString *)method; +@end diff --git a/PSCollectionViewDemo/MKNetworkOperation.m b/PSCollectionViewDemo/MKNetworkOperation.m new file mode 100644 index 0000000..b1a8b83 --- /dev/null +++ b/PSCollectionViewDemo/MKNetworkOperation.m @@ -0,0 +1,1332 @@ +// +// MKNetworkOperation.m +// MKNetworkKit +// +// Created by Mugunth Kumar (@mugunthkumar) on 11/11/11. +// Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd + +// 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 "MKNetworkKit.h" + +#ifdef __OBJC_GC__ +#error MKNetworkKit does not support Objective-C Garbage Collection +#endif + +#if TARGET_OS_IPHONE +#ifndef __IPHONE_5_0 +#error MKNetworkKit does not support iOS 4 and lower +#endif +#endif + +#if ! __has_feature(objc_arc) +#error MKNetworkKit is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +@interface MKNetworkOperation (/*Private Methods*/) +@property (strong, nonatomic) NSURLConnection *connection; +@property (strong, nonatomic) NSString *uniqueId; +@property (strong, nonatomic) NSMutableURLRequest *request; +@property (strong, nonatomic) NSHTTPURLResponse *response; + +@property (strong, nonatomic) NSMutableDictionary *fieldsToBePosted; +@property (strong, nonatomic) NSMutableArray *filesToBePosted; +@property (strong, nonatomic) NSMutableArray *dataToBePosted; + +@property (strong, nonatomic) NSString *username; +@property (strong, nonatomic) NSString *password; + +@property (nonatomic, strong) NSMutableArray *responseBlocks; +@property (nonatomic, strong) NSMutableArray *errorBlocks; +@property (nonatomic, strong) NSMutableArray *errorBlocksType2; + +@property (nonatomic, assign) MKNetworkOperationState state; +@property (nonatomic, assign) BOOL isCancelled; + +@property (strong, nonatomic) NSMutableData *mutableData; +@property (assign, nonatomic) NSUInteger downloadedDataSize; + +@property (nonatomic, strong) NSMutableArray *notModifiedHandlers; + +@property (nonatomic, strong) NSMutableArray *uploadProgressChangedHandlers; +@property (nonatomic, strong) NSMutableArray *downloadProgressChangedHandlers; +@property (nonatomic, copy) MKNKEncodingBlock postDataEncodingHandler; + +@property (nonatomic, assign) NSInteger startPosition; + +@property (nonatomic, strong) NSMutableArray *downloadStreams; +@property (nonatomic, strong) NSData *cachedResponse; +@property (nonatomic, copy) MKNKResponseBlock cacheHandlingBlock; + +#if TARGET_OS_IPHONE +@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@property (strong, nonatomic) NSError *error; + +- (id)initWithURLString:(NSString *)aURLString + params:(NSDictionary *)body + httpMethod:(NSString *)method; + +-(NSData*) bodyData; + +-(NSString*) encodedPostDataString; +- (void) showLocalNotification; +- (void) endBackgroundTask; + +@end + +@implementation MKNetworkOperation + +@dynamic freezable; + +// A RESTful service should always return the same response for a given URL and it's parameters. +// this means if these values are correct, you can cache the responses +// This is another reason why we check only GET methods. +// even if URL and others are same, POST, DELETE, PUT methods should not be cached and should not be treated equal. + +-(BOOL) isCacheable { + + return [self.request.HTTPMethod isEqualToString:@"GET"]; +} + + +//=========================================================== +// + (BOOL)automaticallyNotifiesObserversForKey: +// +//=========================================================== ++ (BOOL)automaticallyNotifiesObserversForKey: (NSString *)theKey +{ + BOOL automatic; + + if ([theKey isEqualToString:@"postDataEncoding"]) { + automatic = NO; + } else { + automatic = [super automaticallyNotifiesObserversForKey:theKey]; + } + + return automatic; +} + +//=========================================================== +// postDataEncoding +//=========================================================== +- (MKNKPostDataEncodingType)postDataEncoding +{ + return _postDataEncoding; +} +- (void)setPostDataEncoding:(MKNKPostDataEncodingType)aPostDataEncoding +{ + _postDataEncoding = aPostDataEncoding; + + NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); + + switch (self.postDataEncoding) { + + case MKNKPostDataEncodingTypeURL: { + [self.request setValue: + [NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] + forHTTPHeaderField:@"Content-Type"]; + } + break; + case MKNKPostDataEncodingTypeJSON: { + [self.request setValue: + [NSString stringWithFormat:@"application/json; charset=%@", charset] + forHTTPHeaderField:@"Content-Type"]; + } + break; + case MKNKPostDataEncodingTypePlist: { + [self.request setValue: + [NSString stringWithFormat:@"application/x-plist; charset=%@", charset] + forHTTPHeaderField:@"Content-Type"]; + } + + default: + break; + } +} + +-(NSString*) encodedPostDataString { + + NSString *returnValue = @""; + if(self.postDataEncodingHandler) + returnValue = self.postDataEncodingHandler(self.fieldsToBePosted); + else if(self.postDataEncoding == MKNKPostDataEncodingTypeURL) + returnValue = [self.fieldsToBePosted urlEncodedKeyValueString]; + else if(self.postDataEncoding == MKNKPostDataEncodingTypeJSON) + returnValue = [self.fieldsToBePosted jsonEncodedKeyValueString]; + else if(self.postDataEncoding == MKNKPostDataEncodingTypePlist) + returnValue = [self.fieldsToBePosted plistEncodedKeyValueString]; + return returnValue; +} + +-(void) setCustomPostDataEncodingHandler:(MKNKEncodingBlock) postDataEncodingHandler forType:(NSString*) contentType { + + NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); + self.postDataEncoding = MKNKPostDataEncodingTypeCustom; + self.postDataEncodingHandler = postDataEncodingHandler; + [self.request setValue: + [NSString stringWithFormat:@"%@; charset=%@", contentType, charset] + forHTTPHeaderField:@"Content-Type"]; +} +//=========================================================== +// freezable +//=========================================================== +- (BOOL)freezable +{ + return _freezable; +} + +-(NSString*) url { + + return [[self.request URL] absoluteString]; +} + +-(NSURLRequest*) readonlyRequest { + + return [self.request copy]; +} + +-(NSHTTPURLResponse*) readonlyResponse { + + return [self.response copy]; +} + +- (NSDictionary *) readonlyPostDictionary { + + return [self.fieldsToBePosted copy]; +} + +-(NSString*) HTTPMethod { + + return self.request.HTTPMethod; +} + +-(NSInteger) HTTPStatusCode { + + if(self.response) + return self.response.statusCode; + else + return 0; +} + +- (void)setFreezable:(BOOL)flag +{ + // get method cannot be frozen. + // No point in freezing a method that doesn't change server state. + if([self.request.HTTPMethod isEqualToString:@"GET"] && flag) return; + _freezable = flag; + + if(_freezable && self.uniqueId == nil) + self.uniqueId = [NSString uniqueString]; +} + + +-(BOOL) isEqual:(id)object { + + if([self.request.HTTPMethod isEqualToString:@"GET"] || [self.request.HTTPMethod isEqualToString:@"HEAD"]) { + + MKNetworkOperation *anotherObject = (MKNetworkOperation*) object; + return ([[self uniqueIdentifier] isEqualToString:[anotherObject uniqueIdentifier]]); + } + + return NO; +} + + +-(NSString*) uniqueIdentifier { + + NSMutableString *str = [NSMutableString stringWithFormat:@"%@ %@", self.request.HTTPMethod, self.url]; + + if(self.username || self.password) { + + [str appendFormat:@" [%@:%@]", + self.username ? self.username : @"", + self.password ? self.password : @""]; + } + + if(self.freezable) { + + [str appendString:self.uniqueId]; + } + return [str md5]; +} + +-(BOOL) isCachedResponse { + + return self.cachedResponse != nil; +} + +-(void) notifyCache { + + if(![self isCacheable]) return; + if(!([self.response statusCode] >= 200 && [self.response statusCode] < 300)) return; + + if(![self isCancelled]) + self.cacheHandlingBlock(self); +} + +-(MKNetworkOperationState) state { + + return _state; +} + +-(void) setState:(MKNetworkOperationState)newState { + + switch (newState) { + case MKNetworkOperationStateReady: + [self willChangeValueForKey:@"isReady"]; + break; + case MKNetworkOperationStateExecuting: + [self willChangeValueForKey:@"isReady"]; + [self willChangeValueForKey:@"isExecuting"]; + break; + case MKNetworkOperationStateFinished: + [self willChangeValueForKey:@"isExecuting"]; + [self willChangeValueForKey:@"isFinished"]; + break; + } + + _state = newState; + + switch (newState) { + case MKNetworkOperationStateReady: + [self didChangeValueForKey:@"isReady"]; + break; + case MKNetworkOperationStateExecuting: + [self didChangeValueForKey:@"isReady"]; + [self didChangeValueForKey:@"isExecuting"]; + break; + case MKNetworkOperationStateFinished: + [self didChangeValueForKey:@"isExecuting"]; + [self didChangeValueForKey:@"isFinished"]; + break; + } + + if(self.operationStateChangedHandler) { + self.operationStateChangedHandler(newState); + } +} + +- (void)encodeWithCoder:(NSCoder *)encoder +{ + [encoder encodeInteger:self.stringEncoding forKey:@"stringEncoding"]; + [encoder encodeInteger:_postDataEncoding forKey:@"postDataEncoding"]; + + [encoder encodeObject:self.uniqueId forKey:@"uniqueId"]; + [encoder encodeObject:self.request forKey:@"request"]; + [encoder encodeObject:self.response forKey:@"response"]; + [encoder encodeObject:self.fieldsToBePosted forKey:@"fieldsToBePosted"]; + [encoder encodeObject:self.filesToBePosted forKey:@"filesToBePosted"]; + [encoder encodeObject:self.dataToBePosted forKey:@"dataToBePosted"]; + [encoder encodeObject:self.username forKey:@"username"]; + [encoder encodeObject:self.password forKey:@"password"]; + [encoder encodeObject:self.clientCertificate forKey:@"clientCertificate"]; + + self.state = MKNetworkOperationStateReady; + [encoder encodeInt32:_state forKey:@"state"]; + [encoder encodeBool:self.isCancelled forKey:@"isCancelled"]; + [encoder encodeObject:self.mutableData forKey:@"mutableData"]; + [encoder encodeInteger:self.downloadedDataSize forKey:@"downloadedDataSize"]; + [encoder encodeObject:self.downloadStreams forKey:@"downloadStreams"]; + [encoder encodeInteger:self.startPosition forKey:@"startPosition"]; + [encoder encodeInteger:self.credentialPersistence forKey:@"credentialPersistence"]; +} + +- (id)initWithCoder:(NSCoder *)decoder +{ + self = [super init]; + if (self) { + [self setStringEncoding:[decoder decodeIntegerForKey:@"stringEncoding"]]; + _postDataEncoding = (MKNKPostDataEncodingType) [decoder decodeIntegerForKey:@"postDataEncoding"]; + self.request = [decoder decodeObjectForKey:@"request"]; + self.uniqueId = [decoder decodeObjectForKey:@"uniqueId"]; + + self.response = [decoder decodeObjectForKey:@"response"]; + self.fieldsToBePosted = [decoder decodeObjectForKey:@"fieldsToBePosted"]; + self.filesToBePosted = [decoder decodeObjectForKey:@"filesToBePosted"]; + self.dataToBePosted = [decoder decodeObjectForKey:@"dataToBePosted"]; + self.username = [decoder decodeObjectForKey:@"username"]; + self.password = [decoder decodeObjectForKey:@"password"]; + self.clientCertificate = [decoder decodeObjectForKey:@"clientCertificate"]; + [self setState:[decoder decodeInt32ForKey:@"state"]]; + self.isCancelled = [decoder decodeBoolForKey:@"isCancelled"]; + self.mutableData = [decoder decodeObjectForKey:@"mutableData"]; + self.downloadedDataSize = [decoder decodeIntegerForKey:@"downloadedDataSize"]; + self.downloadStreams = [decoder decodeObjectForKey:@"downloadStreams"]; + self.startPosition = [decoder decodeIntegerForKey:@"startPosition"]; + self.credentialPersistence = [decoder decodeIntegerForKey:@"credentialPersistence"]; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone +{ + MKNetworkOperation *theCopy = [[[self class] allocWithZone:zone] init]; // use designated initializer + + theCopy.postDataEncoding = _postDataEncoding; + [theCopy setStringEncoding:self.stringEncoding]; + [theCopy setUniqueId:[self.uniqueId copy]]; + + [theCopy setConnection:[self.connection copy]]; + [theCopy setRequest:[self.request copy]]; + [theCopy setResponse:[self.response copy]]; + [theCopy setFieldsToBePosted:[self.fieldsToBePosted copy]]; + [theCopy setFilesToBePosted:[self.filesToBePosted copy]]; + [theCopy setDataToBePosted:[self.dataToBePosted copy]]; + [theCopy setUsername:[self.username copy]]; + [theCopy setPassword:[self.password copy]]; + [theCopy setClientCertificate:[self.clientCertificate copy]]; + [theCopy setResponseBlocks:[self.responseBlocks copy]]; + [theCopy setErrorBlocks:[self.errorBlocks copy]]; + [theCopy setErrorBlocksType2:[self.errorBlocksType2 copy]]; + [theCopy setState:self.state]; + [theCopy setIsCancelled:self.isCancelled]; + [theCopy setMutableData:[self.mutableData copy]]; + [theCopy setDownloadedDataSize:self.downloadedDataSize]; + [theCopy setNotModifiedHandlers:[self.notModifiedHandlers copy]]; + [theCopy setUploadProgressChangedHandlers:[self.uploadProgressChangedHandlers copy]]; + [theCopy setDownloadProgressChangedHandlers:[self.downloadProgressChangedHandlers copy]]; + [theCopy setDownloadStreams:[self.downloadStreams copy]]; + [theCopy setCachedResponse:[self.cachedResponse copy]]; + [theCopy setCacheHandlingBlock:self.cacheHandlingBlock]; + [theCopy setStartPosition:self.startPosition]; + [theCopy setCredentialPersistence:self.credentialPersistence]; + + return theCopy; +} + +-(void) dealloc { + + [_connection cancel]; + _connection = nil; +} + +-(void) updateHandlersFromOperation:(MKNetworkOperation*) operation { + + [self.responseBlocks addObjectsFromArray:operation.responseBlocks]; + [self.errorBlocks addObjectsFromArray:operation.errorBlocks]; + [self.errorBlocksType2 addObjectsFromArray:operation.errorBlocksType2]; + [self.notModifiedHandlers addObjectsFromArray:operation.notModifiedHandlers]; + [self.uploadProgressChangedHandlers addObjectsFromArray:operation.uploadProgressChangedHandlers]; + [self.downloadProgressChangedHandlers addObjectsFromArray:operation.downloadProgressChangedHandlers]; + [self.downloadStreams addObjectsFromArray:operation.downloadStreams]; +} + +-(void) setCachedData:(NSData*) cachedData { + + self.cachedResponse = cachedData; + [self operationSucceeded]; +} + +-(void) updateOperationBasedOnPreviousHeaders:(NSMutableDictionary*) headers { + + NSString *lastModified = headers[@"Last-Modified"]; + NSString *eTag = headers[@"ETag"]; + if(lastModified) { + [self.request setValue:lastModified forHTTPHeaderField:@"IF-MODIFIED-SINCE"]; + } + + if(eTag) { + [self.request setValue:eTag forHTTPHeaderField:@"IF-NONE-MATCH"]; + } +} + +-(void) setUsername:(NSString*) username password:(NSString*) password { + + self.username = username; + self.password = password; +} + +-(void) setUsername:(NSString*) username password:(NSString*) password basicAuth:(BOOL) bYesOrNo { + + [self setUsername:username password:password]; + NSString *base64EncodedString = [[[NSString stringWithFormat:@"%@:%@", self.username, self.password] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString]; + + [self setAuthorizationHeaderValue:base64EncodedString forAuthType:@"Basic"]; +} + +-(void) onCompletion:(MKNKResponseBlock) response onError:(MKNKErrorBlock) error { + + [self.responseBlocks addObject:[response copy]]; + [self.errorBlocks addObject:[error copy]]; +} + +-(void) addCompletionHandler:(MKNKResponseBlock)response errorHandler:(MKNKResponseErrorBlock)error { + + if(response) + [self.responseBlocks addObject:[response copy]]; + if(error) + [self.errorBlocksType2 addObject:[error copy]]; +} + +-(void) onNotModified:(MKNKVoidBlock)notModifiedBlock { + + [self.notModifiedHandlers addObject:[notModifiedBlock copy]]; +} + +-(void) onUploadProgressChanged:(MKNKProgressBlock) uploadProgressBlock { + + [self.uploadProgressChangedHandlers addObject:[uploadProgressBlock copy]]; +} + +-(void) onDownloadProgressChanged:(MKNKProgressBlock) downloadProgressBlock { + + [self.downloadProgressChangedHandlers addObject:[downloadProgressBlock copy]]; +} + +-(void) setUploadStream:(NSInputStream*) inputStream { + +#warning Method not tested yet. + self.request.HTTPBodyStream = inputStream; +} + +-(void) addDownloadStream:(NSOutputStream*) outputStream { + + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.downloadStreams addObject:outputStream]; +} + +- (id)initWithURLString:(NSString *)aURLString + params:(NSDictionary *)params + httpMethod:(NSString *)method + +{ + if((self = [super init])) { + + self.responseBlocks = [NSMutableArray array]; + self.errorBlocks = [NSMutableArray array]; + self.errorBlocksType2 = [NSMutableArray array]; + self.filesToBePosted = [NSMutableArray array]; + self.dataToBePosted = [NSMutableArray array]; + self.fieldsToBePosted = [NSMutableDictionary dictionary]; + + self.notModifiedHandlers = [NSMutableArray array]; + self.uploadProgressChangedHandlers = [NSMutableArray array]; + self.downloadProgressChangedHandlers = [NSMutableArray array]; + self.downloadStreams = [NSMutableArray array]; + + self.credentialPersistence = NSURLCredentialPersistenceForSession; + + NSURL *finalURL = nil; + + if(params) + self.fieldsToBePosted = [params mutableCopy]; + + self.stringEncoding = NSUTF8StringEncoding; // use a delegate to get these values later + + if ([method isEqualToString:@"GET"]) + self.cacheHeaders = [NSMutableDictionary dictionary]; + + if (([method isEqualToString:@"GET"] || + [method isEqualToString:@"DELETE"]) && (params && [params count] > 0)) { + + finalURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", aURLString, + [self encodedPostDataString]]]; + } else { + finalURL = [NSURL URLWithString:aURLString]; + } + + self.request = [NSMutableURLRequest requestWithURL:finalURL + cachePolicy:NSURLRequestReloadIgnoringLocalCacheData + timeoutInterval:kMKNetworkKitRequestTimeOutInSeconds]; + + [self.request setHTTPMethod:method]; + + [self.request setValue:[NSString stringWithFormat:@"%@, en-us", + [[NSLocale preferredLanguages] componentsJoinedByString:@", "] + ] forHTTPHeaderField:@"Accept-Language"]; + + if (([method isEqualToString:@"POST"] || + [method isEqualToString:@"PUT"]) && (params && [params count] > 0)) { + + self.postDataEncoding = MKNKPostDataEncodingTypeURL; + } + + self.state = MKNetworkOperationStateReady; + } + + return self; +} + +-(void) addHeaders:(NSDictionary*) headersDictionary { + + [headersDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [self.request addValue:obj forHTTPHeaderField:key]; + }]; +} + +-(void) setAuthorizationHeaderValue:(NSString*) token forAuthType:(NSString*) authType { + + [self.request setValue:[NSString stringWithFormat:@"%@ %@", authType, token] + forHTTPHeaderField:@"Authorization"]; +} +/* + Printing a MKNetworkOperation object is printed in curl syntax + */ + +-(NSString*) description { + + NSMutableString *displayString = [NSMutableString stringWithFormat:@"%@\nRequest\n-------\n%@", + [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]], + [self curlCommandLineString]]; + + NSString *responseString = [self responseString]; + if([responseString length] > 0) { + [displayString appendFormat:@"\n--------\nResponse\n--------\n%@\n", responseString]; + } + + return displayString; +} + +-(NSString*) curlCommandLineString +{ + __block NSMutableString *displayString = [NSMutableString stringWithFormat:@"curl -X %@", self.request.HTTPMethod]; + + if([self.filesToBePosted count] == 0 && [self.dataToBePosted count] == 0) { + [[self.request allHTTPHeaderFields] enumerateKeysAndObjectsUsingBlock:^(id key, id val, BOOL *stop) + { + [displayString appendFormat:@" -H \"%@: %@\"", key, val]; + }]; + } + + [displayString appendFormat:@" \"%@\"", self.url]; + + if ([self.request.HTTPMethod isEqualToString:@"POST"] || [self.request.HTTPMethod isEqualToString:@"PUT"]) { + + NSString *option = [self.filesToBePosted count] == 0 ? @"-d" : @"-F"; + if(self.postDataEncoding == MKNKPostDataEncodingTypeURL) { + [self.fieldsToBePosted enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + + [displayString appendFormat:@" %@ \"%@=%@\"", option, key, obj]; + }]; + } else { + [displayString appendFormat:@" -d \"%@\"", [self encodedPostDataString]]; + } + + + [self.filesToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + + NSDictionary *thisFile = (NSDictionary*) obj; + [displayString appendFormat:@" -F \"%@=@%@;type=%@\"", thisFile[@"name"], + thisFile[@"filepath"], thisFile[@"mimetype"]]; + }]; + + /* Not sure how to do this via curl + [self.dataToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + + NSDictionary *thisData = (NSDictionary*) obj; + [displayString appendFormat:@" --data-binary \"%@\"", [thisData objectForKey:@"data"]]; + }];*/ + } + + return displayString; +} + + +-(void) addData:(NSData*) data forKey:(NSString*) key { + + [self addData:data forKey:key mimeType:@"application/octet-stream" fileName:@"file"]; +} + +-(void) addData:(NSData*) data forKey:(NSString*) key mimeType:(NSString*) mimeType fileName:(NSString*) fileName { + + if ([self.request.HTTPMethod isEqualToString:@"GET"]) { + [self.request setHTTPMethod:@"POST"]; + } + + NSDictionary *dict = @{@"data": data, + @"name": key, + @"mimetype": mimeType, + @"filename": fileName}; + + [self.dataToBePosted addObject:dict]; +} + +-(void) addFile:(NSString*) filePath forKey:(NSString*) key { + + [self addFile:filePath forKey:key mimeType:@"application/octet-stream"]; +} + +-(void) addFile:(NSString*) filePath forKey:(NSString*) key mimeType:(NSString*) mimeType { + + if ([self.request.HTTPMethod isEqualToString:@"GET"]) { + [self.request setHTTPMethod:@"POST"]; + } + + NSDictionary *dict = @{@"filepath": filePath, + @"name": key, + @"mimetype": mimeType}; + + [self.filesToBePosted addObject:dict]; +} + +-(NSData*) bodyData { + + if([self.filesToBePosted count] == 0 && [self.dataToBePosted count] == 0) { + + return [[self encodedPostDataString] dataUsingEncoding:self.stringEncoding]; + } + + NSString *boundary = @"0xKhTmLbOuNdArY"; + NSMutableData *body = [NSMutableData data]; + __block NSUInteger postLength = 0; + + [self.fieldsToBePosted enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + + NSString *thisFieldString = [NSString stringWithFormat: + @"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@", + boundary, key, obj]; + + [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]]; + [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]]; + }]; + + [self.filesToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + + NSDictionary *thisFile = (NSDictionary*) obj; + NSString *thisFieldString = [NSString stringWithFormat: + @"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\nContent-Transfer-Encoding: binary\r\n\r\n", + boundary, + thisFile[@"name"], + [thisFile[@"filepath"] lastPathComponent], + thisFile[@"mimetype"]]; + + [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]]; + [body appendData: [NSData dataWithContentsOfFile:thisFile[@"filepath"]]]; + [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]]; + }]; + + [self.dataToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + + NSDictionary *thisDataObject = (NSDictionary*) obj; + NSString *thisFieldString = [NSString stringWithFormat: + @"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\nContent-Transfer-Encoding: binary\r\n\r\n", + boundary, + thisDataObject[@"name"], + thisDataObject[@"filename"], + thisDataObject[@"mimetype"]]; + + [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]]; + [body appendData:thisDataObject[@"data"]]; + [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]]; + }]; + + if (postLength >= 1) + [self.request setValue:[NSString stringWithFormat:@"%lu", (unsigned long) postLength] forHTTPHeaderField:@"Content-Length"]; + + [body appendData: [[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:self.stringEncoding]]; + + NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); + + if(([self.filesToBePosted count] > 0) || ([self.dataToBePosted count] > 0)) { + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, boundary] + forHTTPHeaderField:@"Content-Type"]; + + [self.request setValue:[NSString stringWithFormat:@"%lu", (unsigned long) [body length]] forHTTPHeaderField:@"Content-Length"]; + } + + return body; +} + + +-(void) setCacheHandler:(MKNKResponseBlock) cacheHandler { + + self.cacheHandlingBlock = cacheHandler; +} + +#pragma mark - +#pragma Main method +-(void) main { + + @autoreleasepool { + [self start]; + } +} + +-(void) endBackgroundTask { + +#if TARGET_OS_IPHONE + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } + }); +#endif +} + +- (void) start +{ + +#if TARGET_OS_IPHONE + self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ + + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.backgroundTaskId != UIBackgroundTaskInvalid) + { + [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + [self cancel]; + } + }); + }]; + +#endif + + if(!self.isCancelled) { + + if (([self.request.HTTPMethod isEqualToString:@"POST"] || [self.request.HTTPMethod isEqualToString:@"PUT"]) && !self.request.HTTPBodyStream) { + + [self.request setHTTPBody:[self bodyData]]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + self.connection = [[NSURLConnection alloc] initWithRequest:self.request + delegate:self + startImmediately:NO]; + + [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] + forMode:NSRunLoopCommonModes]; + + [self.connection start]; + }); + + self.state = MKNetworkOperationStateExecuting; + } + else { + self.state = MKNetworkOperationStateFinished; + [self endBackgroundTask]; + } +} + +#pragma - +#pragma mark NSOperation stuff + +- (BOOL)isConcurrent +{ + return YES; +} + +- (BOOL)isReady { + + return (self.state == MKNetworkOperationStateReady); +} + +- (BOOL)isFinished +{ + return (self.state == MKNetworkOperationStateFinished); +} + +- (BOOL)isExecuting { + + return (self.state == MKNetworkOperationStateExecuting); +} + +-(void) cancel { + + if([self isFinished]) + return; + + @synchronized(self) { + self.isCancelled = YES; + + [self.connection cancel]; + + [self.responseBlocks removeAllObjects]; + self.responseBlocks = nil; + + [self.errorBlocks removeAllObjects]; + self.errorBlocks = nil; + + [self.errorBlocksType2 removeAllObjects]; + self.errorBlocksType2 = nil; + + [self.notModifiedHandlers removeAllObjects]; + self.notModifiedHandlers = nil; + + [self.uploadProgressChangedHandlers removeAllObjects]; + self.uploadProgressChangedHandlers = nil; + + [self.downloadProgressChangedHandlers removeAllObjects]; + self.downloadProgressChangedHandlers = nil; + + for(NSOutputStream *stream in self.downloadStreams) + [stream close]; + + [self.downloadStreams removeAllObjects]; + self.downloadStreams = nil; + + self.authHandler = nil; + self.mutableData = nil; + self.downloadedDataSize = 0; + + self.cacheHandlingBlock = nil; + + if(self.state == MKNetworkOperationStateExecuting) + self.state = MKNetworkOperationStateFinished; // This notifies the queue and removes the operation. + // if the operation is not removed, the spinner continues to spin, not a good UX + + [self endBackgroundTask]; + } + [super cancel]; +} + +#pragma mark - +#pragma mark NSURLConnection delegates + +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { + + self.state = MKNetworkOperationStateFinished; + self.mutableData = nil; + self.downloadedDataSize = 0; + for(NSOutputStream *stream in self.downloadStreams) + [stream close]; + + [self operationFailedWithError:error]; + [self endBackgroundTask]; +} + +- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { + + if ([challenge previousFailureCount] == 0) { + + if (((challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodDefault) || + (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic) || + (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest) || + (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM)) && + (self.username && self.password)) + { + + // for NTLM, we will assume user name to be of the form "domain\\username" + NSURLCredential *credential = [NSURLCredential credentialWithUser:self.username + password:self.password + persistence:self.credentialPersistence]; + + [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; + } + else if ((challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) && self.clientCertificate) { + + NSData *certData = [[NSData alloc] initWithContentsOfFile:self.clientCertificate]; + +#warning method not implemented. Don't use client certicate authentication for now. + SecIdentityRef myIdentity = nil; // ??? + + SecCertificateRef myCert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData); + SecCertificateRef certArray[1] = { myCert }; + CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL); + CFRelease(myCert); + NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity + certificates:(__bridge NSArray *)myCerts + persistence:NSURLCredentialPersistencePermanent]; + CFRelease(myCerts); + [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; + } + else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { +#warning method not tested. proceed at your own risk + SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust]; + SecTrustResultType result; + SecTrustEvaluate(serverTrust, &result); + + if(result == kSecTrustResultProceed) { + + [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; + } + else if(result == kSecTrustResultConfirm) { + + // ask user + BOOL userOkWithWrongCert = NO; // (ACTUALLY CHEAT., DON'T BE A F***ING BROWSER, USERS ALWAYS TAP YES WHICH IS RISKY) + if(userOkWithWrongCert) { + + // Cert not trusted, but user is OK with that + [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; + } else { + + // Cert not trusted, and user is not OK with that. Don't proceed + [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } + else { + + // invalid or revoked certificate + [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; + //[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } + else if (self.authHandler) { + + // forward the authentication to the view controller that created this operation + // If this happens for NSURLAuthenticationMethodHTMLForm, you have to + // do some shit work like showing a modal webview controller and close it after authentication. + // I HATE THIS. + self.authHandler(challenge); + } + else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } else { + // apple proposes to cancel authentication, which results in NSURLErrorDomain error -1012, but we prefer to trigger a 401 + // [[challenge sender] cancelAuthenticationChallenge:challenge]; + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } +} + +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { + + NSUInteger size = [self.response expectedContentLength] < 0 ? 0 : [self.response expectedContentLength]; + self.response = (NSHTTPURLResponse*) response; + + // dont' save data if the operation was created to download directly to a stream. + if([self.downloadStreams count] == 0) + self.mutableData = [NSMutableData dataWithCapacity:size]; + else + self.mutableData = nil; + + for(NSOutputStream *stream in self.downloadStreams) + [stream open]; + + NSDictionary *httpHeaders = [self.response allHeaderFields]; + + // if you attach a stream to the operation, MKNetworkKit will not cache the response. + // Streams are usually "big data chunks" that doesn't need caching anyways. + + if([self.request.HTTPMethod isEqualToString:@"GET"] && [self.downloadStreams count] == 0) { + + // We have all this complicated cache handling since NSURLRequestReloadRevalidatingCacheData is not implemented + // do cache processing only if the request is a "GET" method + NSString *lastModified = httpHeaders[@"Last-Modified"]; + NSString *eTag = httpHeaders[@"ETag"]; + NSString *expiresOn = httpHeaders[@"Expires"]; + + NSString *contentType = httpHeaders[@"Content-Type"]; + // if contentType is image, + + NSDate *expiresOnDate = nil; + + if([contentType rangeOfString:@"image"].location != NSNotFound) { + + // For images let's assume a expiry date of 7 days if there is no eTag or Last Modified. + if(!eTag && !lastModified) + expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultImageCacheDuration]; + else + expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultImageHeadRequestDuration]; + } + + NSString *cacheControl = httpHeaders[@"Cache-Control"]; // max-age, must-revalidate, no-cache + NSArray *cacheControlEntities = [cacheControl componentsSeparatedByString:@","]; + + for(NSString *substring in cacheControlEntities) { + + if([substring rangeOfString:@"max-age"].location != NSNotFound) { + + // do some processing to calculate expiresOn + NSString *maxAge = nil; + NSArray *array = [substring componentsSeparatedByString:@"="]; + if([array count] > 1) + maxAge = array[1]; + + expiresOnDate = [[NSDate date] dateByAddingTimeInterval:[maxAge intValue]]; + } + if([substring rangeOfString:@"no-cache"].location != NSNotFound) { + + // Don't cache this request + expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultCacheDuration]; + } + } + + // if there was a cacheControl entity, we would have a expiresOnDate that is not nil. + // "Cache-Control" headers take precedence over "Expires" headers + + expiresOn = [expiresOnDate rfc1123String]; + + // now remember lastModified, eTag and expires for this request in cache + if(expiresOn) + (self.cacheHeaders)[@"Expires"] = expiresOn; + if(lastModified) + (self.cacheHeaders)[@"Last-Modified"] = lastModified; + if(eTag) + (self.cacheHeaders)[@"ETag"] = eTag; + } +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { + + if (self.downloadedDataSize == 0) { + // This is the first batch of data + // Check for a range header and make changes as neccesary + NSString *rangeString = [[self request] valueForHTTPHeaderField:@"Range"]; + if ([rangeString hasPrefix:@"bytes="] && [rangeString hasSuffix:@"-"]) { + NSString *bytesText = [rangeString substringWithRange:NSMakeRange(6, [rangeString length] - 7)]; + self.startPosition = [bytesText integerValue]; + self.downloadedDataSize = self.startPosition; + DLog(@"Resuming at %lu bytes", (unsigned long) self.startPosition); + } + } + + if([self.downloadStreams count] == 0) + [self.mutableData appendData:data]; + + for(NSOutputStream *stream in self.downloadStreams) { + + if ([stream hasSpaceAvailable]) { + const uint8_t *dataBuffer = [data bytes]; + [stream write:&dataBuffer[0] maxLength:[data length]]; + } + } + + self.downloadedDataSize += [data length]; + + for(MKNKProgressBlock downloadProgressBlock in self.downloadProgressChangedHandlers) { + + if([self.response expectedContentLength] > 0) { + + double progress = (double)(self.downloadedDataSize) / (double)(self.startPosition + [self.response expectedContentLength]); + downloadProgressBlock(progress); + } + } +} + +- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten + totalBytesWritten:(NSInteger)totalBytesWritten +totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { + + for(MKNKProgressBlock uploadProgressBlock in self.uploadProgressChangedHandlers) { + + if(totalBytesExpectedToWrite > 0) { + uploadProgressBlock(((double)totalBytesWritten/(double)totalBytesExpectedToWrite)); + } + } +} + +// http://stackoverflow.com/questions/1446509/handling-redirects-correctly-with-nsurlconnection +- (NSURLRequest *)connection: (NSURLConnection *)inConnection + willSendRequest: (NSURLRequest *)inRequest + redirectResponse: (NSURLResponse *)inRedirectResponse; +{ + if (inRedirectResponse) { + NSMutableURLRequest *r = [self.request mutableCopy]; + [r setURL: [inRequest URL]]; + + return r; + } else { + return inRequest; + } +} +- (void)connectionDidFinishLoading:(NSURLConnection *)connection { + + if([self isCancelled]) + return; + + self.state = MKNetworkOperationStateFinished; + + for(NSOutputStream *stream in self.downloadStreams) + [stream close]; + + if (self.response.statusCode >= 200 && self.response.statusCode < 300 && ![self isCancelled]) { + + self.cachedResponse = nil; // remove cached data + [self notifyCache]; + [self operationSucceeded]; + + } + if (self.response.statusCode >= 300 && self.response.statusCode < 400) { + + if(self.response.statusCode == 301) { + DLog(@"%@ has moved to %@", self.url, [self.response.URL absoluteString]); + } + else if(self.response.statusCode == 304) { + + for(MKNKVoidBlock notModifiedBlock in self.notModifiedHandlers) { + + notModifiedBlock(); + } + } + else if(self.response.statusCode == 307) { + DLog(@"%@ temporarily redirected", self.url); + } + else { + DLog(@"%@ returned status %d", self.url, (int) self.response.statusCode); + } + + } else if (self.response.statusCode >= 400 && self.response.statusCode < 600 && ![self isCancelled]) { + + [self operationFailedWithError:[NSError errorWithDomain:NSURLErrorDomain + code:self.response.statusCode + userInfo:self.response.allHeaderFields]]; + } + [self endBackgroundTask]; + +} + +#pragma mark - +#pragma mark Our methods to get data + +-(NSData*) responseData { + + if([self isFinished]) + return self.mutableData; + else if(self.cachedResponse) + return self.cachedResponse; + else + return nil; +} + +-(NSString*)responseString { + + return [self responseStringWithEncoding:self.stringEncoding]; +} + +-(NSString*) responseStringWithEncoding:(NSStringEncoding) encoding { + + return [[NSString alloc] initWithData:[self responseData] encoding:encoding]; +} + +#if TARGET_OS_IPHONE +-(UIImage*) responseImage { + + return [UIImage imageWithData:[self responseData]]; +} + +-(void) decompressedResponseImageOfSize:(CGSize) size completionHandler:(void (^)(UIImage *decompressedImage)) imageDecompressionHandler { + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + + __block CGSize targetSize = size; + UIImage *image = [self responseImage]; + CGImageRef imageRef = image.CGImage; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef); + BOOL sameSize = NO; + if (CGSizeEqualToSize(targetSize, CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)))) { + targetSize = CGSizeMake(1, 1); + sameSize = YES; + } + + size_t imageWidth = (size_t)targetSize.width; + size_t imageHeight = (size_t)targetSize.height; + + CGContextRef context = CGBitmapContextCreate(NULL, + imageWidth, + imageHeight, + 8, + // Just always return width * 4 will be enough + imageWidth * 4, + // System only supports RGB, set explicitly + colorSpace, + // Makes system don't need to do extra conversion when displayed. + alphaInfo | kCGBitmapByteOrder32Little); + CGColorSpaceRelease(colorSpace); + if (!context) { + return; + } + + + CGRect rect = (CGRect){CGPointZero, {imageWidth, imageHeight}}; + CGContextDrawImage(context, rect, imageRef); + if (sameSize) { + CGContextRelease(context); + dispatch_async(dispatch_get_main_queue(), ^{ + imageDecompressionHandler(image); + }); + return; + } + CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); + CGContextRelease(context); + + static float scale = 0.0f; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + scale = [UIScreen mainScreen].scale; + }); + + UIImage *decompressedImage = [[UIImage alloc] initWithCGImage:decompressedImageRef scale:scale orientation:image.imageOrientation]; + CGImageRelease(decompressedImageRef); + dispatch_async(dispatch_get_main_queue(), ^{ + imageDecompressionHandler(decompressedImage); + }); + }); +} + +#elif TARGET_OS_MAC +-(NSImage*) responseImage { + + return [[NSImage alloc] initWithData:[self responseData]]; +} + +-(NSXMLDocument*) responseXML { + + return [[NSXMLDocument alloc] initWithData:[self responseData] options:0 error:nil]; +} +#endif + +-(id) responseJSON { + + if([self responseData] == nil) return nil; + NSError *error = nil; + id returnValue = [NSJSONSerialization JSONObjectWithData:[self responseData] options:0 error:&error]; + if(error) DLog(@"JSON Parsing Error: %@", error); + return returnValue; +} + +#pragma mark - +#pragma mark Overridable methods + +-(void) operationSucceeded { + + for(MKNKResponseBlock responseBlock in self.responseBlocks) + responseBlock(self); +} + +-(void) showLocalNotification { +#if TARGET_OS_IPHONE + + if(self.localNotification) { + + [[UIApplication sharedApplication] presentLocalNotificationNow:self.localNotification]; + } else if(self.shouldShowLocalNotificationOnError) { + + UILocalNotification *localNotification = [[UILocalNotification alloc] init]; + + localNotification.alertBody = [self.error localizedDescription]; + localNotification.alertAction = NSLocalizedString(@"Dismiss", @""); + + [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; + } +#endif +} + +-(void) operationFailedWithError:(NSError*) error { + + self.error = error; + DLog(@"%@, [%@]", self, [self.error localizedDescription]); + for(MKNKErrorBlock errorBlock in self.errorBlocks) + errorBlock(error); + + for(MKNKResponseErrorBlock errorBlock in self.errorBlocksType2) + errorBlock(self, error); + +#if TARGET_OS_IPHONE + DLog(@"State: %d", [[UIApplication sharedApplication] applicationState]); + if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) + [self showLocalNotification]; +#endif + +} + +@end diff --git a/PSCollectionViewDemo/PSCollectionView.h b/PSCollectionViewDemo/PSCollectionView.h new file mode 100644 index 0000000..df6c866 --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionView.h @@ -0,0 +1,82 @@ +// +// PSCollectionView.h +// +// Copyright (c) 2012 Peter Shih (http://petershih.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. + +#import +#import "PSCollectionViewCell.h" + +#define kPSCollectionViewDidRelayoutNotification @"kPSCollectionViewDidRelayoutNotification" + +@class PSCollectionViewCell; + +@protocol PSCollectionViewDelegate, PSCollectionViewDataSource; + +@interface PSCollectionView : UIScrollView + +#pragma mark - Public Properties + +@property (nonatomic, strong) UIView *headerView; +@property (nonatomic, strong) UIView *footerView; + +@property (nonatomic, assign, readonly) CGFloat colWidth; +@property (nonatomic, assign, readonly) NSInteger numCols; +@property (nonatomic, assign) NSInteger numColsLandscape; +@property (nonatomic, assign) NSInteger numColsPortrait; +@property (nonatomic, unsafe_unretained) id collectionViewDelegate; +@property (nonatomic, unsafe_unretained) id collectionViewDataSource; + +#pragma mark - Public Methods + +/** + Reloads the collection view + This is similar to UITableView reloadData) + */ +- (void)reloadData; + +/** + Dequeues a reusable view that was previously initialized + This is similar to UITableView dequeueReusableCellWithIdentifier + */ +- (PSCollectionViewCell *)dequeueReusableViewForClass:(Class)viewClass; + +@end + +#pragma mark - Delegate + +@protocol PSCollectionViewDelegate + +@optional +- (void)collectionView:(PSCollectionView *)collectionView didSelectCell:(PSCollectionViewCell *)cell atIndex:(NSInteger)index; +- (Class)collectionView:(PSCollectionView *)collectionView cellClassForRowAtIndex:(NSInteger)index; + +@end + +#pragma mark - DataSource + +@protocol PSCollectionViewDataSource + +@required +- (NSInteger)numberOfRowsInCollectionView:(PSCollectionView *)collectionView; +- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index; +- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index; + +@end diff --git a/PSCollectionViewDemo/PSCollectionView.m b/PSCollectionViewDemo/PSCollectionView.m new file mode 100644 index 0000000..2e5d405 --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionView.m @@ -0,0 +1,434 @@ +// +// PSCollectionView.m +// +// Copyright (c) 2012 Peter Shih (http://petershih.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. + +#import "PSCollectionView.h" + +#define kMargin 8.0 + +static inline NSString * PSCollectionKeyForIndex(NSInteger index) { + return [NSString stringWithFormat:@"%d", index]; +} + +static inline NSInteger PSCollectionIndexForKey(NSString *key) { + return [key integerValue]; +} + +#pragma mark - UIView Category + +@interface UIView (PSCollectionView) + +@property(nonatomic, assign) CGFloat left; +@property(nonatomic, assign) CGFloat top; +@property(nonatomic, assign, readonly) CGFloat right; +@property(nonatomic, assign, readonly) CGFloat bottom; +@property(nonatomic, assign) CGFloat width; +@property(nonatomic, assign) CGFloat height; + +@end + +@implementation UIView (PSCollectionView) + +- (CGFloat)left { + return self.frame.origin.x; +} + +- (void)setLeft:(CGFloat)x { + CGRect frame = self.frame; + frame.origin.x = x; + self.frame = frame; +} + +- (CGFloat)top { + return self.frame.origin.y; +} + +- (void)setTop:(CGFloat)y { + CGRect frame = self.frame; + frame.origin.y = y; + self.frame = frame; +} + +- (CGFloat)right { + return self.frame.origin.x + self.frame.size.width; +} + +- (CGFloat)bottom { + return self.frame.origin.y + self.frame.size.height; +} + +- (CGFloat)width { + return self.frame.size.width; +} + +- (void)setWidth:(CGFloat)width { + CGRect frame = self.frame; + frame.size.width = width; + self.frame = frame; +} + +- (CGFloat)height { + return self.frame.size.height; +} + +- (void)setHeight:(CGFloat)height { + CGRect frame = self.frame; + frame.size.height = height; + self.frame = frame; +} + +@end + +#pragma mark - Gesture Recognizer + +// This is just so we know that we sent this tap gesture recognizer in the delegate +@interface PSCollectionViewTapGestureRecognizer : UITapGestureRecognizer +@end + +@implementation PSCollectionViewTapGestureRecognizer +@end + + +@interface PSCollectionView () + +@property (nonatomic, assign, readwrite) CGFloat lastOffset; +@property (nonatomic, assign, readwrite) CGFloat offsetThreshold; +@property (nonatomic, assign, readwrite) CGFloat lastWidth; +@property (nonatomic, assign, readwrite) CGFloat colWidth; +@property (nonatomic, assign, readwrite) NSInteger numCols; +@property (nonatomic, assign) UIInterfaceOrientation orientation; + +@property (nonatomic, strong) NSMutableDictionary *reuseableViews; +@property (nonatomic, strong) NSMutableDictionary *visibleViews; +@property (nonatomic, strong) NSMutableArray *viewKeysToRemove; +@property (nonatomic, strong) NSMutableDictionary *indexToRectMap; + + +/** + Forces a relayout of the collection grid + */ +- (void)relayoutViews; + +/** + Stores a view for later reuse + TODO: add an identifier like UITableView + */ +- (void)enqueueReusableView:(PSCollectionViewCell *)view; + +/** + Magic! + */ +- (void)removeAndAddCellsIfNecessary; + +@end + +@implementation PSCollectionView + +#pragma mark - Init/Memory + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.alwaysBounceVertical = YES; + + self.lastOffset = 0.0; + self.offsetThreshold = floorf(self.height / 4.0); + + self.colWidth = 0.0; + self.numCols = 0; + self.numColsPortrait = 0; + self.numColsLandscape = 0; + self.orientation = [UIApplication sharedApplication].statusBarOrientation; + + self.reuseableViews = [NSMutableDictionary dictionary]; + self.visibleViews = [NSMutableDictionary dictionary]; + self.viewKeysToRemove = [NSMutableArray array]; + self.indexToRectMap = [NSMutableDictionary dictionary]; + } + return self; +} + +- (void)dealloc { + // clear delegates + self.delegate = nil; + self.collectionViewDataSource = nil; + self.collectionViewDelegate = nil; +} + +#pragma mark - DataSource + +- (void)reloadData { + [self relayoutViews]; +} + +#pragma mark - View + +- (void)layoutSubviews { + [super layoutSubviews]; + + UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; + + if (self.orientation != orientation) { + self.orientation = orientation; + // Recalculates layout + [self relayoutViews]; + } else if(self.lastWidth != self.width) { + // Recalculates layout + [self relayoutViews]; + } else { + // Recycles cells + CGFloat diff = fabsf(self.lastOffset - self.contentOffset.y); + + if (diff > self.offsetThreshold) { + self.lastOffset = self.contentOffset.y; + + [self removeAndAddCellsIfNecessary]; + } + } + + self.lastWidth = self.width; +} + +- (void)relayoutViews { + self.numCols = UIInterfaceOrientationIsPortrait(self.orientation) ? self.numColsPortrait : self.numColsLandscape; + + // Reset all state + [self.visibleViews enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + PSCollectionViewCell *view = (PSCollectionViewCell *)obj; + [self enqueueReusableView:view]; + }]; + [self.visibleViews removeAllObjects]; + [self.viewKeysToRemove removeAllObjects]; + [self.indexToRectMap removeAllObjects]; + + // This is where we should layout the entire grid first + NSInteger numViews = [self.collectionViewDataSource numberOfRowsInCollectionView:self]; + + CGFloat totalHeight = 0.0; + CGFloat top = kMargin; + + // Add headerView if it exists + if (self.headerView) { + top = self.headerView.top; + self.headerView.width = self.width; + [self addSubview:self.headerView]; + top += self.headerView.height; + } + + if (numViews > 0) { + // This array determines the last height offset on a column + NSMutableArray *colOffsets = [NSMutableArray arrayWithCapacity:self.numCols]; + for (int i = 0; i < self.numCols; i++) { + [colOffsets addObject:[NSNumber numberWithFloat:top]]; + } + + // Calculate index to rect mapping + self.colWidth = floorf((self.width - kMargin * (self.numCols + 1)) / self.numCols); + for (NSInteger i = 0; i < numViews; i++) { + NSString *key = PSCollectionKeyForIndex(i); + + // Find the shortest column + NSInteger col = 0; + CGFloat minHeight = [[colOffsets objectAtIndex:col] floatValue]; + for (int i = 1; i < [colOffsets count]; i++) { + CGFloat colHeight = [[colOffsets objectAtIndex:i] floatValue]; + + if (colHeight < minHeight) { + col = i; + minHeight = colHeight; + } + } + + CGFloat left = kMargin + (col * kMargin) + (col * self.colWidth); + CGFloat top = [[colOffsets objectAtIndex:col] floatValue]; + CGFloat colHeight = [self.collectionViewDataSource collectionView:self heightForRowAtIndex:i]; + + CGRect viewRect = CGRectMake(left, top, self.colWidth, colHeight); + + // Add to index rect map + [self.indexToRectMap setObject:NSStringFromCGRect(viewRect) forKey:key]; + + // Update the last height offset for this column + CGFloat heightOffset = colHeight > 0 ? top + colHeight + kMargin : top; + + [colOffsets replaceObjectAtIndex:col withObject:[NSNumber numberWithFloat:heightOffset]]; + } + + for (NSNumber *colHeight in colOffsets) { + totalHeight = (totalHeight < [colHeight floatValue]) ? [colHeight floatValue] : totalHeight; + } + } else { + totalHeight = self.height; + } + + // Add footerView if exists + if (self.footerView) { + self.footerView.top = totalHeight; + self.footerView.width = self.width; + [self addSubview:self.footerView]; + totalHeight += self.footerView.height; + } + + self.contentSize = CGSizeMake(self.width, totalHeight); + + [self removeAndAddCellsIfNecessary]; + + [[NSNotificationCenter defaultCenter] postNotificationName:kPSCollectionViewDidRelayoutNotification object:self]; +} + +- (void)removeAndAddCellsIfNecessary { + static NSInteger bufferViewFactor = 8; + static NSInteger topIndex = 0; + static NSInteger bottomIndex = 0; + + NSInteger numViews = [self.collectionViewDataSource numberOfRowsInCollectionView:self]; + + if (numViews == 0) return; + + // NSLog(@"diff: %f, lastOffset: %f", diff, self.lastOffset); + + // Find out what rows are visible + CGRect visibleRect = CGRectMake(self.contentOffset.x, self.contentOffset.y, self.width, self.height); + visibleRect = CGRectInset(visibleRect, 0, -1.0 * self.offsetThreshold); + + // Remove all rows that are not inside the visible rect + [self.visibleViews enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + PSCollectionViewCell *view = (PSCollectionViewCell *)obj; + CGRect viewRect = view.frame; + if (!CGRectIntersectsRect(visibleRect, viewRect)) { + [self enqueueReusableView:view]; + [self.viewKeysToRemove addObject:key]; + } + }]; + + [self.visibleViews removeObjectsForKeys:self.viewKeysToRemove]; + [self.viewKeysToRemove removeAllObjects]; + + if ([self.visibleViews count] == 0) { + topIndex = 0; + bottomIndex = numViews; + } else { + NSArray *sortedKeys = [[self.visibleViews allKeys] sortedArrayUsingComparator:^(id obj1, id obj2) { + if ([obj1 integerValue] < [obj2 integerValue]) { + return (NSComparisonResult)NSOrderedAscending; + } else if ([obj1 integerValue] > [obj2 integerValue]) { + return (NSComparisonResult)NSOrderedDescending; + } else { + return (NSComparisonResult)NSOrderedSame; + } + }]; + topIndex = [[sortedKeys objectAtIndex:0] integerValue]; + bottomIndex = [[sortedKeys lastObject] integerValue]; + + topIndex = MAX(0, topIndex - (bufferViewFactor * self.numCols)); + bottomIndex = MIN(numViews, bottomIndex + (bufferViewFactor * self.numCols)); + } + // NSLog(@"topIndex: %d, bottomIndex: %d", topIndex, bottomIndex); + + // Add views + for (NSInteger i = topIndex; i < bottomIndex; i++) { + NSString *key = PSCollectionKeyForIndex(i); + CGRect rect = CGRectFromString([self.indexToRectMap objectForKey:key]); + + // If view is within visible rect and is not already shown + if (![self.visibleViews objectForKey:key] && CGRectIntersectsRect(visibleRect, rect)) { + // Only add views if not visible + PSCollectionViewCell *newCell = [self.collectionViewDataSource collectionView:self cellForRowAtIndex:i]; + newCell.frame = CGRectFromString([self.indexToRectMap objectForKey:key]); + [self addSubview:newCell]; + + // Setup gesture recognizer + if ([newCell.gestureRecognizers count] == 0) { + PSCollectionViewTapGestureRecognizer *gr = [[PSCollectionViewTapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectView:)]; + gr.delegate = self; + [newCell addGestureRecognizer:gr]; + newCell.userInteractionEnabled = YES; + } + + [self.visibleViews setObject:newCell forKey:key]; + } + } +} + +#pragma mark - Reusing Views + +- (PSCollectionViewCell *)dequeueReusableViewForClass:(Class)viewClass { + NSString *identifier = NSStringFromClass(viewClass); + + PSCollectionViewCell *view = nil; + if ([self.reuseableViews objectForKey:identifier]) { + view = [[self.reuseableViews objectForKey:identifier] anyObject]; + + if (view) { + // Found a reusable view, remove it from the set + [[self.reuseableViews objectForKey:identifier] removeObject:view]; + } + } + + return view; +} + +- (void)enqueueReusableView:(PSCollectionViewCell *)view { + if ([view respondsToSelector:@selector(prepareForReuse)]) { + [view performSelector:@selector(prepareForReuse)]; + } + view.frame = CGRectZero; + + NSString *identifier = NSStringFromClass([view class]); + if (![self.reuseableViews objectForKey:identifier]) { + [self.reuseableViews setObject:[NSMutableSet set] forKey:identifier]; + } + + [[self.reuseableViews objectForKey:identifier] addObject:view]; + + [view removeFromSuperview]; +} + +#pragma mark - Gesture Recognizer + +- (void)didSelectView:(UITapGestureRecognizer *)gestureRecognizer { + NSString *rectString = NSStringFromCGRect(gestureRecognizer.view.frame); + NSArray *matchingKeys = [self.indexToRectMap allKeysForObject:rectString]; + NSString *key = [matchingKeys lastObject]; + if ([gestureRecognizer.view isMemberOfClass:[[self.visibleViews objectForKey:key] class]]) { + if (self.collectionViewDelegate && [self.collectionViewDelegate respondsToSelector:@selector(collectionView:didSelectCell:atIndex:)]) { + NSInteger matchingIndex = PSCollectionIndexForKey([matchingKeys lastObject]); + [self.collectionViewDelegate collectionView:self didSelectCell:(PSCollectionViewCell *)gestureRecognizer.view atIndex:matchingIndex]; + } + } +} + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { + if (![gestureRecognizer isMemberOfClass:[PSCollectionViewTapGestureRecognizer class]]) return YES; + + NSString *rectString = NSStringFromCGRect(gestureRecognizer.view.frame); + NSArray *matchingKeys = [self.indexToRectMap allKeysForObject:rectString]; + NSString *key = [matchingKeys lastObject]; + + if ([touch.view isMemberOfClass:[[self.visibleViews objectForKey:key] class]]) { + return YES; + } else { + return NO; + } +} + +@end diff --git a/PSCollectionViewDemo/PSCollectionViewCell.h b/PSCollectionViewDemo/PSCollectionViewCell.h new file mode 100644 index 0000000..ef8d28c --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionViewCell.h @@ -0,0 +1,38 @@ +// +// PSCollectionViewCell.h +// +// Copyright (c) 2012 Peter Shih (http://petershih.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. + +#import + +@class PSCollectionView; + +@interface PSCollectionViewCell : UIView + +@property (nonatomic, strong) id object; +@property (nonatomic, weak) PSCollectionView *collectionView; +@property (nonatomic, assign) NSInteger index; + +- (void)prepareForReuse; +- (void)collectionView:(PSCollectionView *)collectionView fillCellWithObject:(id)object atIndex:(NSInteger)index; ++ (CGFloat)rowHeightForObject:(id)object inColumnWidth:(CGFloat)columnWidth; + +@end diff --git a/PSCollectionViewDemo/PSCollectionViewCell.m b/PSCollectionViewDemo/PSCollectionViewCell.m new file mode 100644 index 0000000..6b7d8c4 --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionViewCell.m @@ -0,0 +1,53 @@ +// +// PSCollectionViewCell.m +// +// Copyright (c) 2012 Peter Shih (http://petershih.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. + +#import "PSCollectionViewCell.h" + +@interface PSCollectionViewCell () + +@end + +@implementation PSCollectionViewCell + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + } + return self; +} + + +- (void)prepareForReuse { +} + +- (void)collectionView:(PSCollectionView *)collectionView fillCellWithObject:(id)object atIndex:(NSInteger)index { + self.collectionView = collectionView; + self.object = object; + self.index = index; +} + ++ (CGFloat)rowHeightForObject:(id)object inColumnWidth:(CGFloat)columnWidth { + return 0.0; +} + +@end diff --git a/PSCollectionViewDemo/PSCollectionViewDemo-Info.plist b/PSCollectionViewDemo/PSCollectionViewDemo-Info.plist new file mode 100644 index 0000000..b2a93fc --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionViewDemo-Info.plist @@ -0,0 +1,38 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${PRODUCT_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + opomelo.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch b/PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch new file mode 100644 index 0000000..039113b --- /dev/null +++ b/PSCollectionViewDemo/PSCollectionViewDemo-Prefix.pch @@ -0,0 +1,14 @@ +// +// Prefix header for all source files of the 'PSCollectionViewDemo' target in the 'PSCollectionViewDemo' project +// + +#import + +#ifndef __IPHONE_4_0 +#warning "This project uses features only available in iOS SDK 4.0 and later." +#endif + +#ifdef __OBJC__ + #import + #import +#endif diff --git a/PSCollectionViewDemo/Reachability/Reachability.h b/PSCollectionViewDemo/Reachability/Reachability.h new file mode 100644 index 0000000..7e5c889 --- /dev/null +++ b/PSCollectionViewDemo/Reachability/Reachability.h @@ -0,0 +1,115 @@ +/* + Copyright (c) 2011, Tony Million. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ + +#import + +#import +#import +#import +#import +#import +#import + +/** + * Does ARC support support GCD objects? + * It does if the minimum deployment target is iOS 6+ or Mac OS X 8+ + **/ +#if TARGET_OS_IPHONE + +// Compiling for iOS + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 // iOS 6.0 or later +#define NEEDS_DISPATCH_RETAIN_RELEASE 0 +#else // iOS 5.X or earlier +#define NEEDS_DISPATCH_RETAIN_RELEASE 1 +#endif + +#else + +// Compiling for Mac OS X + +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 // Mac OS X 10.8 or later +#define NEEDS_DISPATCH_RETAIN_RELEASE 0 +#else +#define NEEDS_DISPATCH_RETAIN_RELEASE 1 // Mac OS X 10.7 or earlier +#endif + +#endif + + +extern NSString *const kReachabilityChangedNotification; + +typedef enum +{ + // Apple NetworkStatus Compatible Names. + NotReachable = 0, + ReachableViaWiFi = 2, + ReachableViaWWAN = 1 +} NetworkStatus; + +@class Reachability; + +typedef void (^NetworkReachable)(Reachability * reachability); +typedef void (^NetworkUnreachable)(Reachability * reachability); + +@interface Reachability : NSObject + +@property (nonatomic, copy) NetworkReachable reachableBlock; +@property (nonatomic, copy) NetworkUnreachable unreachableBlock; + + +@property (nonatomic, assign) BOOL reachableOnWWAN; + ++(Reachability*)reachabilityWithHostname:(NSString*)hostname; ++(Reachability*)reachabilityForInternetConnection; ++(Reachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; ++(Reachability*)reachabilityForLocalWiFi; + +-(Reachability *)initWithReachabilityRef:(SCNetworkReachabilityRef)ref; + +-(BOOL)startNotifier; +-(void)stopNotifier; + +-(BOOL)isReachable; +-(BOOL)isReachableViaWWAN; +-(BOOL)isReachableViaWiFi; + +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +-(BOOL)isConnectionRequired; // Identical DDG variant. +-(BOOL)connectionRequired; // Apple's routine. +// Dynamic, on demand connection? +-(BOOL)isConnectionOnDemand; +// Is user intervention required? +-(BOOL)isInterventionRequired; + +-(NetworkStatus)currentReachabilityStatus; +-(SCNetworkReachabilityFlags)reachabilityFlags; +-(NSString*)currentReachabilityString; +-(NSString*)currentReachabilityFlags; + +@end diff --git a/PSCollectionViewDemo/Reachability/Reachability.m b/PSCollectionViewDemo/Reachability/Reachability.m new file mode 100644 index 0000000..c423c9b --- /dev/null +++ b/PSCollectionViewDemo/Reachability/Reachability.m @@ -0,0 +1,492 @@ +/* + Copyright (c) 2011, Tony Million. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ + +#import "Reachability.h" + + +NSString *const kReachabilityChangedNotification = @"kReachabilityChangedNotification"; + +@interface Reachability () + +@property (nonatomic, assign) SCNetworkReachabilityRef reachabilityRef; + + +#if NEEDS_DISPATCH_RETAIN_RELEASE +@property (nonatomic, assign) dispatch_queue_t reachabilitySerialQueue; +#else +@property (nonatomic, strong) dispatch_queue_t reachabilitySerialQueue; +#endif + + +@property (nonatomic, strong) id reachabilityObject; + +-(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags; +-(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags; + +@end + +static NSString *reachabilityFlags(SCNetworkReachabilityFlags flags) +{ + return [NSString stringWithFormat:@"%c%c %c%c%c%c%c%c%c", +#if TARGET_OS_IPHONE + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', +#else + 'X', +#endif + (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', + (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', + (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', + (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', + (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-']; +} + +//Start listening for reachability notifications on the current run loop +static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) +{ +#pragma unused (target) + Reachability *reachability = ((__bridge Reachability*)info); + + // we probably dont need an autoreleasepool here as GCD docs state each queue has its own autorelease pool + // but what the heck eh? + @autoreleasepool + { + [reachability reachabilityChanged:flags]; + } +} + + +@implementation Reachability + +#pragma mark - class constructor methods ++(Reachability*)reachabilityWithHostname:(NSString*)hostname +{ + SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(NULL, [hostname UTF8String]); + if (ref) + { + id reachability = [[self alloc] initWithReachabilityRef:ref]; + +#if __has_feature(objc_arc) + return reachability; +#else + return [reachability autorelease]; +#endif + + } + + return nil; +} + ++(Reachability *)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress +{ + SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); + if (ref) + { + id reachability = [[self alloc] initWithReachabilityRef:ref]; + +#if __has_feature(objc_arc) + return reachability; +#else + return [reachability autorelease]; +#endif + } + + return nil; +} + ++(Reachability *)reachabilityForInternetConnection +{ + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + + return [self reachabilityWithAddress:&zeroAddress]; +} + ++(Reachability*)reachabilityForLocalWiFi +{ + struct sockaddr_in localWifiAddress; + bzero(&localWifiAddress, sizeof(localWifiAddress)); + localWifiAddress.sin_len = sizeof(localWifiAddress); + localWifiAddress.sin_family = AF_INET; + // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 + localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); + + return [self reachabilityWithAddress:&localWifiAddress]; +} + + +// initialization methods + +-(Reachability *)initWithReachabilityRef:(SCNetworkReachabilityRef)ref +{ + self = [super init]; + if (self != nil) + { + self.reachableOnWWAN = YES; + self.reachabilityRef = ref; + } + + return self; +} + +-(void)dealloc +{ + [self stopNotifier]; + + if(self.reachabilityRef) + { + CFRelease(self.reachabilityRef); + self.reachabilityRef = nil; + } + +#if !(__has_feature(objc_arc)) + [super dealloc]; +#endif + + +} + +#pragma mark - notifier methods + +// Notifier +// NOTE: this uses GCD to trigger the blocks - they *WILL NOT* be called on THE MAIN THREAD +// - In other words DO NOT DO ANY UI UPDATES IN THE BLOCKS. +// INSTEAD USE dispatch_async(dispatch_get_main_queue(), ^{UISTUFF}) (or dispatch_sync if you want) + +-(BOOL)startNotifier +{ + SCNetworkReachabilityContext context = { 0, NULL, NULL, NULL, NULL }; + + // this should do a retain on ourself, so as long as we're in notifier mode we shouldn't disappear out from under ourselves + // woah + self.reachabilityObject = self; + + + + // first we need to create a serial queue + // we allocate this once for the lifetime of the notifier + self.reachabilitySerialQueue = dispatch_queue_create("com.tonymillion.reachability", NULL); + if(!self.reachabilitySerialQueue) + { + return NO; + } + + + context.info = (__bridge void *)self; + + if (!SCNetworkReachabilitySetCallback(self.reachabilityRef, TMReachabilityCallback, &context)) + { +#ifdef DEBUG + NSLog(@"SCNetworkReachabilitySetCallback() failed: %s", SCErrorString(SCError())); +#endif + + //clear out the dispatch queue + if(self.reachabilitySerialQueue) + { +#if NEEDS_DISPATCH_RETAIN_RELEASE + dispatch_release(self.reachabilitySerialQueue); +#endif + self.reachabilitySerialQueue = nil; + } + + self.reachabilityObject = nil; + + return NO; + } + + // set it as our reachability queue which will retain the queue + if(!SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, self.reachabilitySerialQueue)) + { +#ifdef DEBUG + NSLog(@"SCNetworkReachabilitySetDispatchQueue() failed: %s", SCErrorString(SCError())); +#endif + + //UH OH - FAILURE! + + // first stop any callbacks! + SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL); + + // then clear out the dispatch queue + if(self.reachabilitySerialQueue) + { +#if NEEDS_DISPATCH_RETAIN_RELEASE + dispatch_release(self.reachabilitySerialQueue); +#endif + self.reachabilitySerialQueue = nil; + } + + self.reachabilityObject = nil; + + return NO; + } + + return YES; +} + +-(void)stopNotifier +{ + // first stop any callbacks! + SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL); + + // unregister target from the GCD serial dispatch queue + SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, NULL); + + if(self.reachabilitySerialQueue) + { +#if NEEDS_DISPATCH_RETAIN_RELEASE + dispatch_release(self.reachabilitySerialQueue); +#endif + self.reachabilitySerialQueue = nil; + } + + self.reachabilityObject = nil; +} + +#pragma mark - reachability tests + +// this is for the case where you flick the airplane mode +// you end up getting something like this: +//Reachability: WR ct----- +//Reachability: -- ------- +//Reachability: WR ct----- +//Reachability: -- ------- +// we treat this as 4 UNREACHABLE triggers - really apple should do better than this + +#define testcase (kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection) + +-(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags +{ + BOOL connectionUP = YES; + + if(!(flags & kSCNetworkReachabilityFlagsReachable)) + connectionUP = NO; + + if( (flags & testcase) == testcase ) + connectionUP = NO; + +#if TARGET_OS_IPHONE + if(flags & kSCNetworkReachabilityFlagsIsWWAN) + { + // we're on 3G + if(!self.reachableOnWWAN) + { + // we dont want to connect when on 3G + connectionUP = NO; + } + } +#endif + + return connectionUP; +} + +-(BOOL)isReachable +{ + SCNetworkReachabilityFlags flags; + + if(!SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + return NO; + + return [self isReachableWithFlags:flags]; +} + +-(BOOL)isReachableViaWWAN +{ +#if TARGET_OS_IPHONE + + SCNetworkReachabilityFlags flags = 0; + + if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + // check we're REACHABLE + if(flags & kSCNetworkReachabilityFlagsReachable) + { + // now, check we're on WWAN + if(flags & kSCNetworkReachabilityFlagsIsWWAN) + { + return YES; + } + } + } +#endif + + return NO; +} + +-(BOOL)isReachableViaWiFi +{ + SCNetworkReachabilityFlags flags = 0; + + if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + // check we're reachable + if((flags & kSCNetworkReachabilityFlagsReachable)) + { +#if TARGET_OS_IPHONE + // check we're NOT on WWAN + if((flags & kSCNetworkReachabilityFlagsIsWWAN)) + { + return NO; + } +#endif + return YES; + } + } + + return NO; +} + + +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +-(BOOL)isConnectionRequired +{ + return [self connectionRequired]; +} + +-(BOOL)connectionRequired +{ + SCNetworkReachabilityFlags flags; + + if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + return (flags & kSCNetworkReachabilityFlagsConnectionRequired); + } + + return NO; +} + +// Dynamic, on demand connection? +-(BOOL)isConnectionOnDemand +{ + SCNetworkReachabilityFlags flags; + + if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) && + (flags & (kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand))); + } + + return NO; +} + +// Is user intervention required? +-(BOOL)isInterventionRequired +{ + SCNetworkReachabilityFlags flags; + + if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) && + (flags & kSCNetworkReachabilityFlagsInterventionRequired)); + } + + return NO; +} + + +#pragma mark - reachability status stuff + +-(NetworkStatus)currentReachabilityStatus +{ + if([self isReachable]) + { + if([self isReachableViaWiFi]) + return ReachableViaWiFi; + +#if TARGET_OS_IPHONE + return ReachableViaWWAN; +#endif + } + + return NotReachable; +} + +-(SCNetworkReachabilityFlags)reachabilityFlags +{ + SCNetworkReachabilityFlags flags = 0; + + if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags)) + { + return flags; + } + + return 0; +} + +-(NSString*)currentReachabilityString +{ + NetworkStatus temp = [self currentReachabilityStatus]; + + if(temp == self.reachableOnWWAN) + { + // updated for the fact we have CDMA phones now! + return NSLocalizedString(@"Cellular", @""); + } + if (temp == ReachableViaWiFi) + { + return NSLocalizedString(@"WiFi", @""); + } + + return NSLocalizedString(@"No Connection", @""); +} + +-(NSString*)currentReachabilityFlags +{ + return reachabilityFlags([self reachabilityFlags]); +} + +#pragma mark - callback function calls this method + +-(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags +{ + if([self isReachableWithFlags:flags]) + { + if(self.reachableBlock) + { + self.reachableBlock(self); + } + } + else + { + if(self.unreachableBlock) + { + self.unreachableBlock(self); + } + } + + // this makes sure the change notification happens on the MAIN THREAD + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification + object:self]; + }); +} + +@end diff --git a/PSCollectionViewDemo/ViewController.h b/PSCollectionViewDemo/ViewController.h new file mode 100644 index 0000000..de581dc --- /dev/null +++ b/PSCollectionViewDemo/ViewController.h @@ -0,0 +1,13 @@ +// +// ViewController.h +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import + +@interface ViewController : UIViewController + +@end diff --git a/PSCollectionViewDemo/ViewController.m b/PSCollectionViewDemo/ViewController.m new file mode 100644 index 0000000..dbb9b41 --- /dev/null +++ b/PSCollectionViewDemo/ViewController.m @@ -0,0 +1,29 @@ +// +// ViewController.m +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import "ViewController.h" + +@interface ViewController () + +@end + +@implementation ViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + // Do any additional setup after loading the view, typically from a nib. +} + +- (void)didReceiveMemoryWarning +{ + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +@end diff --git a/PSCollectionViewDemo/en.lproj/InfoPlist.strings b/PSCollectionViewDemo/en.lproj/InfoPlist.strings new file mode 100644 index 0000000..477b28f --- /dev/null +++ b/PSCollectionViewDemo/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/PSCollectionViewDemo/en.lproj/ViewController.xib b/PSCollectionViewDemo/en.lproj/ViewController.xib new file mode 100644 index 0000000..18825b5 --- /dev/null +++ b/PSCollectionViewDemo/en.lproj/ViewController.xib @@ -0,0 +1,138 @@ + + + + 1536 + 12A269 + 2835 + 1187 + 624.00 + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + 1919 + + + IBProxyObject + IBUIView + + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + + PluginDependencyRecalculationVersion + + + + + IBFilesOwner + IBCocoaTouchFramework + + + IBFirstResponder + IBCocoaTouchFramework + + + + 274 + {{0, 20}, {320, 548}} + + + + + 3 + MC43NQA + + 2 + + + NO + + + IBUIScreenMetrics + + YES + + + + + + {320, 568} + {568, 320} + + + IBCocoaTouchFramework + Retina 4 Full Screen + 2 + + IBCocoaTouchFramework + + + + + + + view + + + + 7 + + + + + + 0 + + + + + + -1 + + + File's Owner + + + -2 + + + + + 6 + + + + + + + ViewController + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + UIResponder + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + + + + + 7 + + + + + ViewController + UIViewController + + IBProjectSource + ./Classes/ViewController.h + + + + + 0 + IBCocoaTouchFramework + YES + 3 + YES + 1919 + + diff --git a/PSCollectionViewDemo/main.m b/PSCollectionViewDemo/main.m new file mode 100644 index 0000000..621c645 --- /dev/null +++ b/PSCollectionViewDemo/main.m @@ -0,0 +1,18 @@ +// +// main.m +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import + +#import "AppDelegate.h" + +int main(int argc, char *argv[]) +{ + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} From 9e2fb74f5227cf72fb08437a661ba39b87d719da Mon Sep 17 00:00:00 2001 From: Sean-Wang Date: Thu, 18 Apr 2013 13:38:37 +0800 Subject: [PATCH 2/2] Add a Demo app for PSCollectionView and fix PSCollectionView bug. --- .../project.pbxproj | 122 + PSCollectionViewDemo/AppDelegate.h | 9 +- PSCollectionViewDemo/AppDelegate.m | 15 + PSCollectionViewDemo/JSONKit/CHANGELOG.md | 389 +++ PSCollectionViewDemo/JSONKit/JSONKit.h | 251 ++ PSCollectionViewDemo/JSONKit/JSONKit.m | 3065 +++++++++++++++++ PSCollectionViewDemo/JSONKit/README.md | 310 ++ PSCollectionViewDemo/PSCollectionViewCell.m | 3 +- .../SDWebImage/MKAnnotationView+WebCache.h | 95 + .../SDWebImage/MKAnnotationView+WebCache.m | 78 + .../SDWebImage/SDImageCache.h | 144 + .../SDWebImage/SDImageCache.m | 314 ++ .../SDWebImage/SDWebImageCompat.h | 40 + .../SDWebImage/SDWebImageCompat.m | 54 + .../SDWebImage/SDWebImageDecoder.h | 18 + .../SDWebImage/SDWebImageDecoder.m | 70 + .../SDWebImage/SDWebImageDownloader.h | 102 + .../SDWebImage/SDWebImageDownloader.m | 226 ++ .../SDWebImageDownloaderOperation.h | 25 + .../SDWebImageDownloaderOperation.m | 339 ++ .../SDWebImage/SDWebImageManager.h | 167 + .../SDWebImage/SDWebImageManager.m | 244 ++ .../SDWebImage/SDWebImageOperation.h | 15 + .../SDWebImage/SDWebImagePrefetcher.h | 58 + .../SDWebImage/SDWebImagePrefetcher.m | 127 + .../SDWebImage/UIButton+WebCache.h | 173 + .../SDWebImage/UIButton+WebCache.m | 129 + .../SDWebImage/UIImageView+WebCache.h | 140 + .../SDWebImage/UIImageView+WebCache.m | 84 + PSCollectionViewDemo/ViewController.h | 9 +- PSCollectionViewDemo/ViewController.m | 78 + PSCollectionViewDemo/WaterflowViewCell.h | 18 + PSCollectionViewDemo/WaterflowViewCell.m | 135 + 33 files changed, 7043 insertions(+), 3 deletions(-) create mode 100644 PSCollectionViewDemo/JSONKit/CHANGELOG.md create mode 100644 PSCollectionViewDemo/JSONKit/JSONKit.h create mode 100644 PSCollectionViewDemo/JSONKit/JSONKit.m create mode 100644 PSCollectionViewDemo/JSONKit/README.md create mode 100644 PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.h create mode 100644 PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDImageCache.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDImageCache.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageCompat.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageCompat.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageManager.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageManager.m create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImageOperation.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.h create mode 100644 PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.m create mode 100644 PSCollectionViewDemo/SDWebImage/UIButton+WebCache.h create mode 100644 PSCollectionViewDemo/SDWebImage/UIButton+WebCache.m create mode 100644 PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.h create mode 100644 PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.m create mode 100644 PSCollectionViewDemo/WaterflowViewCell.h create mode 100644 PSCollectionViewDemo/WaterflowViewCell.m diff --git a/PSCollectionViewDemo.xcodeproj/project.pbxproj b/PSCollectionViewDemo.xcodeproj/project.pbxproj index a3204fb..30381e8 100644 --- a/PSCollectionViewDemo.xcodeproj/project.pbxproj +++ b/PSCollectionViewDemo.xcodeproj/project.pbxproj @@ -29,6 +29,26 @@ 8A35E187171F911400F4D64C /* MKNetworkEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E17A171F911400F4D64C /* MKNetworkEngine.m */; }; 8A35E188171F911400F4D64C /* MKNetworkOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E17D171F911400F4D64C /* MKNetworkOperation.m */; }; 8A35E189171F911400F4D64C /* Reachability.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E180171F911400F4D64C /* Reachability.m */; }; + 8A35E18F171F98E100F4D64C /* CHANGELOG.md in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E18B171F98E100F4D64C /* CHANGELOG.md */; }; + 8A35E190171F98E100F4D64C /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E18D171F98E100F4D64C /* JSONKit.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 8A35E191171F98E100F4D64C /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = 8A35E18E171F98E100F4D64C /* README.md */; }; + 8A35E194171F996600F4D64C /* WaterflowViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E193171F996500F4D64C /* WaterflowViewCell.m */; }; + 8A35E1AB171F9CB600F4D64C /* MKAnnotationView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E197171F9CB600F4D64C /* MKAnnotationView+WebCache.m */; }; + 8A35E1AC171F9CB600F4D64C /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E199171F9CB600F4D64C /* SDImageCache.m */; }; + 8A35E1AD171F9CB600F4D64C /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E19B171F9CB600F4D64C /* SDWebImageCompat.m */; }; + 8A35E1AE171F9CB600F4D64C /* SDWebImageDecoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E19D171F9CB600F4D64C /* SDWebImageDecoder.m */; }; + 8A35E1AF171F9CB600F4D64C /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E19F171F9CB600F4D64C /* SDWebImageDownloader.m */; }; + 8A35E1B0171F9CB600F4D64C /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E1A1171F9CB600F4D64C /* SDWebImageDownloaderOperation.m */; }; + 8A35E1B1171F9CB600F4D64C /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E1A3171F9CB600F4D64C /* SDWebImageManager.m */; }; + 8A35E1B2171F9CB600F4D64C /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E1A6171F9CB600F4D64C /* SDWebImagePrefetcher.m */; }; + 8A35E1B3171F9CB600F4D64C /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E1A8171F9CB600F4D64C /* UIButton+WebCache.m */; }; + 8A35E1B4171F9CB600F4D64C /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A35E1AA171F9CB600F4D64C /* UIImageView+WebCache.m */; }; + 8A35E1B6171F9DA600F4D64C /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1B5171F9DA600F4D64C /* ImageIO.framework */; }; + 8A35E1B8171F9DC200F4D64C /* MapKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1B7171F9DC200F4D64C /* MapKit.framework */; }; + 8A35E1BA171F9DD300F4D64C /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1B9171F9DD300F4D64C /* CFNetwork.framework */; }; + 8A35E1BC171F9E1D00F4D64C /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1BB171F9E1D00F4D64C /* SystemConfiguration.framework */; }; + 8A35E1BE171F9E5500F4D64C /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1BD171F9E5500F4D64C /* Security.framework */; }; + 8A35E1C0171FB9B700F4D64C /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A35E1BF171FB9B700F4D64C /* QuartzCore.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -71,6 +91,39 @@ 8A35E17D171F911400F4D64C /* MKNetworkOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MKNetworkOperation.m; sourceTree = ""; }; 8A35E17F171F911400F4D64C /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Reachability.h; sourceTree = ""; }; 8A35E180171F911400F4D64C /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Reachability.m; sourceTree = ""; }; + 8A35E18B171F98E100F4D64C /* CHANGELOG.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CHANGELOG.md; sourceTree = ""; }; + 8A35E18C171F98E100F4D64C /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; + 8A35E18D171F98E100F4D64C /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; + 8A35E18E171F98E100F4D64C /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.md; sourceTree = ""; }; + 8A35E192171F996500F4D64C /* WaterflowViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WaterflowViewCell.h; sourceTree = ""; }; + 8A35E193171F996500F4D64C /* WaterflowViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WaterflowViewCell.m; sourceTree = ""; }; + 8A35E196171F9CB600F4D64C /* MKAnnotationView+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MKAnnotationView+WebCache.h"; sourceTree = ""; }; + 8A35E197171F9CB600F4D64C /* MKAnnotationView+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "MKAnnotationView+WebCache.m"; sourceTree = ""; }; + 8A35E198171F9CB600F4D64C /* SDImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDImageCache.h; sourceTree = ""; }; + 8A35E199171F9CB600F4D64C /* SDImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDImageCache.m; sourceTree = ""; }; + 8A35E19A171F9CB600F4D64C /* SDWebImageCompat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageCompat.h; sourceTree = ""; }; + 8A35E19B171F9CB600F4D64C /* SDWebImageCompat.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageCompat.m; sourceTree = ""; }; + 8A35E19C171F9CB600F4D64C /* SDWebImageDecoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDecoder.h; sourceTree = ""; }; + 8A35E19D171F9CB600F4D64C /* SDWebImageDecoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDecoder.m; sourceTree = ""; }; + 8A35E19E171F9CB600F4D64C /* SDWebImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloader.h; sourceTree = ""; }; + 8A35E19F171F9CB600F4D64C /* SDWebImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloader.m; sourceTree = ""; }; + 8A35E1A0171F9CB600F4D64C /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageDownloaderOperation.h; sourceTree = ""; }; + 8A35E1A1171F9CB600F4D64C /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageDownloaderOperation.m; sourceTree = ""; }; + 8A35E1A2171F9CB600F4D64C /* SDWebImageManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageManager.h; sourceTree = ""; }; + 8A35E1A3171F9CB600F4D64C /* SDWebImageManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImageManager.m; sourceTree = ""; }; + 8A35E1A4171F9CB600F4D64C /* SDWebImageOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImageOperation.h; sourceTree = ""; }; + 8A35E1A5171F9CB600F4D64C /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDWebImagePrefetcher.h; sourceTree = ""; }; + 8A35E1A6171F9CB600F4D64C /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDWebImagePrefetcher.m; sourceTree = ""; }; + 8A35E1A7171F9CB600F4D64C /* UIButton+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+WebCache.h"; sourceTree = ""; }; + 8A35E1A8171F9CB600F4D64C /* UIButton+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+WebCache.m"; sourceTree = ""; }; + 8A35E1A9171F9CB600F4D64C /* UIImageView+WebCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+WebCache.h"; sourceTree = ""; }; + 8A35E1AA171F9CB600F4D64C /* UIImageView+WebCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+WebCache.m"; sourceTree = ""; }; + 8A35E1B5171F9DA600F4D64C /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = System/Library/Frameworks/ImageIO.framework; sourceTree = SDKROOT; }; + 8A35E1B7171F9DC200F4D64C /* MapKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MapKit.framework; path = System/Library/Frameworks/MapKit.framework; sourceTree = SDKROOT; }; + 8A35E1B9171F9DD300F4D64C /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = System/Library/Frameworks/CFNetwork.framework; sourceTree = SDKROOT; }; + 8A35E1BB171F9E1D00F4D64C /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + 8A35E1BD171F9E5500F4D64C /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + 8A35E1BF171FB9B700F4D64C /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -78,6 +131,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8A35E1C0171FB9B700F4D64C /* QuartzCore.framework in Frameworks */, + 8A35E1BE171F9E5500F4D64C /* Security.framework in Frameworks */, + 8A35E1BC171F9E1D00F4D64C /* SystemConfiguration.framework in Frameworks */, + 8A35E1BA171F9DD300F4D64C /* CFNetwork.framework in Frameworks */, + 8A35E1B8171F9DC200F4D64C /* MapKit.framework in Frameworks */, + 8A35E1B6171F9DA600F4D64C /* ImageIO.framework in Frameworks */, 8A35E142171F8F0C00F4D64C /* UIKit.framework in Frameworks */, 8A35E144171F8F0C00F4D64C /* Foundation.framework in Frameworks */, 8A35E146171F8F0C00F4D64C /* CoreGraphics.framework in Frameworks */, @@ -90,6 +149,12 @@ 8A35E135171F8F0C00F4D64C = { isa = PBXGroup; children = ( + 8A35E1BF171FB9B700F4D64C /* QuartzCore.framework */, + 8A35E1BD171F9E5500F4D64C /* Security.framework */, + 8A35E1BB171F9E1D00F4D64C /* SystemConfiguration.framework */, + 8A35E1B9171F9DD300F4D64C /* CFNetwork.framework */, + 8A35E1B7171F9DC200F4D64C /* MapKit.framework */, + 8A35E1B5171F9DA600F4D64C /* ImageIO.framework */, 8A35E147171F8F0C00F4D64C /* PSCollectionViewDemo */, 8A35E140171F8F0C00F4D64C /* Frameworks */, 8A35E13F171F8F0C00F4D64C /* Products */, @@ -117,6 +182,8 @@ 8A35E147171F8F0C00F4D64C /* PSCollectionViewDemo */ = { isa = PBXGroup; children = ( + 8A35E195171F9CB600F4D64C /* SDWebImage */, + 8A35E18A171F98E100F4D64C /* JSONKit */, 8A35E16B171F902000F4D64C /* MKNetworkKit */, 8A35E164171F8FB400F4D64C /* PSCollectionView */, 8A35E150171F8F0C00F4D64C /* AppDelegate.h */, @@ -124,6 +191,8 @@ 8A35E159171F8F0C00F4D64C /* ViewController.h */, 8A35E15A171F8F0C00F4D64C /* ViewController.m */, 8A35E15C171F8F0D00F4D64C /* ViewController.xib */, + 8A35E192171F996500F4D64C /* WaterflowViewCell.h */, + 8A35E193171F996500F4D64C /* WaterflowViewCell.m */, 8A35E148171F8F0C00F4D64C /* Supporting Files */, ); path = PSCollectionViewDemo; @@ -196,6 +265,45 @@ path = Reachability; sourceTree = ""; }; + 8A35E18A171F98E100F4D64C /* JSONKit */ = { + isa = PBXGroup; + children = ( + 8A35E18B171F98E100F4D64C /* CHANGELOG.md */, + 8A35E18C171F98E100F4D64C /* JSONKit.h */, + 8A35E18D171F98E100F4D64C /* JSONKit.m */, + 8A35E18E171F98E100F4D64C /* README.md */, + ); + path = JSONKit; + sourceTree = ""; + }; + 8A35E195171F9CB600F4D64C /* SDWebImage */ = { + isa = PBXGroup; + children = ( + 8A35E196171F9CB600F4D64C /* MKAnnotationView+WebCache.h */, + 8A35E197171F9CB600F4D64C /* MKAnnotationView+WebCache.m */, + 8A35E198171F9CB600F4D64C /* SDImageCache.h */, + 8A35E199171F9CB600F4D64C /* SDImageCache.m */, + 8A35E19A171F9CB600F4D64C /* SDWebImageCompat.h */, + 8A35E19B171F9CB600F4D64C /* SDWebImageCompat.m */, + 8A35E19C171F9CB600F4D64C /* SDWebImageDecoder.h */, + 8A35E19D171F9CB600F4D64C /* SDWebImageDecoder.m */, + 8A35E19E171F9CB600F4D64C /* SDWebImageDownloader.h */, + 8A35E19F171F9CB600F4D64C /* SDWebImageDownloader.m */, + 8A35E1A0171F9CB600F4D64C /* SDWebImageDownloaderOperation.h */, + 8A35E1A1171F9CB600F4D64C /* SDWebImageDownloaderOperation.m */, + 8A35E1A2171F9CB600F4D64C /* SDWebImageManager.h */, + 8A35E1A3171F9CB600F4D64C /* SDWebImageManager.m */, + 8A35E1A4171F9CB600F4D64C /* SDWebImageOperation.h */, + 8A35E1A5171F9CB600F4D64C /* SDWebImagePrefetcher.h */, + 8A35E1A6171F9CB600F4D64C /* SDWebImagePrefetcher.m */, + 8A35E1A7171F9CB600F4D64C /* UIButton+WebCache.h */, + 8A35E1A8171F9CB600F4D64C /* UIButton+WebCache.m */, + 8A35E1A9171F9CB600F4D64C /* UIImageView+WebCache.h */, + 8A35E1AA171F9CB600F4D64C /* UIImageView+WebCache.m */, + ); + path = SDWebImage; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -252,6 +360,8 @@ 8A35E156171F8F0C00F4D64C /* Default@2x.png in Resources */, 8A35E158171F8F0C00F4D64C /* Default-568h@2x.png in Resources */, 8A35E15E171F8F0D00F4D64C /* ViewController.xib in Resources */, + 8A35E18F171F98E100F4D64C /* CHANGELOG.md in Resources */, + 8A35E191171F98E100F4D64C /* README.md in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -276,6 +386,18 @@ 8A35E187171F911400F4D64C /* MKNetworkEngine.m in Sources */, 8A35E188171F911400F4D64C /* MKNetworkOperation.m in Sources */, 8A35E189171F911400F4D64C /* Reachability.m in Sources */, + 8A35E190171F98E100F4D64C /* JSONKit.m in Sources */, + 8A35E194171F996600F4D64C /* WaterflowViewCell.m in Sources */, + 8A35E1AB171F9CB600F4D64C /* MKAnnotationView+WebCache.m in Sources */, + 8A35E1AC171F9CB600F4D64C /* SDImageCache.m in Sources */, + 8A35E1AD171F9CB600F4D64C /* SDWebImageCompat.m in Sources */, + 8A35E1AE171F9CB600F4D64C /* SDWebImageDecoder.m in Sources */, + 8A35E1AF171F9CB600F4D64C /* SDWebImageDownloader.m in Sources */, + 8A35E1B0171F9CB600F4D64C /* SDWebImageDownloaderOperation.m in Sources */, + 8A35E1B1171F9CB600F4D64C /* SDWebImageManager.m in Sources */, + 8A35E1B2171F9CB600F4D64C /* SDWebImagePrefetcher.m in Sources */, + 8A35E1B3171F9CB600F4D64C /* UIButton+WebCache.m in Sources */, + 8A35E1B4171F9CB600F4D64C /* UIImageView+WebCache.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/PSCollectionViewDemo/AppDelegate.h b/PSCollectionViewDemo/AppDelegate.h index 5d80363..ea3c2fc 100644 --- a/PSCollectionViewDemo/AppDelegate.h +++ b/PSCollectionViewDemo/AppDelegate.h @@ -7,13 +7,20 @@ // #import +#import "MKNetworkKit.h" @class ViewController; -@interface AppDelegate : UIResponder +@interface AppDelegate : UIResponder { + MKNetworkEngine *networkEngine; +} + ++ (AppDelegate *)instance; @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) ViewController *viewController; +@property (strong, nonatomic) MKNetworkEngine *networkEngine; + @end diff --git a/PSCollectionViewDemo/AppDelegate.m b/PSCollectionViewDemo/AppDelegate.m index 2695d3d..ec816c2 100644 --- a/PSCollectionViewDemo/AppDelegate.m +++ b/PSCollectionViewDemo/AppDelegate.m @@ -12,8 +12,18 @@ @implementation AppDelegate +@synthesize networkEngine; + ++ (AppDelegate *)instance { + return (AppDelegate *)[[UIApplication sharedApplication] delegate]; +} + - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); + + networkEngine = [[MKNetworkEngine alloc] initWithHostName:@"imgur.com" customHeaderFields:nil]; + self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; @@ -49,4 +59,9 @@ - (void)applicationWillTerminate:(UIApplication *)application // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } +void uncaughtExceptionHandler(NSException*exception){ + NSLog(@"CRASH: %@", exception); + NSLog(@"Stack Trace: %@", [exception callStackSymbols]); +} + @end diff --git a/PSCollectionViewDemo/JSONKit/CHANGELOG.md b/PSCollectionViewDemo/JSONKit/CHANGELOG.md new file mode 100644 index 0000000..a23cefd --- /dev/null +++ b/PSCollectionViewDemo/JSONKit/CHANGELOG.md @@ -0,0 +1,389 @@ +# JSONKit Changelog + +## Version 1.X ????/??/?? + +**IMPORTANT:** The following changelog notes are a work in progress. They apply to the work done on JSONKit post v1.4. Since JSONKit itself is inbetween versions, these changelog notes are subject to change, may be wrong, and just about everything else you could expect at this point in development. + +### New Features + +* When `JKSerializeOptionPretty` is enabled, JSONKit now sorts the keys. + +* Normally, JSONKit can only serialize NSNull, NSNumber, NSString, NSArray, and NSDictioonary like objects. It is now possible to serialize an object of any class via either a delegate or a `^` block. + + The delegate or `^` block must return an object that can be serialized by JSONKit, however, otherwise JSONKit will fail to serialize the object. In other words, JSONKit tries to serialize an unsupported class of the object just once, and if the delegate or ^block returns another unsupported class, the second attempt to serialize will fail. In practice, this is not a problem at all, but it does prevent endless recursive attempts to serialize an unsupported class. + + This makes it trivial to serialize objects like NSDate or NSData. A NSDate object can be formatted using a NSDateFormatter to return a ISO-8601 `YYYY-MM-DDTHH:MM:SS.sssZ` type object, for example. Or a NSData object could be Base64 encoded. + + This greatly simplifies things when you have a complex, nested objects with objects that do not belong to the classes that JSONKit can serialize. + + It should be noted that the same caching that JSONKit does for the supported class types also applies to the objects of an unsupported class- if the same object is serialized more than once and the object is still in the serialization cache, JSONKit will copy the previous serialization result instead of invoking the delegate or `^` block again. Therefore, you should not expect or depend on your delegate or block being called each time the same object needs to be serialized AND the delegate or block MUST return a "formatted object" that is STRICTLY invariant (that is to say the same object must always return the exact same formatted output). + + To serialize NSArray or NSDictionary objects using a delegate– + + **NOTE:** The delegate is based a single argument, the object with the unsupported class, and the supplied `selector` method must be one that accepts a single `id` type argument (i.e., `formatObject:`). + **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail. + +
+    ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
+    ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
+    
+ + To serialize NSArray or NSDictionary objects using a `^` block– + + **NOTE:** The block is passed a single argument, the object with the unsupported class. + **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail. + +
+    ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError \*\*)error;
+    ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError \*\*)error;
+    
+ + Example using the delegate way: + +
+    @interface MYFormatter : NSObject {
+      NSDateFormatter \*outputFormatter;
+    }
+    @end
+    ​
+    @implementation MYFormatter
+    -(id)init
+    {
+      if((self = [super init]) == NULL) { return(NULL); }
+      if((outputFormatter = [[NSDateFormatter alloc] init]) == NULL) { [self autorelease]; return(NULL); }
+      [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
+      return(self);
+    }
+    ​
+    -(void)dealloc
+    {
+      if(outputFormatter != NULL) { [outputFormatter release]; outputFormatter = NULL; }
+      [super dealloc];
+    }
+    ​
+    -(id)formatObject:(id)object
+    {
+      if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
+      return(NULL);
+    }
+    @end
+    ​
+    {
+      MYFormatter \*myFormatter = [[[MYFormatter alloc] init] autorelease];
+      NSArray \*array = [NSArray arrayWithObject:[NSDate dateWithTimeIntervalSinceNow:0.0]];
+
+      NSString \*jsonString = NULL;
+      jsonString = [array                    JSONStringWithOptions:JKSerializeOptionNone
+                          serializeUnsupportedClassesUsingDelegate:myFormatter
+                                                          selector:@selector(formatObject:)
+                                                             error:NULL];
+      NSLog(@"jsonString: '%@'", jsonString);
+      // 2011-03-25 11:42:16.175 formatter_example[59120:903] jsonString: '["2011-03-25T11:42:16.175-0400"]'
+    }
+    
+ + Example using the `^` block way: + +
+    {
+      NSDateFormatter \*outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
+      [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
+      ​
+      jsonString = [array                 JSONStringWithOptions:encodeOptions
+                          serializeUnsupportedClassesUsingBlock:^id(id object) {
+                            if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
+                            return(NULL);
+                          }
+                                                          error:NULL];
+      NSLog(@"jsonString: '%@'", jsonString);
+      // 2011-03-25 11:49:56.434 json_parse[59167:903] jsonString: '["2011-03-25T11:49:56.434-0400"]'
+    }
+    
+ +### Major Changes + +* The way that JSONKit implements the collection classes was modified. Specifically, JSONKit now follows the same strategy that the Cocoa collection classes use, which is to have a single subclass of the mutable collection class. This concrete subclass has an ivar bit that determines whether or not that instance is mutable, and when an immutable instance receives a mutating message, it throws an exception. + +## Version 1.4 2011/23/03 + +### Highlights + +* JSONKit v1.4 significantly improves the performance of serializing and deserializing. Deserializing is 23% faster than Apples binary `.plist`, and an amazing 549% faster than Apples binary `.plist` when serializing. + +### New Features + +* JSONKit can now return mutable collection classes. +* The `JKSerializeOptionFlags` option `JKSerializeOptionPretty` was implemented. +* It is now possible to serialize a single [`NSString`][NSString]. This functionality was requested in issue #4 and issue #11. + +### Deprecated Methods + +* The following `JSONDecoder` methods are deprecated beginning with JSONKit v1.4 and will be removed in a later release– + +
+    ​- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length;
+    ​- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length error:(NSError \*\*)error;
+    ​- (id)parseJSONData:(NSData \*)jsonData;
+    ​- (id)parseJSONData:(NSData \*)jsonData error:(NSError \*\*)error;
+    
+ + The JSONKit v1.4 objectWith… methods should be used instead. + +### NEW API's + +* The following methods were added to `JSONDecoder`– + + These methods replace their deprecated parse… counterparts and return immutable collection objects. + +
+    ​- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
+    ​- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
+    ​- (id)objectWithData:(NSData \*)jsonData;
+    ​- (id)objectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
+    
+ + These methods are the same as their objectWith… counterparts except they return mutable collection objects. + +
+    ​- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
+    ​- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
+    ​- (id)mutableObjectWithData:(NSData \*)jsonData;
+    ​- (id)mutableObjectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
+    
+ +* The following methods were added to `NSString (JSONKitDeserializing)`– + + These methods are the same as their objectFrom… counterparts except they return mutable collection objects. + +
+    ​- (id)mutableObjectFromJSONString;
+    ​- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
+    ​- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
+    
+ +* The following methods were added to `NSData (JSONKitDeserializing)`– + + These methods are the same as their objectFrom… counterparts except they return mutable collection objects. + +
+    ​- (id)mutableObjectFromJSONData;
+    ​- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
+    ​- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
+    
+ +* The following methods were added to `NSString (JSONKitSerializing)`– + + These methods are for those uses that need to serialize a single [`NSString`][NSString]– + +
+    ​- (NSData \*)JSONData;
+    ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
+    ​- (NSString \*)JSONString;
+    ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
+    
+ +### Bug Fixes + +* JSONKit has a fast and a slow path for parsing JSON Strings. The slow path is needed whenever special string processing is required, such as the conversion of `\` escape sequences or ill-formed UTF-8. Although the slow path had a check for characters < `0x20`, which are not permitted by the [RFC 4627][], there was a bug such that the condition was never actually checked. As a result, JSONKit would have incorrectly accepted JSON that contained characters < `0x20` if it was using the slow path to process a JSON String. +* The low surrogate in a \uhigh\ulow escape sequence in a JSON String was incorrectly treating `dfff` as ill-formed Unicode. This was due to a comparison that used `>= 0xdfff` instead of `> 0xdfff` as it should have. +* `JKParseOptionLooseUnicode` was not properly honored when parsing some types of ill-formed Unicode in \uHHHH escapes in JSON Strings. + +### Important Notes + +* JSONKit v1.4 now uses custom concrete subclasses of [`NSArray`][NSArray], [`NSMutableArray`][NSMutableArray], [`NSDictionary`][NSDictionary], and [`NSMutableDictionary`][NSMutableDictionary]— `JKArray`, `JKMutableArray`, `JKDictionary`, and `JKMutableDictionary`. respectively. These classes are internal and private to JSONKit, you should not instantiate objects from these classes directly. + + In theory, these custom classes should behave exactly the same as the respective Foundation / Cocoa counterparts. + + As usual, in practice may have non-linear excursions from what theory predicts. It is also virtually impossible to properly test or predict how these custom classes will interact with software in the wild. + + Most likely, if you do encounter a problem, it will happen very quickly, and you should report a bug via the [github.com JSONKit Issue Tracker][bugtracker]. + + In addition to the required class cluster primitive methods, the custom collection classes also include support for [`NSFastEnumeration`][NSFastEnumeration], along with methods that support the bulk retrieval of the objects contents. + + #### Exceptions Thrown + + The JSONKit collection classes will throw the same exceptions for the same conditions as their respective Foundation counterparts. If you find a discrepancy, please report a bug via the [github.com JSONKit Issue Tracker][bugtracker]. + + #### Multithreading Safety + + The same multithreading rules and caveats for the Foundation collection classes apply to the JSONKit collection classes. Specifically, it should be safe to use the immutable collections from multiple threads concurrently. + + The mutable collections can be used from multiple threads as long as you provide some form of mutex barrier that ensures that if a thread needs to mutate the collection, then it has exclusive access to the collection– no other thread can be reading from or writing to the collection until the mutating thread has finished. Failure to ensure that there are no other threads reading or writing from the mutable collection when a thread mutates the collection will result in `undefined` behavior. + + #### Mutable Collection Notes + + The mutable versions of the collection classes are meant to be used when you need to make minor modifications to the collection. Neither `JKMutableArray` or `JKMutableDictionary` have been optimized for nor are they intended to be used in situations where you are adding a large number of objects or new keys– these types of operations will cause both classes to frequently reallocate the memory used to hold the objects in the collection. + + #### `JKMutableArray` Usage Notes + + * You should minimize the number of new objects you added to the array. The array is not designed for high performance insertion and removal of objects. If the array does not have any extra capacity it must reallocate the backing store. When the array is forced to grow the backing store, it currently adds an additional 16 slots worth of spare capacity. The array is instantiated without any extra capacity on the assumption that dictionaries are going to be mutated more than arrays. The array never shrinks the backing store. + + * Replacing objects in the array via [`-replaceObjectAtIndex:withObject:`][-replaceObjectAtIndex:withObject:] is very fast since the array simply releases the current object at the index and replaces it with the new object. + + * Inserting an object in to the array via [`-insertObject:atIndex:`][-insertObject:atIndex:] cause the array to [`memmove()`][memmove] all the objects up one slot from the insertion index. This means this operation is fastest when inserting objects at the last index since no objects need to be moved. + + * Removing an object from the array via [`-removeObjectAtIndex:`][-removeObjectAtIndex:] causes the array to [`memmove()`][memmove] all the objects down one slot from the removal index. This means this operation is fastest when removing objects at the last index since no objects need to be moved. The array will not resize its backing store to a smaller size. + + * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSArray`][NSArray] or [`NSMutableArray`][NSMutableArray] class object, respectively, with the contents of the receiver. + + #### `JKMutableDictionary` Usage Notes + + * You should minimize the number of new keys you add to the dictionary. If the number of items in the dictionary exceeds a threshold value it will trigger a resizing operation. To do this, the dictionary must allocate a new, larger backing store, and then re-add all the items in the dictionary by rehashing them to the size of the newer, larger store. This is an expensive operation. While this is a limitation of nearly all hash tables, the capacity for the hash table used by `JKMutableDictionary` has been chosen to minimize the amount of memory used since it is anticipated that most dictionaries will not grow significantly once they are instantiated. + + * If the key already exists in the dictionary and you change the object associated with it via [`-setObject:forKey:`][-setObject:forKey:], this will not cause any performance problems or trigger a hash table resize. + + * Removing a key from the dictionary via [`-removeObjectForKey:`][-removeObjectForKey:] will not cause any performance problems. However, the dictionary will not resize its backing store to the smaller size. + + * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSDictionary`][NSDictionary] or [`NSMutableDictionary`][NSMutableDictionary] class object, respectively, with the contents of the receiver. + +### Major Changes + +* The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag that was added to JSONKit v1.3 has been removed. + + `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was added in JSONKit v1.3 as a temporary work around. While the author was aware of other ways to fix the particular problem caused by the usage of "transfer of ownership callbacks" with Core Foundation classes, the fix provided in JSONKit v1.3 was trivial to implement. This allowed people who needed that functionality to use JSONKit while a proper solution to the problem was worked on. JSONKit v1.4 is the result of that work. + + JSONKit v1.4 no longer uses the Core Foundation collection classes [`CFArray`][CFArray] and [`CFDictionary`][CFDictionary]. Instead, JSONKit v1.4 contains a concrete subclass of [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary]– `JKArray` and `JKDictionary`, respectively. As a result, JSONKit has complete control over the behavior of how items are added and managed within an instantiated collection object. The `JKArray` and `JKDictionary` classes are private to JSONKit, you should not instantiate them direction. Since they are concrete subclasses of their respective collection class cluster, they behave and act exactly the same as [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary]. + + The first benefit is that the "transfer of ownership" object ownership policy can now be safely used. Because the JSONKit collection objects understand that some methods, such as [`-mutableCopy`][-mutableCopy], should not inherit the same "transfer of ownership" object ownership policy, but must follow the standard Cocoa object ownership policy. The "transfer of ownership" object ownership policy reduces the number of [`-retain`][-retain] and [`-release`][-release] calls needed to add an object to a collection, and when creating a large number of objects very quickly (as you would expect when parsing JSON), this can result in a non-trivial amount of time. Eliminating these calls means faster JSON parsing. + + A second benefit is that the author encountered some unexpected behavior when using the [`CFDictionaryCreate`][CFDictionaryCreate] function to create a dictionary and the `keys` argument contained duplicate keys. This required JSONKit to de-duplicate the keys and values before calling [`CFDictionaryCreate`][CFDictionaryCreate]. Unfortunately, JSONKit always had to scan all the keys to make sure there were no duplicates, even though 99.99% of the time there were none. This was less than optimal, particularly because one of the solutions to this particular problem is to use a hash table to perform the de-duplication. Now JSONKit can do the de-duplication while it is instantiating the dictionary collection, solving two problems at once. + + Yet another benefit is that the recently instantiated object cache that JSONKit uses can be used to cache information about the keys used to create dictionary collections, in particular a keys [`-hash`][-hash] value. For a lot of real world JSON, this effectively means that the [`-hash`][-hash] for a key is calculated once, and that value is reused again and again when creating dictionaries. Because all the information required to create the hash table used by `JKDictionary` is already determined at the time the `JKDictionary` object is instantiated, populating the `JKDictionary` is now a very tight loop that only has to call [`-isEqual:`][-isEqual:] on the rare occasions that the JSON being parsed contains duplicate keys. Since the functions that handle this logic are all declared `static` and are internal to JSONKit, the compiler can heavily optimize this code. + + What does this mean in terms of performance? JSONKit was already fast, but now, it's even faster. Below is some benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json] in [samsoffes / json-benchmarks](https://github.com/samsoffes/json-benchmarks), where _read_ means to convert the JSON to native Objective-C objects, and _write_ means to convert the native Objective-C to JSON— + +
+    v1.3 read : min:  456.000 us, avg:  460.056 us, char/s:  53341332.36 /  50.870 MB/s
+    v1.3 write: min:  150.000 us, avg:  151.816 us, char/s: 161643041.58 / 154.155 MB/s
+ +
+    v1.4 read : min:  285.000 us, avg:  288.603 us, char/s:  85030301.14 /  81.091 MB/s
+    v1.4 write: min:  127.000 us, avg:  129.617 us, char/s: 189327017.29 / 180.556 MB/s
+ + JSONKit v1.4 is nearly 60% faster at reading and 17% faster at writing than v1.3. + + The following is the JSON test file taken from the project available at [this blog post](http://psionides.jogger.pl/2010/12/12/cocoa-json-parsing-libraries-part-2/). The keys and information contained in the JSON was anonymized with random characters. Since JSONKit relies on its recently instantiated object cache for a lot of its performance, this JSON happens to be "the worst corner case possible". + +
+    v1.3 read : min: 5222.000 us, avg: 5262.344 us, char/s:  15585260.10 /  14.863 MB/s
+    v1.3 write: min: 1253.000 us, avg: 1259.914 us, char/s:  65095712.88 /  62.080 MB/s
+ +
+    v1.4 read : min: 4096.000 us, avg: 4122.240 us, char/s:  19895736.30 /  18.974 MB/s
+    v1.4 write: min: 1319.000 us, avg: 1335.538 us, char/s:  61409709.05 /  58.565 MB/s
+ + JSONKit v1.4 is 28% faster at reading and 6% faster at writing that v1.3 in this worst-case torture test. + + While your milage may vary, you will likely see improvements in the 50% for reading and 10% for writing on your real world JSON. The nature of JSONKits cache means performance improvements is statistical in nature and depends on the particular properties of the JSON being parsed. + + For comparison, [json-framework][], a popular Objective-C JSON parsing library, turns in the following benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json]— + +
+    ​     read : min: 1670.000 us, avg: 1682.461 us, char/s:  14585776.43 /  13.910 MB/s
+    ​     write: min: 1021.000 us, avg: 1028.970 us, char/s:  23849091.81 /  22.744 MB/s
+ + Since the benchmark for JSONKit and [json-framework][] was done on the same computer, it's safe to compare the timing results. The version of [json-framework][] used was the latest v3.0 available via the master branch at the time of this writing on github.com. + + JSONKit v1.4 is 483% faster at reading and 694% faster at writing than [json-framework][]. + +### Other Changes + +* Added a `__clang_analyzer__` pre-processor conditional around some code that the `clang` static analyzer was giving false positives for. However, `clang` versions ≤ 1.5 do not define `__clang_analyzer__` and therefore will continue to emit analyzer warnings. +* The cache now uses a Galois Linear Feedback Shift Register PRNG to select which item in the cache to randomly age. This should age items in the cache more fairly. +* To promote better L1 cache locality, the cache age structure was rearranged slightly along with modifying when an item is randomly chosen to be aged. +* Removed a lot of internal and private data structures from `JSONKit.h` and put them in `JSONKit.m`. +* Modified the way floating point values are serialized. Previously, the [`printf`][printf] format conversion `%.16g` was used. This was changed to `%.17g` which should theoretically allow for up to a full `float`, or [IEEE 754 Single 32-bit floating-point][Single Precision], of precision when converting floating point values to decimal representation. +* The usual sundry of inconsequential tidies and what not, such as updating the `README.md`, etc. +* The catagory additions to the Cocoa classes were changed from `JSONKit` to `JSONKitDeserializing` and `JSONKitSerializing`, as appropriate. + +## Version 1.3 2011/05/02 + +### New Features + +* Added the `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag. + + This is typically enabled by adding `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to the compilers command line arguments or in `Xcode.app` by adding `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to a projects / targets `Pre-Processor Macros` settings. + + The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` option enables the use of custom Core Foundation collection call backs which omit the [`CFRetain`][CFRetain] calls. This results in saving several [`CFRetain`][CFRetain] and [`CFRelease`][CFRelease] calls typically needed for every single object from the parsed JSON. While the author has used this technique for years without any issues, an unexpected interaction with the Foundation [`-mutableCopy`][-mutableCopy] method and Core Foundation Toll-Free Bridging resulting in a condition in which the objects contained in the collection to be over released. This problem does not occur with the use of [`-copy`][-copy] due to the fact that the objects created by JSONKit are immutable, and therefore [`-copy`][-copy] does not require creating a completely new object and copying the contents, instead [`-copy`][-copy] simply returns a [`-retain`][-retain]'d version of the immutable object which is significantly faster along with the obvious reduction in memory usage. + + Prior to version 1.3, JSONKit always used custom "Transfer of Ownership Collection Callbacks", and thus `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was effectively implicitly defined. + + Beginning with version 1.3, the default behavior of JSONKit is to use the standard Core Foundation collection callbacks ([`kCFTypeArrayCallBacks`][kCFTypeArrayCallBacks], [`kCFTypeDictionaryKeyCallBacks`][kCFTypeDictionaryKeyCallBacks], and [`kCFTypeDictionaryValueCallBacks`][kCFTypeDictionaryValueCallBacks]). The intention is to follow "the principle of least surprise", and the author believes the use of the standard Core Foundation collection callbacks as the default behavior for JSONKit results in the least surprise. + + **NOTE**: `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to `(CF|NS)` `Dictionary` and `Array` class objects. + + For the vast majority of users, the author believes JSONKits custom "Transfer of Ownership Collection Callbacks" will not cause any problems. As previously stated, the author has used this technique in performance critical code for years and has never had a problem. Until a user reported a problem with [`-mutableCopy`][-mutableCopy], the author was unaware that the use of the custom callbacks could even cause a problem. This is probably due to the fact that the vast majority of time the typical usage pattern tends to be "iterate the contents of the collection" and very rarely mutate the returned collection directly (although this last part is likely to vary significantly from programmer to programmer). The author tends to avoid the use of [`-mutableCopy`][-mutableCopy] as it results in a significant performance and memory consumption penalty. The reason for this is in "typical" Cocoa coding patterns, using [`-mutableCopy`][-mutableCopy] will instantiate an identical, albeit mutable, version of the original object. This requires both memory for the new object and time to iterate the contents of the original object and add them to the new object. Furthermore, under "typical" Cocoa coding patterns, the original collection object continues to consume memory until the autorelease pool is released. However, clearly there are cases where the use of [`-mutableCopy`][-mutableCopy] makes sense or may be used by an external library which is out of your direct control. + + The use of the standard Core Foundation collection callbacks results in a 9% to 23% reduction in parsing performance, with an "eye-balled average" of around 13% according to some benchmarking done by the author using Real World™ JSON (i.e., actual JSON from various web services, such as Twitter, etc) using `gcc-4.2 -arch x86_64 -O3 -DNS_BLOCK_ASSERTIONS` with the only change being the addition of `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`. + + `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to parsing / deserializing (i.e. converting from) of JSON. Serializing (i.e., converting to JSON) is completely unaffected by this change. + +### Bug Fixes + +* Fixed a [bug report regarding `-mutableCopy`](https://github.com/johnezang/JSONKit/issues#issue/3). This is related to the addition of the pre-processor define flag `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`. + +### Other Changes + +* Added `JK_EXPECTED` optimization hints around several conditionals. +* When serializing objects, JSONKit first starts with a small, on stack buffer. If the encoded JSON exceeds the size of the stack buffer, JSONKit switches to a heap allocated buffer. If JSONKit switched to a heap allocated buffer, [`CFDataCreateWithBytesNoCopy`][CFDataCreateWithBytesNoCopy] is used to create the [`NSData`][NSData] object, which in most cases causes the heap allocated buffer to "transfer" to the [`NSData`][NSData] object which is substantially faster than allocating a new buffer and copying the bytes. +* Added a pre-processor check in `JSONKit.m` to see if Objective-C Garbage Collection is enabled and issue a `#error` notice that JSONKit does not support Objective-C Garbage Collection. +* Various other minor or trivial modifications, such as updating `README.md`. + +### Other Issues + +* When using the `clang` static analyzer (the version used at the time of this writing was `Apple clang version 1.5 (tags/Apple/clang-60)`), the static analyzer reports a number of problems with `JSONKit.m`. + + The author has investigated these issues and determined that the problems reported by the current version of the static analyzer are "false positives". Not only that, the reported problems are not only "false positives", they are very clearly and obviously wrong. Therefore, the author has made the decision that no action will be taken on these non-problems, which includes not modifying the code for the sole purpose of silencing the static analyzer. The justification for this is "the dog wags the tail, not the other way around." + +## Version 1.2 2011/01/08 + +### Bug Fixes + +* When JSONKit attempted to parse and decode JSON that contained `{"key": value}` dictionaries that contained the same key more than once would likely result in a crash. This was a serious bug. +* Under some conditions, JSONKit could potentially leak memory. +* There was an off by one error in the code that checked whether or not the parser was at the end of the `UTF8` buffer. This could result in JSONKit reading one by past the buffer bounds in some cases. + +### Other Changes + +* Some of the methods were missing `NULL` pointer checks for some of their arguments. This was fixed. In generally, when JSONKit encounters invalid arguments, it throws a `NSInvalidArgumentException` exception. +* Various other minor changes such as tightening up numeric literals with `UL` or `L` qualification, assertion check tweaks and additions, etc. +* The README.md file was updated with additional information. + +### Version 1.1 + +No change log information was kept for versions prior to 1.2. + +[bugtracker]: https://github.com/johnezang/JSONKit/issues +[RFC 4627]: http://tools.ietf.org/html/rfc4627 +[twitter_public_timeline.json]: https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json +[json-framework]: https://github.com/stig/json-framework +[Single Precision]: http://en.wikipedia.org/wiki/Single_precision +[kCFTypeArrayCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html#//apple_ref/c/data/kCFTypeArrayCallBacks +[kCFTypeDictionaryKeyCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryKeyCallBacks +[kCFTypeDictionaryValueCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryValueCallBacks +[CFRetain]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRetain +[CFRelease]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRelease +[CFDataCreateWithBytesNoCopy]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDataRef/Reference/reference.html#//apple_ref/c/func/CFDataCreateWithBytesNoCopy +[CFArray]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html +[CFDictionary]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html +[CFDictionaryCreate]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/func/CFDictionaryCreate +[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy +[-copy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/copy +[-retain]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retain +[-release]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/release +[-isEqual:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual: +[-hash]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/hash +[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html +[NSMutableArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html +[-insertObject:atIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/insertObject:atIndex: +[-removeObjectAtIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/removeObjectAtIndex: +[-replaceObjectAtIndex:withObject:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/replaceObjectAtIndex:withObject: +[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html +[NSMutableDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/index.html +[-setObject:forKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/setObject:forKey: +[-removeObjectForKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/removeObjectForKey: +[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html +[NSFastEnumeration]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/Reference/NSFastEnumeration.html +[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html +[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html +[memmove]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/memmove.3.html diff --git a/PSCollectionViewDemo/JSONKit/JSONKit.h b/PSCollectionViewDemo/JSONKit/JSONKit.h new file mode 100644 index 0000000..71bd0c3 --- /dev/null +++ b/PSCollectionViewDemo/JSONKit/JSONKit.h @@ -0,0 +1,251 @@ +// +// JSONKit.h +// http://github.com/johnezang/JSONKit +// Dual licensed under either the terms of the BSD License, or alternatively +// under the terms of the Apache License, Version 2.0, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + 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 the Zang Industries 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. +*/ + +/* + Copyright 2011 John Engelhart + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#ifdef __OBJC__ +#import +#import +#import +#import +#import +#import +#endif // __OBJC__ + +#ifdef __cplusplus +extern "C" { +#endif + + +// For Mac OS X < 10.5. +#ifndef NSINTEGER_DEFINED +#define NSINTEGER_DEFINED +#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef long NSInteger; +typedef unsigned long NSUInteger; +#define NSIntegerMin LONG_MIN +#define NSIntegerMax LONG_MAX +#define NSUIntegerMax ULONG_MAX +#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +typedef int NSInteger; +typedef unsigned int NSUInteger; +#define NSIntegerMin INT_MIN +#define NSIntegerMax INT_MAX +#define NSUIntegerMax UINT_MAX +#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) +#endif // NSINTEGER_DEFINED + + +#ifndef _JSONKIT_H_ +#define _JSONKIT_H_ + +#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465) +#define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#else +#define JK_DEPRECATED_ATTRIBUTE +#endif + +#define JSONKIT_VERSION_MAJOR 1 +#define JSONKIT_VERSION_MINOR 4 + +typedef NSUInteger JKFlags; + +/* + JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON. + JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines. + JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode. + This option allows JSON with malformed Unicode to be parsed without reporting an error. + Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER". + */ + +enum { + JKParseOptionNone = 0, + JKParseOptionStrict = 0, + JKParseOptionComments = (1 << 0), + JKParseOptionUnicodeNewlines = (1 << 1), + JKParseOptionLooseUnicode = (1 << 2), + JKParseOptionPermitTextAfterValidJSON = (1 << 3), + JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON), +}; +typedef JKFlags JKParseOptionFlags; + +enum { + JKSerializeOptionNone = 0, + JKSerializeOptionPretty = (1 << 0), + JKSerializeOptionEscapeUnicode = (1 << 1), + JKSerializeOptionEscapeForwardSlashes = (1 << 4), + JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes), +}; +typedef JKFlags JKSerializeOptionFlags; + +#ifdef __OBJC__ + +typedef struct JKParseState JKParseState; // Opaque internal, private type. + +// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict + +@interface JSONDecoder : NSObject { + JKParseState *parseState; +} ++ (id)decoder; ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (void)clearCache; + +// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. +// The NSData MUST be UTF8 encoded JSON. +- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead. +- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead. + +// Methods that return immutable collection objects. +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; +// The NSData MUST be UTF8 encoded JSON. +- (id)objectWithData:(NSData *)jsonData; +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error; + +// Methods that return mutable collection objects. +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; +// The NSData MUST be UTF8 encoded JSON. +- (id)mutableObjectWithData:(NSData *)jsonData; +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error; + +@end + +//////////// +#pragma mark Deserializing methods +//////////// + +@interface NSString (JSONKitDeserializing) +- (id)objectFromJSONString; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONString; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +@end + +@interface NSData (JSONKitDeserializing) +// The NSData MUST be UTF8 encoded JSON. +- (id)objectFromJSONData; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONData; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +@end + +//////////// +#pragma mark Serializing methods +//////////// + +@interface NSString (JSONKitSerializing) +// Convenience methods for those that need to serialize the receiving NSString (i.e., instead of having to serialize a NSArray with a single NSString, you can "serialize to JSON" just the NSString). +// Normally, a string that is serialized to JSON has quotation marks surrounding it, which you may or may not want when serializing a single string, and can be controlled with includeQuotes: +// includeQuotes:YES `a "test"...` -> `"a \"test\"..."` +// includeQuotes:NO `a "test"...` -> `a \"test\"...` +- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +@end + +@interface NSArray (JSONKitSerializing) +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +@end + +@interface NSDictionary (JSONKitSerializing) +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +@end + +#ifdef __BLOCKS__ + +@interface NSArray (JSONKitSerializingBlockAdditions) +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +@end + +@interface NSDictionary (JSONKitSerializingBlockAdditions) +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; +@end + +#endif + + +#endif // __OBJC__ + +#endif // _JSONKIT_H_ + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/PSCollectionViewDemo/JSONKit/JSONKit.m b/PSCollectionViewDemo/JSONKit/JSONKit.m new file mode 100644 index 0000000..0e9331f --- /dev/null +++ b/PSCollectionViewDemo/JSONKit/JSONKit.m @@ -0,0 +1,3065 @@ +// +// JSONKit.m +// http://github.com/johnezang/JSONKit +// Dual licensed under either the terms of the BSD License, or alternatively +// under the terms of the Apache License, Version 2.0, as specified below. +// + +/* + Copyright (c) 2011, John Engelhart + + 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 the Zang Industries 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. +*/ + +/* + Copyright 2011 John Engelhart + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + + +/* + Acknowledgments: + + The bulk of the UTF8 / UTF32 conversion and verification comes + from ConvertUTF.[hc]. It has been modified from the original sources. + + The original sources were obtained from http://www.unicode.org/. + However, the web site no longer seems to host the files. Instead, + the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4 + points to International Components for Unicode (ICU) + http://site.icu-project.org/ as an example of how to write a UTF + converter. + + The decision to use the ConvertUTF.[ch] code was made to leverage + "proven" code. Hopefully the local modifications are bug free. + + The code in isValidCodePoint() is derived from the ICU code in + utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR. + + From the original ConvertUTF.[ch]: + + * Copyright 2001-2004 Unicode, Inc. + * + * Disclaimer + * + * This source code is provided as is by Unicode, Inc. No claims are + * made as to fitness for any particular purpose. No warranties of any + * kind are expressed or implied. The recipient agrees to determine + * applicability of information provided. If this file has been + * purchased on magnetic or optical media from Unicode, Inc., the + * sole remedy for any claim will be exchange of defective media + * within 90 days of receipt. + * + * Limitations on Rights to Redistribute This Code + * + * Unicode, Inc. hereby grants the right to freely use the information + * supplied in this file in the creation of products supporting the + * Unicode Standard, and to make copies of this file in any form + * for internal or external distribution as long as this notice + * remains attached. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#import "JSONKit.h" + +//#include +#include +#include +#include +#include + +//#import +#import +#import +#import +#import +#import +#import +#import + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS +#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option. +#endif + +#ifdef __OBJC_GC__ +#error JSONKit does not support Objective-C Garbage Collection +#endif + +#if __has_feature(objc_arc) +#error JSONKit does not support Objective-C Automatic Reference Counting (ARC) +#endif + +// The following checks are really nothing more than sanity checks. +// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety. +// In practice, though, for the compilers and architectures we can reasonably expect this code to be compiled for, these pedantic nitpicks aren't really a problem. +// Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be. + +#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL)) +#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively. +#endif + +#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT)) +#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures. +#endif + +// Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t + +#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type. +#endif + +#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type. +#endif + + +// For DJB hash. +#define JK_HASH_INIT (1402737925UL) + +// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup. +#define JK_FAST_TRAILING_BYTES + +// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots. +#define JK_CACHE_SLOTS_BITS (10) +#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS) +// JK_CACHE_PROBES is the number of probe attempts. +#define JK_CACHE_PROBES (4UL) +// JK_INIT_CACHE_AGE must be < (1 << AGE) - 1, where AGE is sizeof(typeof(AGE)) * 8. +#define JK_INIT_CACHE_AGE (0) + +// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes) +#define JK_TOKENBUFFER_SIZE (1024UL * 2UL) + +// JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary. +#define JK_STACK_OBJS (1024UL * 1UL) + +#define JK_JSONBUFFER_SIZE (1024UL * 4UL) +#define JK_UTF8BUFFER_SIZE (1024UL * 16UL) + +#define JK_ENCODE_CACHE_SLOTS (1024UL) + + +#if defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) +#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) +#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U) +#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U) +#define JK_PREFETCH(ptr) __builtin_prefetch(ptr) +#else // defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) +#define JK_EXPECTED(cond, expect) (cond) +#define JK_EXPECT_T(cond) (cond) +#define JK_EXPECT_F(cond) (cond) +#define JK_PREFETCH(ptr) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) + +#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline) +#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg)) +#define JK_UNUSED_ARG JK_ATTRIBUTES(unused) +#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result) +#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const) +#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure) +#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel) +#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) + +#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) +#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) + + +@class JKArray, JKDictionaryEnumerator, JKDictionary; + +enum { + JSONNumberStateStart = 0, + JSONNumberStateFinished = 1, + JSONNumberStateError = 2, + JSONNumberStateWholeNumberStart = 3, + JSONNumberStateWholeNumberMinus = 4, + JSONNumberStateWholeNumberZero = 5, + JSONNumberStateWholeNumber = 6, + JSONNumberStatePeriod = 7, + JSONNumberStateFractionalNumberStart = 8, + JSONNumberStateFractionalNumber = 9, + JSONNumberStateExponentStart = 10, + JSONNumberStateExponentPlusMinus = 11, + JSONNumberStateExponent = 12, +}; + +enum { + JSONStringStateStart = 0, + JSONStringStateParsing = 1, + JSONStringStateFinished = 2, + JSONStringStateError = 3, + JSONStringStateEscape = 4, + JSONStringStateEscapedUnicode1 = 5, + JSONStringStateEscapedUnicode2 = 6, + JSONStringStateEscapedUnicode3 = 7, + JSONStringStateEscapedUnicode4 = 8, + JSONStringStateEscapedUnicodeSurrogate1 = 9, + JSONStringStateEscapedUnicodeSurrogate2 = 10, + JSONStringStateEscapedUnicodeSurrogate3 = 11, + JSONStringStateEscapedUnicodeSurrogate4 = 12, + JSONStringStateEscapedNeedEscapeForSurrogate = 13, + JSONStringStateEscapedNeedEscapedUForSurrogate = 14, +}; + +enum { + JKParseAcceptValue = (1 << 0), + JKParseAcceptComma = (1 << 1), + JKParseAcceptEnd = (1 << 2), + JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd), + JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd), +}; + +enum { + JKClassUnknown = 0, + JKClassString = 1, + JKClassNumber = 2, + JKClassArray = 3, + JKClassDictionary = 4, + JKClassNull = 5, +}; + +enum { + JKManagedBufferOnStack = 1, + JKManagedBufferOnHeap = 2, + JKManagedBufferLocationMask = (0x3), + JKManagedBufferLocationShift = (0), + + JKManagedBufferMustFree = (1 << 2), +}; +typedef JKFlags JKManagedBufferFlags; + +enum { + JKObjectStackOnStack = 1, + JKObjectStackOnHeap = 2, + JKObjectStackLocationMask = (0x3), + JKObjectStackLocationShift = (0), + + JKObjectStackMustFree = (1 << 2), +}; +typedef JKFlags JKObjectStackFlags; + +enum { + JKTokenTypeInvalid = 0, + JKTokenTypeNumber = 1, + JKTokenTypeString = 2, + JKTokenTypeObjectBegin = 3, + JKTokenTypeObjectEnd = 4, + JKTokenTypeArrayBegin = 5, + JKTokenTypeArrayEnd = 6, + JKTokenTypeSeparator = 7, + JKTokenTypeComma = 8, + JKTokenTypeTrue = 9, + JKTokenTypeFalse = 10, + JKTokenTypeNull = 11, + JKTokenTypeWhiteSpace = 12, +}; +typedef NSUInteger JKTokenType; + +// These are prime numbers to assist with hash slot probing. +enum { + JKValueTypeNone = 0, + JKValueTypeString = 5, + JKValueTypeLongLong = 7, + JKValueTypeUnsignedLongLong = 11, + JKValueTypeDouble = 13, +}; +typedef NSUInteger JKValueType; + +enum { + JKEncodeOptionAsData = 1, + JKEncodeOptionAsString = 2, + JKEncodeOptionAsTypeMask = 0x7, + JKEncodeOptionCollectionObj = (1 << 3), + JKEncodeOptionStringObj = (1 << 4), + JKEncodeOptionStringObjTrimQuotes = (1 << 5), + +}; +typedef NSUInteger JKEncodeOptionType; + +typedef NSUInteger JKHash; + +typedef struct JKTokenCacheItem JKTokenCacheItem; +typedef struct JKTokenCache JKTokenCache; +typedef struct JKTokenValue JKTokenValue; +typedef struct JKParseToken JKParseToken; +typedef struct JKPtrRange JKPtrRange; +typedef struct JKObjectStack JKObjectStack; +typedef struct JKBuffer JKBuffer; +typedef struct JKConstBuffer JKConstBuffer; +typedef struct JKConstPtrRange JKConstPtrRange; +typedef struct JKRange JKRange; +typedef struct JKManagedBuffer JKManagedBuffer; +typedef struct JKFastClassLookup JKFastClassLookup; +typedef struct JKEncodeCache JKEncodeCache; +typedef struct JKEncodeState JKEncodeState; +typedef struct JKObjCImpCache JKObjCImpCache; +typedef struct JKHashTableEntry JKHashTableEntry; + +typedef id (*NSNumberAllocImp)(id receiver, SEL selector); +typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value); +typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object); +#ifdef __BLOCKS__ +typedef id (^JKClassFormatterBlock)(id formatObject); +#endif + + +struct JKPtrRange { + unsigned char *ptr; + size_t length; +}; + +struct JKConstPtrRange { + const unsigned char *ptr; + size_t length; +}; + +struct JKRange { + size_t location, length; +}; + +struct JKManagedBuffer { + JKPtrRange bytes; + JKManagedBufferFlags flags; + size_t roundSizeUpToMultipleOf; +}; + +struct JKObjectStack { + void **objects, **keys; + CFHashCode *cfHashes; + size_t count, index, roundSizeUpToMultipleOf; + JKObjectStackFlags flags; +}; + +struct JKBuffer { + JKPtrRange bytes; +}; + +struct JKConstBuffer { + JKConstPtrRange bytes; +}; + +struct JKTokenValue { + JKConstPtrRange ptrRange; + JKValueType type; + JKHash hash; + union { + long long longLongValue; + unsigned long long unsignedLongLongValue; + double doubleValue; + } number; + JKTokenCacheItem *cacheItem; +}; + +struct JKParseToken { + JKConstPtrRange tokenPtrRange; + JKTokenType type; + JKTokenValue value; + JKManagedBuffer tokenBuffer; +}; + +struct JKTokenCacheItem { + void *object; + JKHash hash; + CFHashCode cfHash; + size_t size; + unsigned char *bytes; + JKValueType type; +}; + +struct JKTokenCache { + JKTokenCacheItem *items; + size_t count; + unsigned int prng_lfsr; + unsigned char age[JK_CACHE_SLOTS]; +}; + +struct JKObjCImpCache { + Class NSNumberClass; + NSNumberAllocImp NSNumberAlloc; + NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong; +}; + +struct JKParseState { + JKParseOptionFlags parseOptionFlags; + JKConstBuffer stringBuffer; + size_t atIndex, lineNumber, lineStartIndex; + size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex; + JKParseToken token; + JKObjectStack objectStack; + JKTokenCache cache; + JKObjCImpCache objCImpCache; + NSError *error; + int errorIsPrev; + BOOL mutableCollections; +}; + +struct JKFastClassLookup { + void *stringClass; + void *numberClass; + void *arrayClass; + void *dictionaryClass; + void *nullClass; +}; + +struct JKEncodeCache { + id object; + size_t offset; + size_t length; +}; + +struct JKEncodeState { + JKManagedBuffer utf8ConversionBuffer; + JKManagedBuffer stringBuffer; + size_t atIndex; + JKFastClassLookup fastClassLookup; + JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS]; + JKSerializeOptionFlags serializeOptionFlags; + JKEncodeOptionType encodeOption; + size_t depth; + NSError *error; + id classFormatterDelegate; + SEL classFormatterSelector; + JKClassFormatterIMP classFormatterIMP; +#ifdef __BLOCKS__ + JKClassFormatterBlock classFormatterBlock; +#endif +}; + +// This is a JSONKit private class. +@interface JKSerializer : NSObject { + JKEncodeState *encodeState; +} + +#ifdef __BLOCKS__ +#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object) +#else +#define JKSERIALIZER_BLOCKS_PROTO id +#endif + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (void)releaseState; + +@end + +struct JKHashTableEntry { + NSUInteger keyHash; + id key, object; +}; + + +typedef uint32_t UTF32; /* at least 32 bits */ +typedef uint16_t UTF16; /* at least 16 bits */ +typedef uint8_t UTF8; /* typically 8 bits */ + +typedef enum { + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD +#define UNI_MAX_BMP (UTF32)0x0000FFFF +#define UNI_MAX_UTF16 (UTF32)0x0010FFFF +#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF +#define UNI_SUR_HIGH_START (UTF32)0xD800 +#define UNI_SUR_HIGH_END (UTF32)0xDBFF +#define UNI_SUR_LOW_START (UTF32)0xDC00 +#define UNI_SUR_LOW_END (UTF32)0xDFFF + + +#if !defined(JK_FAST_TRAILING_BYTES) +static const char trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; +#endif + +static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; +static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + +#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex])) +#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length])) + + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection); +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex); +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject); +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex); + + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count); +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection); +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary); +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary); +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary); +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry); +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object); +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey); + + +static void _JSONDecoderCleanup(JSONDecoder *decoder); + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection); + + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer); +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length); +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize); +static void jk_objectStack_release(JKObjectStack *objectStack); +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count); +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount); + +static void jk_error(JKParseState *parseState, NSString *format, ...); +static int jk_parse_string(JKParseState *parseState); +static int jk_parse_number(JKParseState *parseState); +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr); +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState); +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState); +static int jk_parse_next_token(JKParseState *parseState); +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String); +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex); +static void *jk_parse_dictionary(JKParseState *parseState); +static void *jk_parse_array(JKParseState *parseState); +static void *jk_object_for_token(JKParseState *parseState); +static void *jk_cachedObjects(JKParseState *parseState); +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState); +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy); + + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...); +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...); +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format); +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState); +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format); +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format); +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length); +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr); +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object); +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr); + +#define jk_encode_write1(es, dc, f) (JK_EXPECT_F(_jk_encode_prettyPrint) ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b); +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b); +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c); + +// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type. +// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the +// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection +// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable. +// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4. + + +// This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23 +// Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly. +// Since we do not require anything "special" that +load provides, and we can accomplish the same thing using __attribute__ ((constructor)), the +load logic was moved here. + +static Class _JKArrayClass = NULL; +static size_t _JKArrayInstanceSize = 0UL; +static Class _JKDictionaryClass = NULL; +static size_t _JKDictionaryInstanceSize = 0UL; + +// For JSONDecoder... +static Class _jk_NSNumberClass = NULL; +static NSNumberAllocImp _jk_NSNumberAllocImp = NULL; +static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL; + +extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor)); + +void jk_collectionClassLoadTimeInitialization(void) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal. + + _JKArrayClass = objc_getClass("JKArray"); + _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass)); + + _JKDictionaryClass = objc_getClass("JKDictionary"); + _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass)); + + // For JSONDecoder... + _jk_NSNumberClass = [NSNumber class]; + _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)]; + + // Hacktacular. Need to do it this way due to the nature of class clusters. + id temp_NSNumber = [NSNumber alloc]; + _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)]; + [[temp_NSNumber init] release]; + temp_NSNumber = NULL; + + [pool release]; pool = NULL; +} + + +#pragma mark - +@interface JKArray : NSMutableArray { + id *objects; + NSUInteger count, capacity, mutations; +} +@end + +@implementation JKArray + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL)); + JKArray *array = NULL; + if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc. + array->isa = _JKArrayClass; + if((array = [array init]) == NULL) { return(NULL); } + array->capacity = count; + array->count = count; + if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); } + memcpy(array->objects, objects, array->capacity * sizeof(id)); + array->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(array); +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; } + if((array->count + 1UL) >= array->capacity) { + id *newObjects = NULL; + if((newObjects = (id *)realloc(array->objects, sizeof(id) * (array->capacity + 16UL))) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; } + array->objects = newObjects; + array->capacity += 16UL; + memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count)); + } + array->count++; + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; } + array->objects[objectIndex] = newObject; +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + array->objects[objectIndex] = newObject; +} + +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count - 1UL] = NULL; } + array->count--; +} + +- (void)dealloc +{ + if(JK_EXPECT_T(objects != NULL)) { + NSUInteger atObject = 0UL; + for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } } + free(objects); objects = NULL; + } + + [super dealloc]; +} + +- (NSUInteger)count +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return(count); +} + +- (void)getObjects:(id *)objectsPtr range:(NSRange)range +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range)]; } + if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range), (unsigned long)count]; } +#ifndef __clang_analyzer__ + memcpy(objectsPtr, objects + range.location, range.length * sizeof(id)); +#endif +} + +- (id)objectAtIndex:(NSUInteger)objectIndex +{ + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } + NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL)); + return(objects[objectIndex]); +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= count)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; } + + return(enumeratedCount); +} + +- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)(count + 1UL)]; } +#ifdef __clang_analyzer__ + [anObject retain]; // Stupid clang analyzer... Issue #19. +#else + anObject = [anObject retain]; +#endif + _JKArrayInsertObjectAtIndex(self, anObject, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectAtIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } + _JKArrayRemoveObjectAtIndex(self, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } +#ifdef __clang_analyzer__ + [anObject retain]; // Stupid clang analyzer... Issue #19. +#else + anObject = [anObject retain]; +#endif + _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [(NSArray *)[NSArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return([(NSMutableArray *)[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +@end + + +#pragma mark - +@interface JKDictionaryEnumerator : NSEnumerator { + id collection; + NSUInteger nextObject; +} + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary; +- (NSArray *)allObjects; +- (id)nextObject; + +@end + +@implementation JKDictionaryEnumerator + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary +{ + NSParameterAssert(initDictionary != NULL); + if((self = [super init]) == NULL) { return(NULL); } + if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); } + return(self); +} + +- (void)dealloc +{ + if(collection != NULL) { CFRelease(collection); collection = NULL; } + [super dealloc]; +} + +- (NSArray *)allObjects +{ + NSParameterAssert(collection != NULL); + NSUInteger count = [(NSDictionary *)collection count], atObject = 0UL; + id objects[count]; + + while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; } + + return([NSArray arrayWithObjects:objects count:atObject]); +} + +- (id)nextObject +{ + NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL)); + JKHashTableEntry *entry = _JKDictionaryHashEntry(collection); + NSUInteger capacity = _JKDictionaryCapacity(collection); + id returnObject = NULL; + + if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } } + + return(returnObject); +} + +@end + +#pragma mark - +@interface JKDictionary : NSMutableDictionary { + NSUInteger count, capacity, mutations; + JKHashTableEntry *entry; +} +@end + +@implementation JKDictionary + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too. +static const NSUInteger jk_dictionaryCapacities[] = { + 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL, + 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL, + 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL, + 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL, + 111638519UL, 180634607UL, 292272623UL, 472907251UL +}; + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) { + NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = (NSUInteger)lround(floor(((double)count) * 1.33)); + while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } } + return(jk_dictionaryCapacities[bottom]); +} + +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + + NSUInteger capacityForCount = 0UL; + if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize + NSUInteger oldCapacity = dictionary->capacity; +#ifndef NS_BLOCK_ASSERTIONS + NSUInteger oldCount = dictionary->count; +#endif + JKHashTableEntry *oldEntry = dictionary->entry; + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; } + dictionary->capacity = capacityForCount; + dictionary->count = 0UL; + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < oldCapacity; idx++) { if(oldEntry[idx].key != NULL) { _JKDictionaryAddObject(dictionary, oldEntry[idx].keyHash, oldEntry[idx].key, oldEntry[idx].object); oldEntry[idx].keyHash = 0UL; oldEntry[idx].key = NULL; oldEntry[idx].object = NULL; } } + NSCParameterAssert((oldCount == dictionary->count)); + free(oldEntry); oldEntry = NULL; + } +} + +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL)); + JKDictionary *dictionary = NULL; + if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc. + dictionary->isa = _JKDictionaryClass; + if((dictionary = [dictionary init]) == NULL) { return(NULL); } + dictionary->capacity = _JKDictionaryCapacityForCount(count); + dictionary->count = 0UL; + + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); } + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); } + + dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(dictionary); +} + +- (void)dealloc +{ + if(JK_EXPECT_T(entry != NULL)) { + NSUInteger atEntry = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; } + if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; } + } + + free(entry); entry = NULL; + } + + [super dealloc]; +} + +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->entry); +} + +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->capacity); +} + +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) { + NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity)); + CFRelease(entry->key); entry->key = NULL; + CFRelease(entry->object); entry->object = NULL; + entry->keyHash = 0UL; + dictionary->count--; + // In order for certain invariants that are used to speed up the search for a particular key, we need to "re-add" all the entries in the hash table following this entry until we hit a NULL entry. + NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL; + NSCParameterAssert((removeIdx < dictionary->capacity)); + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(atEntry->key == NULL) { break; } + NSUInteger keyHash = atEntry->keyHash; + id key = atEntry->key, object = atEntry->object; + NSCParameterAssert(object != NULL); + atEntry->keyHash = 0UL; + atEntry->key = NULL; + atEntry->object = NULL; + NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL; + for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) { + JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)]; + if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; } + } + } +} + +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) { + NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL)); + NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(JK_EXPECT_F(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && (JK_EXPECT_F(key == atEntry->key) || JK_EXPECT_F(CFEqual(atEntry->key, key)))) { _JKDictionaryRemoveObjectWithEntry(dictionary, atEntry); } + if(JK_EXPECT_T(atEntry->key == NULL)) { NSCParameterAssert((atEntry->keyHash == 0UL) && (atEntry->object == NULL)); atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; } + } + + // We should never get here. If we do, we -release the key / object because it's our responsibility. + CFRelease(key); + CFRelease(object); +} + +- (NSUInteger)count +{ + return(count); +} + +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); } + NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL; + JKHashTableEntry *atEntry = NULL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity]; + if(JK_EXPECT_T(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && ((atEntry->key == aKey) || CFEqual(atEntry->key, aKey))) { NSCParameterAssert(atEntry->object != NULL); return(atEntry); break; } + if(JK_EXPECT_F(atEntry->key == NULL)) { NSCParameterAssert(atEntry->object == NULL); return(NULL); break; } // If the key was in the table, we would have found it by now. + } + return(NULL); +} + +- (id)objectForKey:(id)aKey +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + return((entryForKey != NULL) ? entryForKey->object : NULL); +} + +- (void)getObjects:(id *)objects andKeys:(id *)keys +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { + NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count)); + if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; } + if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; } + arrayIdx++; + } + } +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < capacity)) { if(JK_EXPECT_T(entry[state->state].key != NULL)) { stackbuf[enumeratedCount++] = entry[state->state].key; } state->state++; } + + return(enumeratedCount); +} + +- (NSEnumerator *)keyEnumerator +{ + return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]); +} + +- (void)setObject:(id)anObject forKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; } + + _JKDictionaryResizeIfNeccessary(self); +#ifndef __clang_analyzer__ + aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak", + anObject = [anObject retain]; // but this -retain doesn't!? +#endif // __clang_analyzer__ + _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectForKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + if(entryForKey != NULL) { + _JKDictionaryRemoveObjectWithEntry(self, entryForKey); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; + } +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]); +} + +@end + + + +#pragma mark - + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); } +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); } + +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c) { return((((currentHash << 5) + currentHash) + (c - 29)) ^ (currentHash >> 19)); } + + +static void jk_error(JKParseState *parseState, NSString *format, ...) { + NSCParameterAssert((parseState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + +#if 0 + const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex; + const unsigned char *lineEnd = lineStart; + const unsigned char *atCharacterPtr = NULL; + + for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } } + + NSString *lineString = @"", *carretString = @""; + if(lineStart < JK_END_STRING_PTR(parseState)) { + lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease]; + carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "]; + } +#endif + + if(parseState->error == NULL) { + parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey", + [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey", + //lineString, @"JKErrorLine0Key", + //carretString, @"JKErrorLine1Key", + NULL]]; + } +} + +#pragma mark - +#pragma mark Buffer and Object Stack management functions + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) { + if((managedBuffer->flags & JKManagedBufferMustFree)) { + if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; } + managedBuffer->flags &= ~JKManagedBufferMustFree; + } + + managedBuffer->bytes.ptr = NULL; + managedBuffer->bytes.length = 0UL; + managedBuffer->flags &= ~JKManagedBufferLocationMask; +} + +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) { + jk_managedBuffer_release(managedBuffer); + managedBuffer->bytes.ptr = ptr; + managedBuffer->bytes.length = length; + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack; +} + +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) { + size_t roundedUpNewSize = newSize; + + if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); } + + if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) { + if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) { + NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0); + unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr; + + if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); } + memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize)); + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree); + managedBuffer->bytes.ptr = newBuffer; + managedBuffer->bytes.length = roundedUpNewSize; + } else { + NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap)); + if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); } + managedBuffer->bytes.length = roundedUpNewSize; + } + } + + return(managedBuffer->bytes.ptr); +} + + + +static void jk_objectStack_release(JKObjectStack *objectStack) { + NSCParameterAssert(objectStack != NULL); + + NSCParameterAssert(objectStack->index <= objectStack->count); + size_t atIndex = 0UL; + for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) { + if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; } + if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; } + } + objectStack->index = 0UL; + + if(objectStack->flags & JKObjectStackMustFree) { + NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap); + if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; } + if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; } + if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; } + objectStack->flags &= ~JKObjectStackMustFree; + } + + objectStack->objects = NULL; + objectStack->keys = NULL; + objectStack->cfHashes = NULL; + + objectStack->count = 0UL; + objectStack->flags &= ~JKObjectStackLocationMask; +} + +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) { + NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL)); + jk_objectStack_release(objectStack); + objectStack->objects = objects; + objectStack->keys = keys; + objectStack->cfHashes = cfHashes; + objectStack->count = count; + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack; +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif +} + +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) { + size_t roundedUpNewCount = newCount; + int returnCode = 0; + + void **newObjects = NULL, **newKeys = NULL; + CFHashCode *newCFHashes = NULL; + + if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); } + + if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) { + if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) { + NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0); + + if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + + if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode)); + + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree); + objectStack->objects = newObjects; newObjects = NULL; + objectStack->keys = newKeys; newKeys = NULL; + objectStack->cfHashes = newCFHashes; newCFHashes = NULL; + objectStack->count = roundedUpNewCount; + } else { + NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap)); + if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; } + if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; } + if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; } + +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif + objectStack->count = roundedUpNewCount; + } + } + + errorExit: + if(newObjects != NULL) { free(newObjects); newObjects = NULL; } + if(newKeys != NULL) { free(newKeys); newKeys = NULL; } + if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; } + + return(returnCode); +} + +//////////// +#pragma mark - +#pragma mark Unicode related functions + +JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) { + ConversionResult result = conversionOK; + UTF32 ch = *u32CodePoint; + + if(JK_EXPECT_F(ch >= UNI_SUR_HIGH_START) && (JK_EXPECT_T(ch <= UNI_SUR_LOW_END))) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch >= 0xFDD0U) && (JK_EXPECT_F(ch <= 0xFDEFU) || JK_EXPECT_F((ch & 0xFFFEU) == 0xFFFEU)) && JK_EXPECT_T(ch <= 0x10FFFFU)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + + finished: + *u32CodePoint = ch; + return(result); +} + + +static int isLegalUTF8(const UTF8 *source, size_t length) { + const UTF8 *srcptr = source + length; + UTF8 a; + + switch(length) { + default: return(0); // Everything else falls through when "true"... + case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); } + + switch(*source) { // no fall-through in this inner switch + case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break; + case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break; + case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break; + case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break; + default: if(JK_EXPECT_F(a < 0x80)) { return(0); } + } + + case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); } + } + + if(JK_EXPECT_F(*source > 0xF4)) { return(0); } + + return(1); +} + +static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) { + ConversionResult result = conversionOK; + const UTF8 *source = sourceStart; + UTF32 ch = 0UL; + +#if !defined(JK_FAST_TRAILING_BYTES) + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; +#else + unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25); +#endif + + if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) { + source++; + while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; } + NSCParameterAssert(source <= sourceEnd); + result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal; + ch = UNI_REPLACEMENT_CHAR; + goto finished; + } + + switch(extraBytesToRead) { // The cases all fall through. + case 5: ch += *source++; ch <<= 6; + case 4: ch += *source++; ch <<= 6; + case 3: ch += *source++; ch <<= 6; + case 2: ch += *source++; ch <<= 6; + case 1: ch += *source++; ch <<= 6; + case 0: ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + result = isValidCodePoint(&ch); + + finished: + *nextUTF8 = source; + *convertedUTF32 = ch; + + return(result); +} + + +static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) { + const UTF32 byteMask = 0xBF, byteMark = 0x80; + ConversionResult result = conversionOK; + UTF8 *target = *targetStart; + UTF32 ch = u32CodePoint; + unsigned short bytesToWrite = 0; + + result = isValidCodePoint(&ch); + + // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars. + if(ch < (UTF32)0x80) { bytesToWrite = 1; } + else if(ch < (UTF32)0x800) { bytesToWrite = 2; } + else if(ch < (UTF32)0x10000) { bytesToWrite = 3; } + else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } + else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } + + target += bytesToWrite; + if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; } + + switch (bytesToWrite) { // note: everything falls through. + case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); + } + + target += bytesToWrite; + + finished: + *targetStart = target; + return(result); +} + +JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) { + UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx]; + ConversionResult result; + + if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } } + size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len; + + while(*tokenBufferIdx < nextIdx) { *stringHash = jk_calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } + + return(0); +} + +//////////// +#pragma mark - +#pragma mark Decoding / parsing / deserializing functions + +static int jk_parse_string(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1; + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atStringCharacter = stringStart; + unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr; + size_t tokenStartIndex = parseState->atIndex; + size_t tokenBufferIdx = 0UL; + + int onlySimpleString = 1, stringState = JSONStringStateStart; + uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U; + uint32_t escapedUnicodeCodePoint = 0U; + JKHash stringHash = JK_HASH_INIT; + + while(1) { + unsigned long currentChar; + + if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; } + + if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; } + stringHash = jk_calculateHash(stringHash, currentChar); + while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } + continue; + } else { + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; } + + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { + switchToSlowPath: + onlySimpleString = 0; + stringState = JSONStringStateParsing; + tokenBufferIdx = (atStringCharacter - stringStart) - 1L; + if(JK_EXPECT_F((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length)) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + memcpy(tokenBuffer, stringStart, tokenBufferIdx); + goto slowMatch; + } + + if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } + + stringHash = jk_calculateHash(stringHash, currentChar); + } + } + + slowMatch: + + for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) { + if((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + + NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); + + unsigned long currentChar = (*atStringCharacter), escapedChar; + + if(JK_EXPECT_T(stringState == JSONStringStateParsing)) { + if(JK_EXPECT_T(currentChar >= 0x20UL)) { + if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; } + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; } + stringHash = jk_calculateHash(stringHash, currentChar); + tokenBuffer[tokenBufferIdx++] = currentChar; + continue; + } else { // UTF8 sequence + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { + if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(jk_string_add_unicodeCodePoint(parseState, u32ch, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + atStringCharacter = nextValidCharacter - 1; + continue; + } else { + while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } + atStringCharacter--; + continue; + } + } + } else { // currentChar < 0x20 + jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; + } + + } else { // stringState != JSONStringStateParsing + int isSurrogate = 1; + + switch(stringState) { + case JSONStringStateEscape: + switch(currentChar) { + case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break; + + case 'b': escapedChar = '\b'; goto parsedEscapedChar; + case 'f': escapedChar = '\f'; goto parsedEscapedChar; + case 'n': escapedChar = '\n'; goto parsedEscapedChar; + case 'r': escapedChar = '\r'; goto parsedEscapedChar; + case 't': escapedChar = '\t'; goto parsedEscapedChar; + case '\\': escapedChar = '\\'; goto parsedEscapedChar; + case '/': escapedChar = '/'; goto parsedEscapedChar; + case '"': escapedChar = '"'; goto parsedEscapedChar; + + parsedEscapedChar: + stringState = JSONStringStateParsing; + stringHash = jk_calculateHash(stringHash, escapedChar); + tokenBuffer[tokenBufferIdx++] = escapedChar; + break; + + default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break; + } + break; + + case JSONStringStateEscapedUnicode1: + case JSONStringStateEscapedUnicode2: + case JSONStringStateEscapedUnicode3: + case JSONStringStateEscapedUnicode4: isSurrogate = 0; + case JSONStringStateEscapedUnicodeSurrogate1: + case JSONStringStateEscapedUnicodeSurrogate2: + case JSONStringStateEscapedUnicodeSurrogate3: + case JSONStringStateEscapedUnicodeSurrogate4: + { + uint16_t hexValue = 0U; + + switch(currentChar) { + case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex; + case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex; + case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex; + + parsedHex: + if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; } + + if(stringState == JSONStringStateEscapedUnicode4) { + if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) { + if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; } + else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + } + else { escapedUnicodeCodePoint = escapedUnicode1; } + } + + if(stringState == JSONStringStateEscapedUnicodeSurrogate4) { + if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; } + } + + if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) { + if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + stringState = JSONStringStateParsing; + if(jk_string_add_unicodeCodePoint(parseState, escapedUnicodeCodePoint, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + } + else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; } + break; + + default: jk_error(parseState, @"Unexpected character found in \\u Unicode escape sequence. Found '%c', expected [0-9a-fA-F].", currentChar); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + break; + + case JSONStringStateEscapedNeedEscapeForSurrogate: + if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter--; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + case JSONStringStateEscapedNeedEscapedUForSurrogate: + if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter -= 2; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + } + +finishedParsing: + + if(JK_EXPECT_T(stringState == JSONStringStateFinished)) { + NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter); + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex; + parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr); + + if(JK_EXPECT_T(onlySimpleString)) { + NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer)); + parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1; + parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL; + } else { + parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr; + parseState->token.value.ptrRange.length = tokenBufferIdx; + } + + parseState->token.value.hash = stringHash; + parseState->token.value.type = JKValueTypeString; + parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr); + } + + if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); } + return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1); +} + +static int jk_parse_number(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *numberStart = JK_AT_STRING_PTR(parseState); + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atNumberCharacter = NULL; + int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0; + size_t startingIndex = parseState->atIndex; + + for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) { + unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL; + + switch(numberState) { + case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; } + case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; } + else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; } + else { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; } + case JSONNumberStateFractionalNumberStart: + case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; } + else { numberState = JSONNumberStateExponent; } break; } + case JSONNumberStateWholeNumberZero: + case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; } + case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; } + case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; } + break; + default: /* XXX Add error message */ numberState = JSONNumberStateError; break; + } + } + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex; + parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup; + parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr; + + if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) { + unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL]; + unsigned char *endOfNumber = NULL; + + memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length); + numberTempBuf[parseState->token.tokenPtrRange.length] = 0; + + errno = 0; + + // Treat "-0" as a floating point number, which is capable of representing negative zeros. + if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; } + + if(isFloatingPoint) { + parseState->token.value.number.doubleValue = strtod((const char *)numberTempBuf, (char **)&endOfNumber); // strtod is documented to return U+2261 (identical to) 0.0 on an underflow error (along with setting errno to ERANGE). + parseState->token.value.type = JKValueTypeDouble; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue; + parseState->token.value.ptrRange.length = sizeof(double); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type); + } else { + if(isNegative) { + parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue; + parseState->token.value.ptrRange.length = sizeof(long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue; + } else { + parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeUnsignedLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue; + parseState->token.value.ptrRange.length = sizeof(unsigned long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue; + } + } + + if(JK_EXPECT_F(errno != 0)) { + numberState = JSONNumberStateError; + if(errno == ERANGE) { + switch(parseState->token.value.type) { + case JKValueTypeDouble: jk_error(parseState, @"The value '%s' could not be represented as a 'double' due to %s.", numberTempBuf, (parseState->token.value.number.doubleValue == 0.0) ? "underflow" : "overflow"); break; // see above for == 0.0. + case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + } + } + if(JK_EXPECT_F(endOfNumber != &numberTempBuf[parseState->token.tokenPtrRange.length]) && JK_EXPECT_F(numberState != JSONNumberStateError)) { numberState = JSONNumberStateError; jk_error(parseState, @"The conversion function did not consume all of the number tokens characters."); } + + size_t hashIndex = 0UL; + for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = jk_calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } + } + + if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); } + return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1); +} + +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) { + parseState->token.tokenPtrRange.ptr = ptr; + parseState->token.tokenPtrRange.length = length; + parseState->token.type = type; + parseState->atIndex += advanceBy; +} + +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) { + NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState))); + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); } + + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); } + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); } + if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); } + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); } + } + + return(0UL); +} + +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) { + size_t newlineAdvanceAtIndex = 0UL; + if(JK_EXPECT_F((newlineAdvanceAtIndex = jk_parse_is_newline(parseState, JK_AT_STRING_PTR(parseState))) > 0UL)) { parseState->lineNumber++; parseState->atIndex += (newlineAdvanceAtIndex - 1UL); parseState->lineStartIndex = parseState->atIndex + 1UL; return(1); } + return(0); +} + +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) { +#ifndef __clang_analyzer__ + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; } + if(jk_parse_skip_newline(parseState)) { continue; } + if(parseState->parseOptionFlags & JKParseOptionComments) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) { + if((*(atCharacterPtr + 1)) == '/') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { break; } } + continue; + } + if((*(atCharacterPtr + 1)) == '*') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(jk_parse_skip_newline(parseState)) { continue; } + if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; } + } + continue; + } + } + } + break; + } +#endif +} + +static int jk_parse_next_token(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + unsigned char currentCharacter = 0U; + int stopParsing = 0; + + parseState->prev_atIndex = parseState->atIndex; + parseState->prev_lineNumber = parseState->lineNumber; + parseState->prev_lineStartIndex = parseState->lineStartIndex; + + jk_parse_skip_whitespace(parseState); + + if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) { + currentCharacter = *atCharacterPtr; + + if(JK_EXPECT_T(currentCharacter == '"')) { if(JK_EXPECT_T((stopParsing = jk_parse_string(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeString, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); } + else if((JK_EXPECT_T(currentCharacter >= '0') && JK_EXPECT_T(currentCharacter <= '9')) || JK_EXPECT_T(currentCharacter == '-')) { if(JK_EXPECT_T((stopParsing = jk_parse_number(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeNumber, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); } + + else if(JK_EXPECT_T(currentCharacter == 't')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'r')) && (JK_EXPECT_T(atCharacterPtr[2] == 'u')) && (JK_EXPECT_T(atCharacterPtr[3] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeTrue, 4UL); } } + else if(JK_EXPECT_T(currentCharacter == 'f')) { if(!((JK_EXPECT_T((atCharacterPtr + 5UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'a')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 's')) && (JK_EXPECT_T(atCharacterPtr[4] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 5UL, JKTokenTypeFalse, 5UL); } } + else if(JK_EXPECT_T(currentCharacter == 'n')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'u')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 'l')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeNull, 4UL); } } + else { stopParsing = 1; /* XXX Add error message */ } + } + + if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); } + return(stopParsing); +} + +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) { + NSString *acceptStrings[16]; + int acceptIdx = 0; + if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; } + if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; } + if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; } + if(acceptIdx == 1) { jk_error(parseState, @"Expected %@, not '%*.*s'", acceptStrings[0], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 2) { jk_error(parseState, @"Expected %@ or %@, not '%*.*s'", acceptStrings[0], acceptStrings[1], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 3) { jk_error(parseState, @"Expected %@, %@, or %@, not '%*.*s", acceptStrings[0], acceptStrings[1], acceptStrings[2], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } +} + +static void *jk_parse_array(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedArray = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [array] objectsIndex > %zu, resize failed? %@ line %#ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { + void *object = NULL; +#ifndef NS_BLOCK_ASSERTIONS + parseState->objectStack.objects[parseState->objectStack.index] = NULL; + parseState->objectStack.keys [parseState->objectStack.index] = NULL; +#endif + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL"); stopParsing = 1; break; } else { parseState->objectStack.objects[parseState->objectStack.index++] = object; arrayState = JKParseAcceptCommaOrEnd; } + break; + case JKTokenTypeArrayEnd: if(JK_EXPECT_T(arrayState & JKParseAcceptEnd)) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedArray = (void *)_JKArrayCreate((id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ']'."); } stopParsing = 1; break; + case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedArray == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedArray); +} + +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) { + void *parsedDictionary = NULL; + + parseState->objectStack.index--; + + parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); + + return(parsedDictionary); +} + +static void *jk_parse_dictionary(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int dictState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedDictionary = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [dictionary] objectsIndex > %zu, resize failed? %@ line #%ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + size_t objectStackIndex = parseState->objectStack.index++; + parseState->objectStack.keys[objectStackIndex] = NULL; + parseState->objectStack.objects[objectStackIndex] = NULL; + void *key = NULL, *object = NULL; + + if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) { + switch(parseState->token.type) { + case JKTokenTypeString: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; } + if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; } + else { + parseState->objectStack.keys[objectStackIndex] = key; + if(JK_EXPECT_T(parseState->token.value.cacheItem != NULL)) { if(JK_EXPECT_F(parseState->token.value.cacheItem->cfHash == 0UL)) { parseState->token.value.cacheItem->cfHash = CFHash(key); } parseState->objectStack.cfHashes[objectStackIndex] = parseState->token.value.cacheItem->cfHash; } + else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); } + } + break; + + case JKTokenTypeObjectEnd: if((JK_EXPECT_T(dictState & JKParseAcceptEnd))) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedDictionary = jk_create_dictionary(parseState, startingObjectIndex); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected '}'."); } stopParsing = 1; break; + case JKTokenTypeComma: if((JK_EXPECT_T(dictState & JKParseAcceptComma))) { dictState = JKParseAcceptValue; parseState->objectStack.index--; continue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + + if(JK_EXPECT_T(stopParsing == 0)) { + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { if(JK_EXPECT_F(parseState->token.type != JKTokenTypeSeparator)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Expected ':'."); stopParsing = 1; } } + } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL."); stopParsing = 1; break; } else { parseState->objectStack.objects[objectStackIndex] = object; dictState = JKParseAcceptCommaOrEnd; } + break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedDictionary == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.keys[idx] != NULL) { CFRelease(parseState->objectStack.keys[idx]); parseState->objectStack.keys[idx] = NULL; } if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedDictionary); +} + +static id json_parse_it(JKParseState *parseState) { + id parsedObject = NULL; + int stopParsing = 0; + + while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) { + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break; + default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break; + } + } + } + + NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + + if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); } + if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); } + + if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_parse_skip_whitespace(parseState); + if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining."); + parsedObject = NULL; + } + } + + return(parsedObject); +} + +//////////// +#pragma mark - +#pragma mark Object cache + +// This uses a Galois Linear Feedback Shift Register (LFSR) PRNG to pick which item in the cache to age. It has a period of (2^32)-1. +// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. The LFSR is initalized to 1 in -initWithParseOptions: +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U); + parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1; +} + +// The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts. +// +// The hash table is a linear C array of JKTokenCacheItem. The terms "item" and "bucket" are synonymous with the index in to the cache array, i.e. cache.items[bucket]. +// +// Items in the cache have an age associated with them. An items age is incremented using saturating unsigned arithmetic and decremeted using unsigned right shifts. +// Thus, an items age is managed using an AIMD policy- additive increase, multiplicative decrease. All age calculations and manipulations are branchless. +// The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits. +// +// A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0. +// +// When an item is found in the cache, it's age is incremented. +// If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items. +// +// If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache. + +static void *jk_cachedObjects(JKParseState *parseState) { + unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL; + void *parsedAtom = NULL; + + if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); } + + for(x = 0UL; x < JK_CACHE_PROBES; x++) { + if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; } + + if((JK_EXPECT_T(parseState->cache.items[bucket].hash == parseState->token.value.hash)) && (JK_EXPECT_T(parseState->cache.items[bucket].size == parseState->token.value.ptrRange.length)) && (JK_EXPECT_T(parseState->cache.items[bucket].type == parseState->token.value.type)) && (JK_EXPECT_T(parseState->cache.items[bucket].bytes != NULL)) && (JK_EXPECT_T(memcmp(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) { + parseState->cache.age[bucket] = (((uint32_t)parseState->cache.age[bucket]) + 1U) - (((((uint32_t)parseState->cache.age[bucket]) + 1U) >> 31) ^ 1U); + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + NSCParameterAssert(parseState->cache.items[bucket].object != NULL); + return((void *)CFRetain(parseState->cache.items[bucket].object)); + } else { + if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; } + if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); } + // This is the open addressing function. The values length and type are used as a form of "double hashing" to distribute values with the same effective value hash across different object cache buckets. + // The values type is a prime number that is relatively coprime to the other primes in the set of value types and the number of hash table buckets. + bucket = (parseState->token.value.hash + (parseState->token.value.ptrRange.length * (x + 1UL)) + (parseState->token.value.type * (x + 1UL)) + (3UL * (x + 1UL))) & (parseState->cache.count - 1UL); + } + } + + switch(parseState->token.value.type) { + case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break; + case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: + if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); } + else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); } + break; + case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) { + bucket = useableBucket; + if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; } + + if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) { + memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length); + parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom); + parseState->cache.items[bucket].hash = parseState->token.value.hash; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length; + parseState->cache.items[bucket].type = parseState->token.value.type; + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + parseState->cache.age[bucket] = JK_INIT_CACHE_AGE; + } else { // The realloc failed, so clear the appropriate fields. + parseState->cache.items[bucket].hash = 0UL; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = 0UL; + parseState->cache.items[bucket].type = 0UL; + } + } + + return(parsedAtom); +} + + +static void *jk_object_for_token(JKParseState *parseState) { + void *parsedAtom = NULL; + + parseState->token.value.cacheItem = NULL; + switch(parseState->token.type) { + case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break; + case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break; + case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break; + case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break; + case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break; + default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + return(parsedAtom); +} + +#pragma mark - +@implementation JSONDecoder + ++ (id)decoder +{ + return([self decoderWithParseOptions:JKParseOptionStrict]); +} + ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]); +} + +- (id)init +{ + return([self initWithParseOptions:JKParseOptionStrict]); +} + +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + if((self = [super init]) == NULL) { return(NULL); } + + if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; } + + if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; } + + parseState->parseOptionFlags = parseOptionFlags; + + parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL; + parseState->objectStack.roundSizeUpToMultipleOf = 2048UL; + + parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass; + parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp; + parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp; + + parseState->cache.prng_lfsr = 1U; + parseState->cache.count = JK_CACHE_SLOTS; + if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; } + + return(self); + + errorExit: + if(self) { [self autorelease]; self = NULL; } + return(NULL); +} + +// This is here primarily to support the NSString and NSData convenience functions so the autoreleased JSONDecoder can release most of its resources before the pool pops. +static void _JSONDecoderCleanup(JSONDecoder *decoder) { + if((decoder != NULL) && (decoder->parseState != NULL)) { + jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer); + jk_objectStack_release(&decoder->parseState->objectStack); + + [decoder clearCache]; + if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; } + + free(decoder->parseState); decoder->parseState = NULL; + } +} + +- (void)dealloc +{ + _JSONDecoderCleanup(self); + [super dealloc]; +} + +- (void)clearCache +{ + if(JK_EXPECT_T(parseState != NULL)) { + if(JK_EXPECT_T(parseState->cache.items != NULL)) { + size_t idx = 0UL; + for(idx = 0UL; idx < parseState->cache.count; idx++) { + if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; } + if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; } + memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem)); + parseState->cache.age[idx] = 0U; + } + } + } +} + +// This needs to be completely rewritten. +static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) { + NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->stringBuffer.bytes.ptr = string; + parseState->stringBuffer.bytes.length = length; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = (mutableCollections == NO) ? NO : YES; + + unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer)); + + void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64); + void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64); + CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64); + jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS); + + id parsedJSON = json_parse_it(parseState); + + if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; } + + jk_managedBuffer_release(&parseState->token.tokenBuffer); + jk_objectStack_release(&parseState->objectStack); + + parseState->stringBuffer.bytes.ptr = NULL; + parseState->stringBuffer.bytes.length = 0UL; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = NO; + + return(parsedJSON); +} + +//////////// +#pragma mark Deprecated as of v1.4 +//////////// + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error +{ + return([self objectWithUTF8String:string length:length error:error]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData: instead. +- (id)parseJSONData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData:error: instead. +- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error +{ + return([self objectWithData:jsonData error:error]); +} + +//////////// +#pragma mark Methods that return immutable collection objects +//////////// + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error)); +} + +- (id)objectWithData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +//////////// +#pragma mark Methods that return mutable collection objects +//////////// + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self mutableObjectWithUTF8String:string length:length error:NULL]); +} + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error)); +} + +- (id)mutableObjectWithData:(NSData *)jsonData +{ + return([self mutableObjectWithData:jsonData error:NULL]); +} + +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +@end + +/* + The NSString and NSData convenience methods need a little bit of explanation. + + Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like + + const unsigned char *utf8String = (const unsigned char *)[self UTF8String]; + if(utf8String == NULL) { return(NULL); } + size_t utf8Length = strlen((const char *)utf8String); + return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]); + + This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is + allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed. + + In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead. + + Now we use an autoreleased CFMutableData that is sized to the UTF8 length of the NSString in question and is used to hold the UTF8 + conversion of said string. + + Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free + the buffer. + + Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved + to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls + _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used + again. + + If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the + autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in + autorelease limbo. It's more complicated for us, but a win for the user. + + Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our + requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in + autorelease limbo, but we've done our best to minimize that impact, so it all balances out. + */ + +@implementation NSString (JSONKitDeserializing) + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) { + id returnObject = NULL; + CFMutableDataRef mutableData = NULL; + JSONDecoder *decoder = NULL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString); + NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) { + UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData); + CFIndex usedBytes = 0L, convertedCount = 0L; + + convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { if(error != NULL) { *error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:[NSDictionary dictionaryWithObject:@"An error occurred converting the contents of a NSString to UTF8." forKey:NSLocalizedDescriptionKey]]; } goto exitNow; } + + if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + } + +exitNow: + if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); } + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)objectFromJSONString +{ + return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO)); +} + + +- (id)mutableObjectFromJSONString +{ + return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES)); +} + +@end + +@implementation NSData (JSONKitDeserializing) + +- (id)objectFromJSONData +{ + return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)mutableObjectFromJSONData +{ + return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + + +@end + +//////////// +#pragma mark - +#pragma mark Encoding / deserializing functions + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) { + NSCParameterAssert((encodeState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + + if(encodeState->error == NULL) { + encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + NULL]]; + } +} + +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) { + NSCParameterAssert(encodeState != NULL); + if(JK_EXPECT_T(cacheSlot != NULL)) { + NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex)); + cacheSlot->object = object; + cacheSlot->offset = startingAtIndex; + cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex); + } +} + +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) { + va_list varArgsList, varArgsListCopy; + va_start(varArgsList, format); + va_copy(varArgsListCopy, varArgsList); + + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + + ssize_t formattedStringLength = 0L; + int returnValue = 0; + + if(JK_EXPECT_T((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsList)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { + NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)); + if(JK_EXPECT_F(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (formattedStringLength * 2UL)+ 4096UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); returnValue = 1; goto exitNow; } + if(JK_EXPECT_F((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsListCopy)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { jk_encode_error(encodeState, @"vsnprintf failed unexpectedly."); returnValue = 1; goto exitNow; } + } + +exitNow: + va_end(varArgsList); + va_end(varArgsListCopy); + if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); } + return(returnValue); +} + +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + if(JK_EXPECT_F(((encodeState->atIndex + strlen(format) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + strlen(format) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + size_t formatIdx = 0UL; + for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) { + NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_T(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n'; + size_t depthWhiteSpace = 0UL; + for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + return(0); +} + +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (format != NULL) && ((depthChange >= -1L) && (depthChange <= 1L)) && ((encodeState->depth == 0UL) ? (depthChange >= 0L) : 1) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->depth += depthChange; + if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + else { + if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; + if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + } + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + return(0); +} + +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL)); + if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; } + else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); } + return(0); +} + +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex)); + if(JK_EXPECT_F((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < (length + 4UL))) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL + length) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } } + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length); + encodeState->atIndex += length; + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) { + return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) ); +} + +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL)); + + id object = (id)objectPtr, encodeCacheObject = object; + int isClass = JKClassUnknown; + size_t startingAtIndex = encodeState->atIndex; + + JKHash objectHash = jk_encode_object_hash(objectPtr); + JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS]; + + if(JK_EXPECT_T(cacheSlot->object == object)) { + NSCParameterAssert((cacheSlot->object != NULL) && + (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) && + (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length))); + if(JK_EXPECT_F(((encodeState->atIndex + cacheSlot->length + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + cacheSlot->length + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex))); + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length); + encodeState->atIndex += cacheSlot->length; + return(0); + } + + // When we encounter a class that we do not handle, and we have either a delegate or block that the user supplied to format unsupported classes, + // we "re-run" the object check. However, we re-run the object check exactly ONCE. If the user supplies an object that isn't one of the + // supported classes, we fail the second time (i.e., double fault error). + BOOL rerunningAfterClassFormatter = NO; + rerunAfterClassFormatter:; + + // XXX XXX XXX XXX + // + // We need to work around a bug in 10.7, which breaks ABI compatibility with Objective-C going back not just to 10.0, but OpenStep and even NextStep. + // + // It has long been documented that "the very first thing that a pointer to an Objective-C object "points to" is a pointer to that objects class". + // + // This is euphemistically called "tagged pointers". There are a number of highly technical problems with this, most involving long passages from + // the C standard(s). In short, one can make a strong case, couched from the perspective of the C standard(s), that that 10.7 "tagged pointers" are + // fundamentally Wrong and Broken, and should have never been implemented. Assuming those points are glossed over, because the change is very clearly + // breaking ABI compatibility, this should have resulted in a minimum of a "minimum version required" bump in various shared libraries to prevent + // causes code that used to work just fine to suddenly break without warning. + // + // In fact, the C standard says that the hack below is "undefined behavior"- there is no requirement that the 10.7 tagged pointer hack of setting the + // "lower, unused bits" must be preserved when casting the result to an integer type, but this "works" because for most architectures + // `sizeof(long) == sizeof(void *)` and the compiler uses the same representation for both. (note: this is informal, not meant to be + // normative or pedantically correct). + // + // In other words, while this "works" for now, technically the compiler is not obligated to do "what we want", and a later version of the compiler + // is not required in any way to produce the same results or behavior that earlier versions of the compiler did for the statement below. + // + // Fan-fucking-tastic. + // + // Why not just use `object_getClass()`? Because `object->isa` reduces to (typically) a *single* instruction. Calling `object_getClass()` requires + // that the compiler potentially spill registers, establish a function call frame / environment, and finally execute a "jump subroutine" instruction. + // Then, the called subroutine must spend half a dozen instructions in its prolog, however many instructions doing whatever it does, then half a dozen + // instructions in its prolog. One instruction compared to dozens, maybe a hundred instructions. + // + // Yes, that's one to two orders of magnitude difference. Which is compelling in its own right. When going for performance, you're often happy with + // gains in the two to three percent range. + // + // XXX XXX XXX XXX + + + BOOL workAroundMacOSXABIBreakingBug = (JK_EXPECT_F(((NSUInteger)object) & 0x1)) ? YES : NO; + void *objectISA = (JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) ? NULL : *((void **)objectPtr); + if(JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) { goto slowClassLookup; } + + if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } + else { + slowClassLookup: + if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.stringClass = objectISA; } isClass = JKClassString; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.numberClass = objectISA; } isClass = JKClassNumber; } + else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.dictionaryClass = objectISA; } isClass = JKClassDictionary; } + else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.arrayClass = objectISA; } isClass = JKClassArray; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.nullClass = objectISA; } isClass = JKClassNull; } + else { + if((rerunningAfterClassFormatter == NO) && ( +#ifdef __BLOCKS__ + ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) || +#endif + ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; } + + if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); } + else { jk_encode_error(encodeState, @"Unable to serialize object class %@ that was returned by the unsupported class formatter. Original object class was %@.", (object == NULL) ? @"NULL" : NSStringFromClass([object class]), NSStringFromClass([encodeCacheObject class])); return(1); } + } + } + + // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray + // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro: + // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1; + + switch(isClass) { + case JKClassString: + { + { + const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman); + if(cStringPtr != NULL) { + const unsigned char *utf8String = cStringPtr; + size_t utf8Idx = 0UL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + if(JK_EXPECT_F(((encodeState->atIndex + (stringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (stringLength * 2UL) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; } + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + + slowUTF8Path: + { + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L; + + if(JK_EXPECT_F((size_t)maxStringUTF8Length > encodeState->utf8ConversionBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->utf8ConversionBuffer, maxStringUTF8Length + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + CFIndex usedBytes = 0L, convertedCount = 0L; + convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { jk_encode_error(encodeState, @"An error occurred converting the contents of a NSString to UTF8."); return(1); } + + if(JK_EXPECT_F((encodeState->atIndex + (maxStringUTF8Length * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (maxStringUTF8Length * 2UL) + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr; + + size_t utf8Idx = 0UL; + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + NSCParameterAssert((CFIndex)utf8Idx < usedBytes); + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); } + else { + utf8Idx = (nextValidCharacter - utf8String) - 1UL; + if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } } + else { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x\\u%4.4x", (0xd7c0U + (u32ch >> 10)), (0xdc00U + (u32ch & 0x3ffU))))) { return(1); } } + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + break; + + case JKClassNumber: + { + if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); } + else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); } + + const char *objCType = [object objCType]; + char anum[256], *aptr = &anum[255]; + int isNegative = 0; + unsigned long long ullv; + long long llv; + + if(JK_EXPECT_F(objCType == NULL) || JK_EXPECT_F(objCType[0] == 0) || JK_EXPECT_F(objCType[1] != 0)) { jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%s'", (objCType == NULL) ? "" : objCType); return(1); } + + switch(objCType[0]) { + case 'c': case 'i': case 's': case 'l': case 'q': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) { + if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; } + goto convertNumber; + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) { + convertNumber: + if(JK_EXPECT_F(ullv < 10ULL)) { *--aptr = ullv + '0'; } else { while(JK_EXPECT_T(ullv > 0ULL)) { *--aptr = (ullv % 10ULL) + '0'; ullv /= 10ULL; NSCParameterAssert(aptr > anum); } } + if(isNegative) { *--aptr = '-'; } + NSCParameterAssert(aptr > anum); + return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr)); + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'f': case 'd': + { + double dv; + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) { + if(JK_EXPECT_F(!isfinite(dv))) { jk_encode_error(encodeState, @"Floating point values must be finite. JSON does not support NaN or Infinity."); return(1); } + return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv)); + } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); } + } + break; + default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break; + } + } + break; + + case JKClassArray: + { + int printComma = 0; + CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L; + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); } + if(JK_EXPECT_F(arrayCount > 1020L)) { + for(id arrayObject in object) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, arrayObject))) { return(1); } } + } else { + void *objects[1024]; + CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects); + for(idx = 0L; idx < arrayCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } } + } + return(jk_encode_write1(encodeState, -1L, "]")); + } + break; + + case JKClassDictionary: + { + int printComma = 0; + CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L; + id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object; + + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); } + if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) { + for(id keyObject in enumerateObject) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + void *keyObjectISA = *((void **)keyObject); + if(JK_EXPECT_F((keyObjectISA != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); } + } + } else { + void *keys[1024], *objects[1024]; + CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects); + for(idx = 0L; idx < dictionaryCount; idx++) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + void *keyObjectISA = *((void **)keys[idx]); + if(JK_EXPECT_F(keyObjectISA != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } + } + } + return(jk_encode_write1(encodeState, -1L, "}")); + } + break; + + case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break; + + default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break; + } + + return(0); +} + + +@implementation JKSerializer + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]); +} + +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ +#ifndef __BLOCKS__ +#pragma unused(block) +#endif + NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) && + (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) && + (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1)); + + id returnObject = NULL; + + if(encodeState != NULL) { [self releaseState]; } + if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); } + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + + if(delegate != NULL) { + if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; } + if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; } + encodeState->classFormatterDelegate = delegate; + encodeState->classFormatterSelector = selector; + encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector]; + NSCParameterAssert(encodeState->classFormatterIMP != NULL); + } + +#ifdef __BLOCKS__ + encodeState->classFormatterBlock = block; +#endif + encodeState->serializeOptionFlags = optionFlags; + encodeState->encodeOption = encodeOption; + encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL); + encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL; + + unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer)); + + unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer)); + + if(((encodeOption & JKEncodeOptionCollectionObj) != 0UL) && (([object isKindOfClass:[NSArray class]] == NO) && ([object isKindOfClass:[NSDictionary class]] == NO))) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSArray or NSDictionary.", NSStringFromClass([object class])); goto errorExit; } + if(((encodeOption & JKEncodeOptionStringObj) != 0UL) && ([object isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSString.", NSStringFromClass([object class])); goto errorExit; } + + if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) { + BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO; + + if((encodeState->atIndex < 2UL)) + if((stackBuffer == NO) && ((encodeState->stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState->stringBuffer.bytes.ptr, encodeState->atIndex + 16UL)) == NULL)) { jk_encode_error(encodeState, @"Unable to realloc buffer"); goto errorExit; } + + switch((encodeOption & JKEncodeOptionAsTypeMask)) { + case JKEncodeOptionAsData: + if(stackBuffer == YES) { if((returnObject = [(id)CFDataCreate( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + else { if((returnObject = [(id)CFDataCreateWithBytesNoCopy( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + break; + + case JKEncodeOptionAsString: + if(stackBuffer == YES) { if((returnObject = [(id)CFStringCreateWithBytes( NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + else { if((returnObject = [(id)CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + break; + + default: jk_encode_error(encodeState, @"Unknown encode as type."); break; + } + + if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; } + } + +errorExit: + if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; } + [self releaseState]; + + return(returnObject); +} + +- (void)releaseState +{ + if(encodeState != NULL) { + jk_managedBuffer_release(&encodeState->stringBuffer); + jk_managedBuffer_release(&encodeState->utf8ConversionBuffer); + free(encodeState); encodeState = NULL; + } +} + +- (void)dealloc +{ + [self releaseState]; + [super dealloc]; +} + +@end + +@implementation NSString (JSONKitSerializing) + +//////////// +#pragma mark Methods for serializing a single NSString. +//////////// + +// Useful for those who need to serialize just a NSString. Otherwise you would have to do something like [NSArray arrayWithObject:stringToBeJSONSerialized], serializing the array, and then chopping of the extra ^\[.*\]$ square brackets. + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSArray (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + + +#ifdef __BLOCKS__ + +@implementation NSArray (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +#endif // __BLOCKS__ + diff --git a/PSCollectionViewDemo/JSONKit/README.md b/PSCollectionViewDemo/JSONKit/README.md new file mode 100644 index 0000000..8b4a4d9 --- /dev/null +++ b/PSCollectionViewDemo/JSONKit/README.md @@ -0,0 +1,310 @@ +# JSONKit + +JSONKit is dual licensed under either the terms of the BSD License, or alternatively under the terms of the Apache License, Version 2.0.
+Copyright © 2011, John Engelhart. + +### A Very High Performance Objective-C JSON Library + +**UPDATE:** (2011/12/18) The benchmarks below were performed before Apples [`NSJSONSerialization`][NSJSONSerialization] was available (as of Mac OS X 10.7 and iOS 5). The obvious question is: Which is faster, [`NSJSONSerialization`][NSJSONSerialization] or JSONKit? According to [this site](http://www.bonto.ch/blog/2011/12/08/json-libraries-for-ios-comparison-updated/), JSONKit is faster than [`NSJSONSerialization`][NSJSONSerialization]. Some quick "back of the envelope" calculations using the numbers reported, JSONKit appears to be approximately 25% to 40% faster than [`NSJSONSerialization`][NSJSONSerialization], which is pretty significant. + + Parsing | Serializing +:---------:|:-------------: +Deserialize from JSON | Serialize to JSON +*23% Faster than Binary* .plist* !* | *549% Faster than Binary* .plist* !* + +* Benchmarking was performed on a MacBook Pro with a 2.66GHz Core 2. +* All JSON libraries were compiled with `gcc-4.2 -DNS_BLOCK_ASSERTIONS -O3 -arch x86_64`. +* Timing results are the average of 1,000 iterations of the user + system time reported by [`getrusage`][getrusage]. +* The JSON used was [`twitter_public_timeline.json`](https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json) from [samsoffes / json-benchmarks](https://github.com/samsoffes/json-benchmarks). +* Since the `.plist` format does not support serializing [`NSNull`][NSNull], the `null` values in the original JSON were changed to `"null"`. +* The [experimental](https://github.com/johnezang/JSONKit/tree/experimental) branch contains the `gzip` compression changes. + * JSONKit automagically links to `libz.dylib` on the fly at run time– no manual linking required. + * Parsing / deserializing will automagically decompress a buffer if it detects a `gzip` signature header. + * You can compress / `gzip` the serialized JSON by passing `JKSerializeOptionCompress` to `-JSONDataWithOptions:error:`. + +[JSON versus PLIST, the Ultimate Showdown](http://www.cocoanetics.com/2011/03/json-versus-plist-the-ultimate-showdown/) benchmarks the common JSON libraries and compares them to Apples `.plist` format. + +*** + +JavaScript Object Notation, or [JSON][], is a lightweight, text-based, serialization format for structured data that is used by many web-based services and API's. It is defined by [RFC 4627][]. + +JSON provides the following primitive types: + +* `null` +* Boolean `true` and `false` +* Number +* String +* Array +* Object (a.k.a. Associative Arrays, Key / Value Hash Tables, Maps, Dictionaries, etc.) + +These primitive types are mapped to the following Objective-C Foundation classes: + +JSON | Objective-C +-------------------|------------- +`null` | [`NSNull`][NSNull] +`true` and `false` | [`NSNumber`][NSNumber] +Number | [`NSNumber`][NSNumber] +String | [`NSString`][NSString] +Array | [`NSArray`][NSArray] +Object | [`NSDictionary`][NSDictionary] + +JSONKit uses Core Foundation internally, and it is assumed that Core Foundation ≡ Foundation for every equivalent base type, i.e. [`CFString`][CFString] ≡ [`NSString`][NSString]. + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119][]. + +### JSON To Objective-C Primitive Mapping Details + +* The [JSON specification][RFC 4627] is somewhat ambiguous about the details and requirements when it comes to Unicode, and it does not specify how Unicode issues and errors should be handled. Most of the ambiguity stems from the interpretation and scope [RFC 4627][] Section 3, Encoding: `JSON text SHALL be encoded in Unicode.` It is the authors opinion and interpretation that the language of [RFC 4627][] requires that a JSON implementation MUST follow the requirements specified in the [Unicode Standard][], and in particular the [Conformance][Unicode Standard - Conformance] chapter of the [Unicode Standard][], which specifies requirements related to handling, interpreting, and manipulating Unicode text. + + The default behavior for JSONKit is strict [RFC 4627][] conformance. It is the authors opinion and interpretation that [RFC 4627][] requires JSON to be encoded in Unicode, and therefore JSON that is not legal Unicode as defined by the [Unicode Standard][] is invalid JSON. Therefore, JSONKit will not accept JSON that contains ill-formed Unicode. The default, strict behavior implies that the `JKParseOptionLooseUnicode` option is not enabled. + + When the `JKParseOptionLooseUnicode` option is enabled, JSONKit follows the specifications and recommendations given in [The Unicode 6.0 standard, Chapter 3 - Conformance][Unicode Standard - Conformance], section 3.9 *Unicode Encoding Forms*. As a general rule of thumb, the Unicode code point `U+FFFD` is substituted for any ill-formed Unicode encountered. JSONKit attempts to follow the recommended *Best Practice for Using U+FFFD*: ***Replace each maximal subpart of an ill-formed subsequence by a single U+FFFD.*** + + The following Unicode code points are treated as ill-formed Unicode, and if `JKParseOptionLooseUnicode` is enabled, cause `U+FFFD` to be substituted in their place: + + `U+0000`.
+ `U+D800` thru `U+DFFF`, inclusive.
+ `U+FDD0` thru `U+FDEF`, inclusive.
+ U+nFFFE and U+nFFFF, where *n* is from `0x0` to `0x10` + + The code points `U+FDD0` thru `U+FDEF`, U+nFFFE, and U+nFFFF (where *n* is from `0x0` to `0x10`), are defined as ***Noncharacters*** by the Unicode standard and "should never be interchanged". + + An exception is made for the code point `U+0000`, which is legal Unicode. The reason for this is that this particular code point is used by C string handling code to specify the end of the string, and any such string handling code will incorrectly stop processing a string at the point where `U+0000` occurs. Although reasonable people may have different opinions on this point, it is the authors considered opinion that the risks of permitting JSON Strings that contain `U+0000` outweigh the benefits. One of the risks in allowing `U+0000` to appear unaltered in a string is that it has the potential to create security problems by subtly altering the semantics of the string which can then be exploited by a malicious attacker. This is similar to the issue of [arbitrarily deleting characters from Unicode text][Unicode_UTR36_Deleting]. + + [RFC 4627][] allows for these limitations under section 4, Parsers: `An implementation may set limits on the length and character contents of strings.` While the [Unicode Standard][] permits the mutation of the original JSON (i.e., substituting `U+FFFD` for ill-formed Unicode), [RFC 4627][] is silent on this issue. It is the authors opinion and interpretation that [RFC 4627][], section 3 – *Encoding*, `JSON text SHALL be encoded in Unicode.` implies that such mutations are not only permitted but MUST be expected by any strictly conforming [RFC 4627][] JSON implementation. The author feels obligated to note that this opinion and interpretation may not be shared by others and, in fact, may be a minority opinion and interpretation. You should be aware that any mutation of the original JSON may subtly alter its semantics and, as a result, may have security related implications for anything that consumes the final result. + + It is important to note that JSONKit will not delete characters from the JSON being parsed as this is a [requirement specified by the Unicode Standard][Unicode_UTR36_Deleting]. Additional information can be found in the [Unicode Security FAQ][Unicode_Security_FAQ] and [Unicode Technical Report #36 - Unicode Security Consideration][Unicode_UTR36], in particular the section on [non-visual security][Unicode_UTR36_NonVisualSecurity]. + +* The [JSON specification][RFC 4627] does not specify the details or requirements for JSON String values, other than such strings must consist of Unicode code points, nor does it specify how errors should be handled. While JSONKit makes an effort (subject to the reasonable caveats above regarding Unicode) to preserve the parsed JSON String exactly, it can not guarantee that [`NSString`][NSString] will preserve the exact Unicode semantics of the original JSON String. + + JSONKit does not perform any form of Unicode Normalization on the parsed JSON Strings, but can not make any guarantees that the [`NSString`][NSString] class will not perform Unicode Normalization on the parsed JSON String used to instantiate the [`NSString`][NSString] object. The [`NSString`][NSString] class may place additional restrictions or otherwise transform the JSON String in such a way so that the JSON String is not bijective with the instantiated [`NSString`][NSString] object. In other words, JSONKit can not guarantee that when you round trip a JSON String to a [`NSString`][NSString] and then back to a JSON String that the two JSON Strings will be exactly the same, even though in practice they are. For clarity, "exactly" in this case means bit for bit identical. JSONKit can not even guarantee that the two JSON Strings will be [Unicode equivalent][Unicode_equivalence], even though in practice they will be and would be the most likely cause for the two round tripped JSON Strings to no longer be bit for bit identical. + +* JSONKit maps `true` and `false` to the [`CFBoolean`][CFBoolean] values [`kCFBooleanTrue`][kCFBooleanTrue] and [`kCFBooleanFalse`][kCFBooleanFalse], respectively. Conceptually, [`CFBoolean`][CFBoolean] values can be thought of, and treated as, [`NSNumber`][NSNumber] class objects. The benefit to using [`CFBoolean`][CFBoolean] is that `true` and `false` JSON values can be round trip deserialized and serialized without conversion or promotion to a [`NSNumber`][NSNumber] with a value of `0` or `1`. + +* The [JSON specification][RFC 4627] does not specify the details or requirements for JSON Number values, nor does it specify how errors due to conversion should be handled. In general, JSONKit will not accept JSON that contains JSON Number values that it can not convert with out error or loss of precision. + + For non-floating-point numbers (i.e., JSON Number values that do not include a `.` or `e|E`), JSONKit uses a 64-bit C primitive type internally, regardless of whether the target architecture is 32-bit or 64-bit. For unsigned values (i.e., those that do not begin with a `-`), this allows for values up to 264-1 and up to -263 for negative values. As a special case, the JSON Number `-0` is treated as a floating-point number since the underlying floating-point primitive type is capable of representing a negative zero, whereas the underlying twos-complement non-floating-point primitive type can not. JSON that contains Number values that exceed these limits will fail to parse and optionally return a [`NSError`][NSError] object. The functions [`strtoll()`][strtoll] and [`strtoull()`][strtoull] are used to perform the conversions. + + The C `double` primitive type, or [IEEE 754 Double 64-bit floating-point][Double Precision], is used to represent floating-point JSON Number values. JSON that contains floating-point Number values that can not be represented as a `double` (i.e., due to over or underflow) will fail to parse and optionally return a [`NSError`][NSError] object. The function [`strtod()`][strtod] is used to perform the conversion. Note that the JSON standard does not allow for infinities or `NaN` (Not a Number). The conversion and manipulation of [floating-point values is non-trivial](http://www.validlab.com/goldberg/paper.pdf). Unfortunately, [RFC 4627][] is silent on how such details should be handled. You should not depend on or expect that when a floating-point value is round tripped that it will have the same textual representation or even compare equal. This is true even when JSONKit is used as both the parser and creator of the JSON, let alone when transferring JSON between different systems and implementations. + +* For JSON Objects (or [`NSDictionary`][NSDictionary] in JSONKit nomenclature), [RFC 4627][] says `The names within an object SHOULD be unique` (note: `name` is a `key` in JSONKit nomenclature). At this time the JSONKit behavior is `undefined` for JSON that contains names within an object that are not unique. However, JSONKit currently tries to follow a "the last key / value pair parsed is the one chosen" policy. This behavior is not finalized and should not be depended on. + + The previously covered limitations regarding JSON Strings have important consequences for JSON Objects since JSON Strings are used as the `key`. The [JSON specification][RFC 4627] does not specify the details or requirements for JSON Strings used as `keys` in JSON Objects, specifically what it means for two `keys` to compare equal. Unfortunately, because [RFC 4627][] states `JSON text SHALL be encoded in Unicode.`, this means that one must use the [Unicode Standard][] to interpret the JSON, and the [Unicode Standard][] allows for strings that are encoded with different Unicode Code Points to "compare equal". JSONKit uses [`NSString`][NSString] exclusively to manage the parsed JSON Strings. Because [`NSString`][NSString] uses [Unicode][Unicode Standard] as its basis, there exists the possibility that [`NSString`][NSString] may subtly and silently convert the Unicode Code Points contained in the original JSON String in to a [Unicode equivalent][Unicode_equivalence] string. Due to this, the JSONKit behavior for JSON Strings used as `keys` in JSON Objects that may be [Unicode equivalent][Unicode_equivalence] but not binary equivalent is `undefined`. + + **See also:**
+     [W3C - Requirements for String Identity Matching and String Indexing](http://www.w3.org/TR/charreq/#sec2) + +### Objective-C To JSON Primitive Mapping Details + +* When serializing, the top level container, and all of its children, are required to be *strictly* [invariant][wiki_invariant] during enumeration. This property is used to make certain optimizations, such as if a particular object has already been serialized, the result of the previous serialized `UTF8` string can be reused (i.e., the `UTF8` string of the previous serialization can simply be copied instead of performing all the serialization work again). While this is probably only of interest to those who are doing extraordinarily unusual things with the run-time or custom classes inheriting from the classes that JSONKit will serialize (i.e, a custom object whose value mutates each time it receives a message requesting its value for serialization), it also covers the case where any of the objects to be serialized are mutated during enumeration (i.e., mutated by another thread). The number of times JSONKit will request an objects value is non-deterministic, from a minimum of once up to the number of times it appears in the serialized JSON– therefore an object MUST NOT depend on receiving a message requesting its value each time it appears in the serialized output. The behavior is `undefined` if these requirements are violated. + +* The objects to be serialized MUST be acyclic. If the objects to be serialized contain circular references the behavior is `undefined`. For example, + + ```objective-c + [arrayOne addObject:arrayTwo]; + [arrayTwo addObject:arrayOne]; + id json = [arrayOne JSONString]; + ``` + + … will result in `undefined` behavior. + +* The contents of [`NSString`][NSString] objects are encoded as `UTF8` and added to the serialized JSON. JSONKit assumes that [`NSString`][NSString] produces well-formed `UTF8` Unicode and does no additional validation of the conversion. When `JKSerializeOptionEscapeUnicode` is enabled, JSONKit will encode Unicode code points that can be encoded as a single `UTF16` code unit as \uXXXX, and will encode Unicode code points that require `UTF16` surrogate pairs as \uhigh\ulow. While JSONKit makes every effort to serialize the contents of a [`NSString`][NSString] object exactly, modulo any [RFC 4627][] requirements, the [`NSString`][NSString] class uses the [Unicode Standard][] as its basis for representing strings. You should be aware that the [Unicode Standard][] defines [string equivalence][Unicode_equivalence] in a such a way that two strings that compare equal are not required to be bit for bit identical. Therefore there exists the possibility that [`NSString`][NSString] may mutate a string in such a way that it is [Unicode equivalent][Unicode_equivalence], but not bit for bit identical with the original string. + +* The [`NSDictionary`][NSDictionary] class allows for any object, which can be of any class, to be used as a `key`. JSON, however, only permits Strings to be used as `keys`. Therefore JSONKit will fail with an error if it encounters a [`NSDictionary`][NSDictionary] that contains keys that are not [`NSString`][NSString] objects during serialization. More specifically, the keys must return `YES` when sent [`-isKindOfClass:[NSString class]`][-isKindOfClass:]. + +* JSONKit will fail with an error if it encounters an object that is not a [`NSNull`][NSNull], [`NSNumber`][NSNumber], [`NSString`][NSString], [`NSArray`][NSArray], or [`NSDictionary`][NSDictionary] class object during serialization. More specifically, JSONKit will fail with an error if it encounters an object where [`-isKindOfClass:`][-isKindOfClass:] returns `NO` for all of the previously mentioned classes. + +* JSON does not allow for Numbers that are ±Infinity or ±NaN. Therefore JSONKit will fail with an error if it encounters a [`NSNumber`][NSNumber] that contains such a value during serialization. + +* Objects created with [`[NSNumber numberWithBool:YES]`][NSNumber_numberWithBool] and [`[NSNumber numberWithBool:NO]`][NSNumber_numberWithBool] will be mapped to the JSON values of `true` and `false`, respectively. More specifically, an object must have pointer equality with [`kCFBooleanTrue`][kCFBooleanTrue] or [`kCFBooleanFalse`][kCFBooleanFalse] (i.e., `if((id)object == (id)kCFBooleanTrue)`) in order to be mapped to the JSON values `true` and `false`. + +* [`NSNumber`][NSNumber] objects that are not booleans (as defined above) are sent [`-objCType`][-objCType] to determine what type of C primitive type they represent. Those that respond with a type from the set `cislq` are treated as `long long`, those that respond with a type from the set `CISLQB` are treated as `unsigned long long`, and those that respond with a type from the set `fd` are treated as `double`. [`NSNumber`][NSNumber] objects that respond with a type not in the set of types mentioned will cause JSONKit to fail with an error. + + More specifically, [`CFNumberGetValue(object, kCFNumberLongLongType, &longLong)`][CFNumberGetValue] is used to retrieve the value of both the signed and unsigned integer values, and the type reported by [`-objCType`][-objCType] is used to determine whether the result is signed or unsigned. For floating-point values, [`CFNumberGetValue`][CFNumberGetValue] is used to retrieve the value using [`kCFNumberDoubleType`][kCFNumberDoubleType] for the type argument. + + Floating-point numbers are converted to their decimal representation using the [`printf`][printf] format conversion specifier `%.17g`. Theoretically this allows up to a `float`, or [IEEE 754 Single 32-bit floating-point][Single Precision], worth of precision to be represented. This means that for practical purposes, `double` values are converted to `float` values with the associated loss of precision. The [RFC 4627][] standard is silent on how floating-point numbers should be dealt with and the author has found that real world JSON implementations vary wildly in how they handle this issue. Furthermore, the `%g` format conversion specifier may convert floating-point values that can be exactly represented as an integer to a textual representation that does not include a `.` or `e`– essentially silently promoting a floating-point value to an integer value (i.e, `5.0` becomes `5`). Because of these and many other issues surrounding the conversion and manipulation of floating-point values, you should not expect or depend on floating point values to maintain their full precision, or when round tripped, to compare equal. + + +### Reporting Bugs + +Please use the [github.com JSONKit Issue Tracker](https://github.com/johnezang/JSONKit/issues) to report bugs. + +The author requests that you do not file a bug report with JSONKit regarding problems reported by the `clang` static analyzer unless you first manually verify that it is an actual, bona-fide problem with JSONKit and, if appropriate, is not "legal" C code as defined by the C99 language specification. If the `clang` static analyzer is reporting a problem with JSONKit that is not an actual, bona-fide problem and is perfectly legal code as defined by the C99 language specification, then the appropriate place to file a bug report or complaint is with the developers of the `clang` static analyzer. + +### Important Details + +* JSONKit is not designed to be used with the Mac OS X Garbage Collection. The behavior of JSONKit when compiled with `-fobjc-gc` is `undefined`. It is extremely unlikely that Mac OS X Garbage Collection will ever be supported. + +* JSONKit is not designed to be used with [Objective-C Automatic Reference Counting (ARC)][ARC]. The behavior of JSONKit when compiled with `-fobjc-arc` is `undefined`. The behavior of JSONKit compiled without [ARC][] mixed with code that has been compiled with [ARC][] is normatively `undefined` since at this time no analysis has been done to understand if this configuration is safe to use. At this time, there are no plans to support [ARC][] in JSONKit. Although tenative, it is extremely unlikely that [ARC][] will ever be supported, for many of the same reasons that Mac OS X Garbage Collection is not supported. + +* The JSON to be parsed by JSONKit MUST be encoded as Unicode. In the unlikely event you end up with JSON that is not encoded as Unicode, you must first convert the JSON to Unicode, preferably as `UTF8`. One way to accomplish this is with the [`NSString`][NSString] methods [`-initWithBytes:length:encoding:`][NSString_initWithBytes] and [`-initWithData:encoding:`][NSString_initWithData]. + +* Internally, the low level parsing engine uses `UTF8` exclusively. The `JSONDecoder` method `-objectWithData:` takes a [`NSData`][NSData] object as its argument and it is assumed that the raw bytes contained in the [`NSData`][NSData] is `UTF8` encoded, otherwise the behavior is `undefined`. + +* It is not safe to use the same instantiated `JSONDecoder` object from multiple threads at the same time. If you wish to share a `JSONDecoder` between threads, you are responsible for adding mutex barriers to ensure that only one thread is decoding JSON using the shared `JSONDecoder` object at a time. + +### Tips for speed + +* Enable the `NS_BLOCK_ASSERTIONS` pre-processor flag. JSONKit makes heavy use of [`NSCParameterAssert()`][NSCParameterAssert] internally to ensure that various arguments, variables, and other state contains only legal and expected values. If an assertion check fails it causes a run time exception that will normally cause a program to terminate. These checks and assertions come with a price: they take time to execute and do not contribute to the work being performed. It is perfectly safe to enable `NS_BLOCK_ASSERTIONS` as JSONKit always performs checks that are required for correct operation. The checks performed with [`NSCParameterAssert()`][NSCParameterAssert] are completely optional and are meant to be used in "debug" builds where extra integrity checks are usually desired. While your mileage may vary, the author has found that adding `-DNS_BLOCK_ASSERTIONS` to an `-O2` optimization setting can generally result in an approximate 7-12% increase in performance. + +* Since the very low level parsing engine works exclusively with `UTF8` byte streams, anything that is not already encoded as `UTF8` must first be converted to `UTF8`. While JSONKit provides additions to the [`NSString`][NSString] class which allows you to conveniently convert JSON contained in a [`NSString`][NSString], this convenience does come with a price. JSONKit must allocate an autoreleased [`NSMutableData`][NSMutableData] large enough to hold the strings `UTF8` conversion and then convert the string to `UTF8` before it can begin parsing. This takes both memory and time. Once the parsing has finished, JSONKit sets the autoreleased [`NSMutableData`][NSMutableData] length to `0`, which allows the [`NSMutableData`][NSMutableData] to release the memory. This helps to minimize the amount of memory that is in use but unavailable until the autorelease pool pops. Therefore, if speed and memory usage are a priority, you should avoid using the [`NSString`][NSString] convenience methods if possible. + +* If you are receiving JSON data from a web server, and you are able to determine that the raw bytes returned by the web server is JSON encoded as `UTF8`, you should use the `JSONDecoder` method `-objectWithUTF8String:length:` which immediately begins parsing the pointers bytes. In practice, every JSONKit method that converts JSON to an Objective-C object eventually calls this method to perform the conversion. + +* If you are using one of the various ways provided by the `NSURL` family of classes to receive JSON results from a web server, which typically return the results in the form of a [`NSData`][NSData] object, and you are able to determine that the raw bytes contained in the [`NSData`][NSData] are encoded as `UTF8`, then you should use either the `JSONDecoder` method `objectWithData:` or the [`NSData`][NSData] method `-objectFromJSONData`. If are going to be converting a lot of JSON, the better choice is to instantiate a `JSONDecoder` object once and use the same instantiated object to perform all your conversions. This has two benefits: + 1. The [`NSData`][NSData] method `-objectFromJSONData` creates an autoreleased `JSONDecoder` object to perform the one time conversion. By instantiating a `JSONDecoder` object once and using the `objectWithData:` method repeatedly, you can avoid this overhead. + 2. The instantiated object cache from the previous JSON conversion is reused. This can result in both better performance and a reduction in memory usage if the JSON your are converting is very similar. A typical example might be if you are converting JSON at periodic intervals that consists of real time status updates. + +* On average, the JSONData… methods are nearly four times faster than the JSONString… methods when serializing a [`NSDictionary`][NSDictionary] or [`NSArray`][NSArray] to JSON. The difference in speed is due entirely to the instantiation overhead of [`NSString`][NSString]. + +* If at all possible, use [`NSData`][NSData] instead of [`NSString`][NSString] methods when processing JSON. This avoids the sometimes significant conversion overhead that [`NSString`][NSString] performs in order to provide an object oriented interface for its contents. For many uses, using [`NSString`][NSString] is not needed and results in wasted effort– for example, using JSONKit to serialize a [`NSDictionary`][NSDictionary] or [`NSArray`][NSArray] to a [`NSString`][NSString]. This [`NSString`][NSString] is then passed to a method that sends the JSON to a web server, and this invariably requires converting the [`NSString`][NSString] to [`NSData`][NSData] before it can be sent. In this case, serializing the collection object directly to [`NSData`][NSData] would avoid the unnecessary conversions to and from a [`NSString`][NSString] object. + +### Parsing Interface + +#### JSONDecoder Interface + +The objectWith… methods return immutable collection objects and their respective mutableObjectWith… methods return mutable collection objects. + +**Note:** The bytes contained in a [`NSData`][NSData] object ***MUST*** be `UTF8` encoded. + +**Important:** Methods will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `parseOptionFlags` is not valid. +**Important:** `objectWithUTF8String:` and `mutableObjectWithUTF8String:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `string` is `NULL`. +**Important:** `objectWithData:` and `mutableObjectWithData:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `jsonData` is `NULL`. + +```objective-c ++ (id)decoder; ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags; + +- (void)clearCache; + +- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length; +- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error; +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length; +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error; + +- (id)objectWithData:(NSData *)jsonData; +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error; +- (id)mutableObjectWithData:(NSData *)jsonData; +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error; +``` + +#### NSString Interface + +```objective-c +- (id)objectFromJSONString; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONString; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +``` + +#### NSData Interface + +```objective-c +- (id)objectFromJSONData; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +- (id)mutableObjectFromJSONData; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; +``` + +#### JKParseOptionFlags + + + + + + + + + +
Parsing OptionDescription
JKParseOptionNoneThis is the default if no other other parse option flags are specified, and the option used when a convenience method does not provide an argument for explicitly specifying the parse options to use. Synonymous with JKParseOptionStrict.
JKParseOptionStrictThe JSON will be parsed in strict accordance with the RFC 4627 specification.
JKParseOptionCommentsAllow C style // and /* … */ comments in JSON. This is a fairly common extension to JSON, but JSON that contains C style comments is not strictly conforming JSON.
JKParseOptionUnicodeNewlinesAllow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines in JSON. The JSON specification only allows the newline characters \r and \n, but this option allows JSON that contains the Unicode recommended newline characters to be parsed. JSON that contains these additional newline characters is not strictly conforming JSON.
JKParseOptionLooseUnicodeNormally the decoder will stop with an error at any malformed Unicode. This option allows JSON with malformed Unicode to be parsed without reporting an error. Any malformed Unicode is replaced with \uFFFD, or REPLACEMENT CHARACTER, as specified in The Unicode 6.0 standard, Chapter 3, section 3.9 Unicode Encoding Forms.
JKParseOptionPermitTextAfterValidJSONNormally, non-white-space that follows the JSON is interpreted as a parsing failure. This option allows for any trailing non-white-space to be ignored and not cause a parsing error.
+ +### Serializing Interface + +The serializing interface includes [`NSString`][NSString] convenience methods for those that need to serialize a single [`NSString`][NSString]. For those that need this functionality, the [`NSString`][NSString] additions are much more convenient than having to wrap a single [`NSString`][NSString] in a [`NSArray`][NSArray], which then requires stripping the unneeded `[`…`]` characters from the serialized JSON result. When serializing a single [`NSString`][NSString], you can control whether or not the serialized JSON result is surrounded by quotation marks using the `includeQuotes:` argument: + +Example | Result | Argument +--------------|-------------------|-------------------- +`a "test"...` | `"a \"test\"..."` | `includeQuotes:YES` +`a "test"...` | `a \"test\"...` | `includeQuotes:NO` + +**Note:** The [`NSString`][NSString] methods that do not include a `includeQuotes:` argument behave as if invoked with `includeQuotes:YES`. +**Note:** The bytes contained in the returned [`NSData`][NSData] object are `UTF8` encoded. + +#### NSArray and NSDictionary Interface + +```objective-c +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; +``` + + +#### NSString Interface + +```objective-c +- (NSData *)JSONData; +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +- (NSString *)JSONString; +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; +``` + +#### JKSerializeOptionFlags + + + + + + + +
Serializing OptionDescription
JKSerializeOptionNoneThis is the default if no other other serialize option flags are specified, and the option used when a convenience method does not provide an argument for explicitly specifying the serialize options to use.
JKSerializeOptionPrettyNormally the serialized JSON does not include any unnecessary white-space. While this form is the most compact, the lack of any white-space means that it's something only another JSON parser could love. Enabling this option causes JSONKit to add additional white-space that makes it easier for people to read. Other than the extra white-space, the serialized JSON is identical to the JSON that would have been produced had this option not been enabled.
JKSerializeOptionEscapeUnicodeWhen JSONKit encounters Unicode characters in NSString objects, the default behavior is to encode those Unicode characters as UTF8. This option causes JSONKit to encode those characters as \uXXXX. For example,
["w∈L⟺y(∣y∣≤∣w∣)"]
becomes:
["w\u2208L\u27fa\u2203y(\u2223y\u2223\u2264\u2223w\u2223)"]
JKSerializeOptionEscapeForwardSlashesAccording to the JSON specification, the / (U+002F) character may be backslash escaped (i.e., \/), but it is not required. The default behavior of JSONKit is to not backslash escape the / character. Unfortunately, it was found some real world implementations of the ASP.NET Date Format require the date to be strictly encoded as \/Date(...)\/, and the only way to achieve this is through the use of JKSerializeOptionEscapeForwardSlashes. See github issue #21 for more information.
+ +[JSON]: http://www.json.org/ +[RFC 4627]: http://tools.ietf.org/html/rfc4627 +[RFC 2119]: http://tools.ietf.org/html/rfc2119 +[Single Precision]: http://en.wikipedia.org/wiki/Single_precision_floating-point_format +[Double Precision]: http://en.wikipedia.org/wiki/Double_precision_floating-point_format +[wiki_invariant]: http://en.wikipedia.org/wiki/Invariant_(computer_science) +[ARC]: http://clang.llvm.org/docs/AutomaticReferenceCounting.html +[CFBoolean]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/index.html +[kCFBooleanTrue]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanTrue +[kCFBooleanFalse]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanFalse +[kCFNumberDoubleType]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFNumberDoubleType +[CFNumberGetValue]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/c/func/CFNumberGetValue +[Unicode Standard]: http://www.unicode.org/versions/Unicode6.0.0/ +[Unicode Standard - Conformance]: http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf +[Unicode_equivalence]: http://en.wikipedia.org/wiki/Unicode_equivalence +[UnicodeNewline]: http://en.wikipedia.org/wiki/Newline#Unicode +[Unicode_UTR36]: http://www.unicode.org/reports/tr36/ +[Unicode_UTR36_NonVisualSecurity]: http://www.unicode.org/reports/tr36/#Canonical_Represenation +[Unicode_UTR36_Deleting]: http://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters +[Unicode_Security_FAQ]: http://www.unicode.org/faq/security.html +[NSNull]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/index.html +[NSNumber]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/index.html +[NSNumber_numberWithBool]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/clm/NSNumber/numberWithBool: +[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html +[NSString_initWithBytes]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithBytes:length:encoding: +[NSString_initWithData]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithData:encoding: +[NSString_UTF8String]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/UTF8String +[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html +[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html +[NSError]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/index.html +[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html +[NSMutableData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/index.html +[NSInvalidArgumentException]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException +[CFString]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html +[NSCParameterAssert]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/macro/NSCParameterAssert +[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy +[-isKindOfClass:]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html%23//apple_ref/occ/intfm/NSObject/isKindOfClass: +[-objCType]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNumber/objCType +[strtoll]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoll.3.html +[strtod]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtod.3.html +[strtoull]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoull.3.html +[getrusage]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/getrusage.2.html +[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html +[NSJSONSerialization]: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html diff --git a/PSCollectionViewDemo/PSCollectionViewCell.m b/PSCollectionViewDemo/PSCollectionViewCell.m index 6b7d8c4..b848a70 100644 --- a/PSCollectionViewDemo/PSCollectionViewCell.m +++ b/PSCollectionViewDemo/PSCollectionViewCell.m @@ -42,8 +42,9 @@ - (void)prepareForReuse { - (void)collectionView:(PSCollectionView *)collectionView fillCellWithObject:(id)object atIndex:(NSInteger)index { self.collectionView = collectionView; - self.object = object; + //self.object = object; self.index = index; + self.object = [object objectAtIndex:index]; // 调用接口传递的 object 是数组,但是 waterflowViewCell.m 中 layoutSubviews 中 object 应该是数组中的一个字典 } + (CGFloat)rowHeightForObject:(id)object inColumnWidth:(CGFloat)columnWidth { diff --git a/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.h b/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.h new file mode 100644 index 0000000..fca8df0 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.h @@ -0,0 +1,95 @@ +// +// MKAnnotationView+WebCache.h +// SDWebImage +// +// Created by Olivier Poitrey on 14/03/12. +// Copyright (c) 2012 Dailymotion. All rights reserved. +// + +#import "MapKit/MapKit.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with MKAnnotationView. + */ +@interface MKAnnotationView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Cancel the current download + */ +- (void)cancelCurrentImageLoad; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.m b/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.m new file mode 100644 index 0000000..8f27a17 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/MKAnnotationView+WebCache.m @@ -0,0 +1,78 @@ +// +// MKAnnotationView+WebCache.m +// SDWebImage +// +// Created by Olivier Poitrey on 14/03/12. +// Copyright (c) 2012 Dailymotion. All rights reserved. +// + +#import "MKAnnotationView+WebCache.h" +#import "objc/runtime.h" + +static char operationKey; + +@implementation MKAnnotationView (WebCache) + +- (void)setImageWithURL:(NSURL *)url +{ + [self setImageWithURL:url placeholderImage:nil options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder +{ + [self setImageWithURL:url placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options +{ + [self setImageWithURL:url placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock +{ + [self cancelCurrentImageLoad]; + + self.image = placeholder; + + if (url) + { + __weak MKAnnotationView *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) + { + __strong MKAnnotationView *sself = wself; + if (!sself) return; + if (image) + { + sself.image = image; + } + if (completedBlock && finished) + { + completedBlock(image, error, cacheType); + } + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)cancelCurrentImageLoad +{ + // Cancel in progress downloader from queue + id operation = objc_getAssociatedObject(self, &operationKey); + if (operation) + { + [operation cancel]; + objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDImageCache.h b/PSCollectionViewDemo/SDWebImage/SDImageCache.h new file mode 100644 index 0000000..22ff04d --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDImageCache.h @@ -0,0 +1,144 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +enum SDImageCacheType +{ + /** + * The image wasn't available the SDWebImage caches, but was downloaded from the web. + */ + SDImageCacheTypeNone = 0, + /** + * The image was obtained from the disk cache. + */ + SDImageCacheTypeDisk, + /** + * The image was obtained from the memory cache. + */ + SDImageCacheTypeMemory +}; +typedef enum SDImageCacheType SDImageCacheType; + +/** + * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed + * asynchronous so it doesn’t add unnecessary latency to the UI. + */ +@interface SDImageCache : NSObject + +/** + * The maximum length of time to keep an image in the cache, in seconds + */ +@property (assign, nonatomic) NSInteger maxCacheAge; + +/** + * Returns global shared cache instance + * + * @return SDImageCache global instance + */ ++ (SDImageCache *)sharedImageCache; + +/** + * Init a new cache store with a specific namespace + * + * @param ns The namespace to use for this cache store + */ +- (id)initWithNamespace:(NSString *)ns; + +/** + * Store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Store an image into memory and optionally disk cache at the given key. + * + * @param image The image to store + * @param data The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES + */ +- (void)storeImage:(UIImage *)image imageData:(NSData *)data forKey:(NSString *)key toDisk:(BOOL)toDisk; + +/** + * Query the disk cache asynchronously. + * + * @param key The unique key used to store the wanted image + */ +- (void)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock; + +/** + * Query the memory cache synchronously. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; + +/** + * Query the disk cache synchronously after checking the memory cache. + * + * @param key The unique key used to store the wanted image + */ +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key; + +/** + * Remove the image from memory and disk cache synchronously + * + * @param key The unique image cache key + */ +- (void)removeImageForKey:(NSString *)key; + +/** + * Remove the image from memory and optionaly disk cache synchronously + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES + */ +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; + +/** + * Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Clear all disk cached images + */ +- (void)clearDisk; + +/** + * Remove all expired cached image from disk + */ +- (void)cleanDisk; + +/** + * Get the size used by the disk cache + */ +- (unsigned long long)getSize; + +/** + * Get the number of images in the disk cache + */ +- (int)getDiskCount; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDImageCache.m b/PSCollectionViewDemo/SDWebImage/SDImageCache.m new file mode 100644 index 0000000..dbb0bf5 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDImageCache.m @@ -0,0 +1,314 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCache.h" +#import "SDWebImageDecoder.h" +#import +#import +#import + +static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week + +@interface SDImageCache () + +@property (strong, nonatomic) NSCache *memCache; +@property (strong, nonatomic) NSString *diskCachePath; +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; + +@end + + +@implementation SDImageCache + ++ (SDImageCache *)sharedImageCache +{ + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{instance = self.new;}); + return instance; +} + +- (id)init +{ + return [self initWithNamespace:@"default"]; +} + +- (id)initWithNamespace:(NSString *)ns +{ + if ((self = [super init])) + { + NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; + + // Create IO serial queue + _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); + + // Init default values + _maxCacheAge = kDefaultCacheMaxCacheAge; + + // Init the memory cache + _memCache = [[NSCache alloc] init]; + _memCache.name = fullNamespace; + + // Init the disk cache + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace]; + +#if TARGET_OS_IPHONE + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(clearMemory) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(cleanDisk) + name:UIApplicationWillTerminateNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; + SDDispatchQueueRelease(_ioQueue); +} + +#pragma mark SDImageCache (private) + +- (NSString *)cachePathForKey:(NSString *)key +{ + const char *str = [key UTF8String]; + unsigned char r[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), r); + NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; + + return [self.diskCachePath stringByAppendingPathComponent:filename]; +} + +#pragma mark ImageCache + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk +{ + if (!image || !key) + { + return; + } + + [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale]; + + if (toDisk) + { + dispatch_async(self.ioQueue, ^ + { + NSData *data = imageData; + + if (!data) + { + if (image) + { +#if TARGET_OS_IPHONE + data = UIImageJPEGRepresentation(image, (CGFloat)1.0); +#else + data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; +#endif + } + } + + if (data) + { + // Can't use defaultManager another thread + NSFileManager *fileManager = NSFileManager.new; + + if (![fileManager fileExistsAtPath:_diskCachePath]) + { + [fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + + [fileManager createFileAtPath:[self cachePathForKey:key] contents:data attributes:nil]; + } + }); + } +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key +{ + [self storeImage:image imageData:nil forKey:key toDisk:YES]; +} + +- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk +{ + [self storeImage:image imageData:nil forKey:key toDisk:toDisk]; +} + +- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key +{ + return [self.memCache objectForKey:key]; +} + +- (UIImage *)imageFromDiskCacheForKey:(NSString *)key +{ + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) + { + return image; + } + + // Second check the disk cache... + UIImage *diskImage = [UIImage decodedImageWithImage:SDScaledImageForPath(key, [NSData dataWithContentsOfFile:[self cachePathForKey:key]])]; + + if (diskImage) + { + CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + return diskImage; +} + +- (void)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock +{ + if (!doneBlock) return; + + if (!key) + { + doneBlock(nil, SDImageCacheTypeNone); + return; + } + + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) + { + doneBlock(image, SDImageCacheTypeMemory); + return; + } + + dispatch_async(self.ioQueue, ^ + { + @autoreleasepool + { + UIImage *diskImage = [UIImage decodedImageWithImage:SDScaledImageForPath(key, [NSData dataWithContentsOfFile:[self cachePathForKey:key]])]; + + if (diskImage) + { + CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + + dispatch_async(dispatch_get_main_queue(), ^ + { + doneBlock(diskImage, SDImageCacheTypeDisk); + }); + } + }); +} + +- (void)removeImageForKey:(NSString *)key +{ + [self removeImageForKey:key fromDisk:YES]; +} + +- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk +{ + if (key == nil) + { + return; + } + + [self.memCache removeObjectForKey:key]; + + if (fromDisk) + { + dispatch_async(self.ioQueue, ^ + { + [[NSFileManager defaultManager] removeItemAtPath:[self cachePathForKey:key] error:nil]; + }); + } +} + +- (void)clearMemory +{ + [self.memCache removeAllObjects]; +} + +- (void)clearDisk +{ + dispatch_async(self.ioQueue, ^ + { + [[NSFileManager defaultManager] removeItemAtPath:self.diskCachePath error:nil]; + [[NSFileManager defaultManager] createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + }); +} + +- (void)cleanDisk +{ + dispatch_async(self.ioQueue, ^ + { + NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; + // convert NSString path to NSURL path + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + // build an enumerator by also prefetching file properties we want to read + NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:@[ NSURLIsDirectoryKey, NSURLContentModificationDateKey ] + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + for (NSURL *fileURL in fileEnumerator) + { + // skip folder + NSNumber *isDirectory; + [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; + if ([isDirectory boolValue]) + { + continue; + } + + // compare file date with the max age + NSDate *fileModificationDate; + [fileURL getResourceValue:&fileModificationDate forKey:NSURLContentModificationDateKey error:NULL]; + if ([[fileModificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) + { + [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; + } + } + }); +} + +-(unsigned long long)getSize +{ + unsigned long long size = 0; + NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:self.diskCachePath]; + for (NSString *fileName in fileEnumerator) + { + NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; + NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; + size += [attrs fileSize]; + } + return size; +} + +- (int)getDiskCount +{ + int count = 0; + NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:self.diskCachePath]; + for (NSString *fileName in fileEnumerator) + { + count += 1; + } + + return count; +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.h b/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.h new file mode 100644 index 0000000..a075045 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.h @@ -0,0 +1,40 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#ifdef __OBJC_GC__ +#error SDWebImage does not support Objective-C Garbage Collection +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 +#error SDWebImage doesn't support Deployement Target version < 5.0 +#endif + +#if !TARGET_OS_IPHONE +#import +#ifndef UIImage +#define UIImage NSImage +#endif +#ifndef UIImageView +#define UIImageView NSImageView +#endif +#else +#import +#endif + +#if OS_OBJECT_USE_OBJC + #define SDDispatchQueueRelease(q) + #define SDDispatchQueueSetterSementics strong +#else + #define SDDispatchQueueRelease(q) (dispatch_release(q)) + #define SDDispatchQueueSetterSementics assign +#endif + +extern inline UIImage *SDScaledImageForPath(NSString *path, NSObject *imageOrData); diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.m b/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.m new file mode 100644 index 0000000..1ff3afb --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageCompat.m @@ -0,0 +1,54 @@ +// +// SDWebImageCompat.m +// SDWebImage +// +// Created by Olivier Poitrey on 11/12/12. +// Copyright (c) 2012 Dailymotion. All rights reserved. +// + +#import "SDWebImageCompat.h" + +#if !__has_feature(objc_arc) +#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +inline UIImage *SDScaledImageForPath(NSString *path, NSObject *imageOrData) +{ + if (!imageOrData) + { + return nil; + } + + UIImage *image = nil; + if ([imageOrData isKindOfClass:[NSData class]]) + { + image = [[UIImage alloc] initWithData:(NSData *)imageOrData]; + } + else if ([imageOrData isKindOfClass:[UIImage class]]) + { + image = (UIImage *)imageOrData; + } + else + { + return nil; + } + + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) + { + CGFloat scale = 1.0; + if (path.length >= 8) + { + // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) + NSRange range = [path rangeOfString:@"@2x." options:0 range:NSMakeRange(path.length - 8, 5)]; + if (range.location != NSNotFound) + { + scale = 2.0; + } + } + + UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; + image = scaledImage; + } + + return image; +} diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.h b/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.h new file mode 100644 index 0000000..0176a7b --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.h @@ -0,0 +1,18 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +@interface UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.m b/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.m new file mode 100644 index 0000000..fe70fd9 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDecoder.m @@ -0,0 +1,70 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * Created by james on 9/28/11. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDecoder.h" + +@implementation UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image +{ + CGImageRef imageRef = image.CGImage; + CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); + CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; + + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); + BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || + infoMask == kCGImageAlphaNoneSkipFirst || + infoMask == kCGImageAlphaNoneSkipLast); + + // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. + // https://developer.apple.com/library/mac/#qa/qa1037/_index.html + if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) + { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + + // Set noneSkipFirst. + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } + // Some PNGs tell us they have alpha but only 3 components. Odd. + else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) + { + // Unset the old alpha info. + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } + + // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. + CGContextRef context = CGBitmapContextCreate(NULL, + imageSize.width, + imageSize.height, + CGImageGetBitsPerComponent(imageRef), + 0, + colorSpace, + bitmapInfo); + CGColorSpaceRelease(colorSpace); + + // If failed, return undecompressed image + if (!context) return image; + + CGContextDrawImage(context, imageRect, imageRef); + CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; + CGImageRelease(decompressedImageRef); + return decompressedImage; +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.h b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.h new file mode 100644 index 0000000..7f5ff0c --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.h @@ -0,0 +1,102 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +typedef enum +{ + SDWebImageDownloaderLowPriority = 1 << 0, + SDWebImageDownloaderProgressiveDownload = 1 << 1, + /** + * By default, request prevent the of NSURLCache. With this flag, NSURLCache + * is used with default policies. + */ + SDWebImageDownloaderUseNSURLCache = 1 << 2, + /** + * Call completion block with nil image/imageData if the image was read from NSURLCache + * (to be combined with `SDWebImageDownloaderUseNSURLCache`). + */ + SDWebImageDownloaderIgnoreCachedResponse = 1 << 3 +} SDWebImageDownloaderOptions; + +typedef enum +{ + SDWebImageDownloaderFIFOExecutionOrder, + /** + * Default value. All download operations will execute in queue style (first-in-first-out). + */ + SDWebImageDownloaderLIFOExecutionOrder + /** + * All download operations will execute in stack style (last-in-first-out). + */ +} SDWebImageDownloaderExecutionOrder; + +extern NSString *const SDWebImageDownloadStartNotification; +extern NSString *const SDWebImageDownloadStopNotification; + +typedef void(^SDWebImageDownloaderProgressBlock)(NSUInteger receivedSize, long long expectedSize); +typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +@property (assign, nonatomic) NSInteger maxConcurrentDownloads; + +/** + * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; + ++ (SDWebImageDownloader *)sharedDownloader; + +/** + * Set a value for a HTTP header to be appended to each download HTTP request. + * + * @param value The value for the header field. Use `nil` value to remove the header. + * @param field The name of the header field to set. + */ +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; + +/** + * Returns the value of the specified HTTP header field. + * + * @return The value associated with the header field field, or `nil` if there is no corresponding header field. + */ +- (NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param progress A block called repeatedly while the image is downloading + * @param completed A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveDownload isn't use. With the + * SDWebImageDownloaderProgressiveDownload option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A cancellable SDWebImageOperation + */ +- (id)downloadImageWithURL:(NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.m b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.m new file mode 100644 index 0000000..af17cd2 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloader.m @@ -0,0 +1,226 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderOperation.h" +#import + +NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; + +static NSString *const kProgressCallbackKey = @"progress"; +static NSString *const kCompletedCallbackKey = @"completed"; + +@interface SDWebImageDownloader () + +@property (strong, nonatomic) NSOperationQueue *downloadQueue; +@property (weak, nonatomic) NSOperation *lastAddedOperation; +@property (strong, nonatomic) NSMutableDictionary *URLCallbacks; +@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; +// This queue is used to serialize the handling of the network responses of all the download operation in a single queue +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t workingQueue; +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; + +@end + +@implementation SDWebImageDownloader + ++ (void)initialize +{ + // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) + // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import + if (NSClassFromString(@"SDNetworkActivityIndicator")) + { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; +#pragma clang diagnostic pop + + // Remove observer in case it was previously added. + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"startActivity") + name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"stopActivity") + name:SDWebImageDownloadStopNotification object:nil]; + } +} + ++ (SDWebImageDownloader *)sharedDownloader +{ + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{instance = self.new;}); + return instance; +} + +- (id)init +{ + if ((self = [super init])) + { + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + _downloadQueue = NSOperationQueue.new; + _downloadQueue.maxConcurrentOperationCount = 2; + _URLCallbacks = NSMutableDictionary.new; + _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/*" forKey:@"Accept"]; + _workingQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloader", DISPATCH_QUEUE_SERIAL); + _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); + } + return self; +} + +- (void)dealloc +{ + [self.downloadQueue cancelAllOperations]; + SDDispatchQueueRelease(_workingQueue); + SDDispatchQueueRelease(_barrierQueue); +} + +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field +{ + if (value) + { + self.HTTPHeaders[field] = value; + } + else + { + [self.HTTPHeaders removeObjectForKey:field]; + } +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field +{ + return self.HTTPHeaders[field]; +} + +- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads +{ + _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; +} + +- (NSInteger)maxConcurrentDownloads +{ + return _downloadQueue.maxConcurrentOperationCount; +} + +- (id)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSUInteger, long long))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock +{ + __block SDWebImageDownloaderOperation *operation; + __weak SDWebImageDownloader *wself = self; + + [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^ + { + // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise + NSMutableURLRequest *request = [NSMutableURLRequest.alloc initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:15]; + request.HTTPShouldHandleCookies = NO; + request.HTTPShouldUsePipelining = YES; + request.allHTTPHeaderFields = wself.HTTPHeaders; + operation = [SDWebImageDownloaderOperation.alloc initWithRequest:request queue:wself.workingQueue options:options progress:^(NSUInteger receivedSize, long long expectedSize) + { + if (!wself) return; + SDWebImageDownloader *sself = wself; + NSArray *callbacksForURL = [sself callbacksForURL:url]; + for (NSDictionary *callbacks in callbacksForURL) + { + SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; + if (callback) callback(receivedSize, expectedSize); + } + } + completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) + { + if (!wself) return; + SDWebImageDownloader *sself = wself; + NSArray *callbacksForURL = [sself callbacksForURL:url]; + if (finished) + { + [sself removeCallbacksForURL:url]; + } + for (NSDictionary *callbacks in callbacksForURL) + { + SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; + if (callback) callback(image, data, error, finished); + } + } + cancelled:^ + { + if (!wself) return; + SDWebImageDownloader *sself = wself; + [sself callbacksForURL:url]; + [sself removeCallbacksForURL:url]; + }]; + [wself.downloadQueue addOperation:operation]; + if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) + { + // Emulate LIFO execution order by systematically adding new operations as last operation's dependency + [wself.lastAddedOperation addDependency:operation]; + wself.lastAddedOperation = operation; + } + }]; + + return operation; +} + +- (void)addProgressCallback:(void (^)(NSUInteger, long long))progressBlock andCompletedBlock:(void (^)(UIImage *, NSData *data, NSError *, BOOL))completedBlock forURL:(NSURL *)url createCallback:(void (^)())createCallback +{ + // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. + if(url == nil) + { + if (completedBlock != nil) + { + completedBlock(nil, nil, nil, NO); + } + return; + } + + dispatch_barrier_sync(self.barrierQueue, ^ + { + BOOL first = NO; + if (!self.URLCallbacks[url]) + { + self.URLCallbacks[url] = NSMutableArray.new; + first = YES; + } + + // Handle single download of simultaneous download request for the same URL + NSMutableArray *callbacksForURL = self.URLCallbacks[url]; + NSMutableDictionary *callbacks = NSMutableDictionary.new; + if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; + if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; + [callbacksForURL addObject:callbacks]; + self.URLCallbacks[url] = callbacksForURL; + + if (first) + { + createCallback(); + } + }); +} + +- (NSArray *)callbacksForURL:(NSURL *)url +{ + __block NSArray *callbacksForURL; + dispatch_sync(self.barrierQueue, ^ + { + callbacksForURL = self.URLCallbacks[url]; + }); + return callbacksForURL; +} + +- (void)removeCallbacksForURL:(NSURL *)url +{ + dispatch_barrier_async(self.barrierQueue, ^ + { + [self.URLCallbacks removeObjectForKey:url]; + }); +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.h b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..b7afd7f --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.h @@ -0,0 +1,25 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +@interface SDWebImageDownloaderOperation : NSOperation + +@property (strong, nonatomic, readonly) NSURLRequest *request; +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +- (id)initWithRequest:(NSURLRequest *)request + queue:(dispatch_queue_t)queue + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock + cancelled:(void (^)())cancelBlock; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.m b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..07b3ad5 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageDownloaderOperation.m @@ -0,0 +1,339 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageDecoder.h" +#import + +@interface SDWebImageDownloaderOperation () + +@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; +@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; +@property (copy, nonatomic) void (^cancelBlock)(); + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (assign, nonatomic) long long expectedSize; +@property (strong, nonatomic) NSMutableData *imageData; +@property (strong, nonatomic) NSURLConnection *connection; +@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t queue; + +@end + +@implementation SDWebImageDownloaderOperation +{ + size_t width, height; + BOOL responseFromCached; +} + +- (id)initWithRequest:(NSURLRequest *)request queue:(dispatch_queue_t)queue options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSUInteger, long long))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock cancelled:(void (^)())cancelBlock +{ + if ((self = [super init])) + { + _queue = queue; + _request = request; + _options = options; + _progressBlock = [progressBlock copy]; + _completedBlock = [completedBlock copy]; + _cancelBlock = [cancelBlock copy]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called + } + return self; +} + +- (void)start +{ + dispatch_async(dispatch_get_main_queue(), ^ + { + if (self.isCancelled) + { + self.finished = YES; + [self reset]; + return; + } + + self.executing = YES; + self.connection = [NSURLConnection.alloc initWithRequest:self.request delegate:self startImmediately:NO]; + + // If not in low priority mode, ensure we aren't blocked by UI manipulations (default runloop mode for NSURLConnection is NSEventTrackingRunLoopMode) + if (!(self.options & SDWebImageDownloaderLowPriority)) + { + [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + } + + [self.connection start]; + + if (self.connection) + { + if (self.progressBlock) + { + self.progressBlock(0, -1); + } + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; + } + else + { + if (self.completedBlock) + { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: @"Connection can't be initialized"}], YES); + } + } + }); +} + +- (void)cancel +{ + if (self.isFinished) return; + [super cancel]; + if (self.cancelBlock) self.cancelBlock(); + + if (self.connection) + { + [self.connection cancel]; + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; + + // As we cancelled the connection, its callback won't be called and thus won't + // maintain the isFinished and isExecuting flags. + if (self.isExecuting) self.executing = NO; + if (!self.isFinished) self.finished = YES; + } + + [self reset]; +} + +- (void)done +{ + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset +{ + dispatch_async(dispatch_get_main_queue(), ^ + { + self.cancelBlock = nil; + self.completedBlock = nil; + self.progressBlock = nil; + self.connection = nil; + self.imageData = nil; + }); +} + +- (void)setFinished:(BOOL)finished +{ + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing +{ + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isConcurrent +{ + return YES; +} + +#pragma mark NSURLConnection (delegate) + +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response +{ + if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) + { + NSUInteger expected = response.expectedContentLength > 0 ? (NSUInteger)response.expectedContentLength : 0; + self.expectedSize = expected; + if (self.progressBlock) + { + self.progressBlock(0, expected); + } + + dispatch_async(self.queue, ^ + { + self.imageData = [NSMutableData.alloc initWithCapacity:expected]; + }); + } + else + { + [self.connection cancel]; + + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + if (self.completedBlock) + { + self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); + } + + [self done]; + } +} + +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data +{ + dispatch_async(self.queue, ^ + { + [self.imageData appendData:data]; + + if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) + { + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Get the total bytes downloaded + const NSUInteger totalSize = self.imageData.length; + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL); + CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize); + + if (width + height == 0) + { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); + if (properties) + { + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &width); + CFRelease(properties); + } + } + + if (width + height > 0 && totalSize < self.expectedSize) + { + // Create the image + CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); + +#ifdef TARGET_OS_IPHONE + // Workaround for iOS anamorphic image + if (partialImageRef) + { + const size_t partialHeight = CGImageGetHeight(partialImageRef); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); + CGColorSpaceRelease(colorSpace); + if (bmContext) + { + CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); + CGImageRelease(partialImageRef); + partialImageRef = CGBitmapContextCreateImage(bmContext); + CGContextRelease(bmContext); + } + else + { + CGImageRelease(partialImageRef); + partialImageRef = nil; + } + } +#endif + + if (partialImageRef) + { + UIImage *image = [UIImage decodedImageWithImage:SDScaledImageForPath(self.request.URL.absoluteString, [UIImage imageWithCGImage:partialImageRef])]; + CGImageRelease(partialImageRef); + dispatch_async(dispatch_get_main_queue(), ^ + { + if (self.completedBlock) + { + self.completedBlock(image, nil, nil, NO); + } + }); + } + } + + CFRelease(imageSource); + } + NSUInteger received = self.imageData.length; + dispatch_async(dispatch_get_main_queue(), ^ + { + if (self.progressBlock) + { + self.progressBlock(received, self.expectedSize); + } + }); + }); +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection +{ + self.connection = nil; + + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; + + if (completionBlock) + { + if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) + { + completionBlock(nil, nil, nil, YES); + self.completionBlock = nil; + [self done]; + } + else + { + dispatch_async(self.queue, ^ + { + UIImage *image = [UIImage decodedImageWithImage:SDScaledImageForPath(self.request.URL.absoluteString, self.imageData)]; + dispatch_async(dispatch_get_main_queue(), ^ + { + if (CGSizeEqualToSize(image.size, CGSizeZero)) + { + completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey: @"Downloaded image has 0 pixels"}], YES); + } + else + { + completionBlock(image, self.imageData, nil, YES); + } + self.completionBlock = nil; + [self done]; + }); + }); + } + } + else + { + [self done]; + } +} + +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error +{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; + + if (self.completedBlock) + { + self.completedBlock(nil, nil, error, YES); + } + + [self done]; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse +{ + responseFromCached = NO; // If this method is called, it means the response wasn't read from cache + if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) + { + // Prevents caching of responses + return nil; + } + else + { + return cachedResponse; + } +} + + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageManager.h b/PSCollectionViewDemo/SDWebImage/SDWebImageManager.h new file mode 100644 index 0000000..a6e39ac --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageManager.h @@ -0,0 +1,167 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDownloader.h" +#import "SDImageCache.h" + +typedef enum +{ + /** + * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. + * This flag disable this blacklisting. + */ + SDWebImageRetryFailed = 1 << 0, + /** + * By default, image downloads are started during UI interactions, this flags disable this feature, + * leading to delayed download on UIScrollView deceleration for instance. + */ + SDWebImageLowPriority = 1 << 1, + /** + * This flag disables on-disk caching + */ + SDWebImageCacheMemoryOnly = 1 << 2, + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + * By default, the image is only displayed once completely downloaded. + */ + SDWebImageProgressiveDownload = 1 << 3, + /** + * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. + * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. + * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. + * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. + * + * Use this flag only if you can't make your URLs static with embeded cache busting parameter. + */ + SDWebImageRefreshCached = 1 << 4 +} SDWebImageOptions; + +typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType); +typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished); + + +@class SDWebImageManager; + +@protocol SDWebImageManagerDelegate + +@optional + +/** + * Controls which image should be downloaded when the image is not found in the cache. + * + * @param imageManager The current `SDWebImageManager` + * @param imageURL The url of the image to be downloaded + * + * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. + */ +- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; + +/** + * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. + * NOTE: This method is called from a global queue in order to not to block the main thread. + * + * @param imageManager The current `SDWebImageManager` + * @param image The image to transform + * @param imageURL The url of the image to transform + * + * @return The transformed image object. + */ +- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; + +@end + +/** + * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. + * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). + * You can use this class directly to benefit from web image downloading with caching in another context than + * a UIView. + * + * Here is a simple example of how to use SDWebImageManager: + * + * SDWebImageManager *manager = [SDWebImageManager sharedManager]; + * [manager downloadWithURL:imageURL + * delegate:self + * options:0 + * progress:nil + * completed:^(UIImage *image, NSError *error, BOOL fromCache) + * { + * if (image) + * { + * // do something with image + * } + * }]; + */ +@interface SDWebImageManager : NSObject + +@property (weak, nonatomic) id delegate; + +@property (strong, nonatomic, readonly) SDImageCache *imageCache; +@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; + +/** + * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can + * be used to remove dynamic part of an image URL. + * + * The following example sets a filter in the application delegate that will remove any query-string from the + * URL before to use it as a cache key: + * + * [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) + * { + * url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + * return [url absoluteString]; + * }]; + */ +@property (strong) NSString *(^cacheKeyFilter)(NSURL *url); + +/** + * Returns global SDWebImageManager instance. + * + * @return SDWebImageManager shared instance + */ ++ (SDWebImageManager *)sharedManager; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param delegate The delegate object used to send result back + * @param options A mask to specify options to use for this request + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. + * + * This block as no return value and takes the requested UIImage as first parameter. + * In case of error the image parameter is nil and the second parameter may contain an NSError. + * + * The third parameter is a Boolean indicating if the image was retrived from the local cache + * of from the network. + * + * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and + * the image is downloading. This block is thus called repetidly with a partial image. When + * image is fully downloaded, the block is called a last time with the full image and the last + * parameter set to YES. + * + * @return Returns a cancellable NSOperation + */ +- (id)downloadWithURL:(NSURL *)url + options:(SDWebImageOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; + +/** + * Cancel all current opreations + */ +- (void)cancelAll; + +/** + * Check one or more operations running + */ +- (BOOL)isRunning; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageManager.m b/PSCollectionViewDemo/SDWebImage/SDWebImageManager.m new file mode 100644 index 0000000..c7fee6a --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageManager.m @@ -0,0 +1,244 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageManager.h" +#import + +@interface SDWebImageCombinedOperation : NSObject + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (copy, nonatomic) void (^cancelBlock)(); + +@end + +@interface SDWebImageManager () + +@property (strong, nonatomic, readwrite) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; +@property (strong, nonatomic) NSMutableArray *failedURLs; +@property (strong, nonatomic) NSMutableArray *runningOperations; + +@end + +@implementation SDWebImageManager + ++ (id)sharedManager +{ + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{instance = self.new;}); + return instance; +} + +- (id)init +{ + if ((self = [super init])) + { + _imageCache = [SDImageCache sharedImageCache]; + _imageDownloader = SDWebImageDownloader.new; + _failedURLs = NSMutableArray.new; + _runningOperations = NSMutableArray.new; + } + return self; +} + + +- (NSString *)cacheKeyForURL:(NSURL *)url +{ + if (self.cacheKeyFilter) + { + return self.cacheKeyFilter(url); + } + else + { + return [url absoluteString]; + } +} + +- (id)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock +{ + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + if ([url isKindOfClass:NSString.class]) + { + url = [NSURL URLWithString:(NSString *)url]; + } + + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) + { + url = nil; + } + + __block SDWebImageCombinedOperation *operation = SDWebImageCombinedOperation.new; + __weak SDWebImageCombinedOperation *weakOperation = operation; + + if (!url || !completedBlock || (!(options & SDWebImageRetryFailed) && [self.failedURLs containsObject:url])) + { + if (completedBlock) completedBlock(nil, nil, SDImageCacheTypeNone, NO); + return operation; + } + + @synchronized(self.runningOperations) + { + [self.runningOperations addObject:operation]; + } + NSString *key = [self cacheKeyForURL:url]; + + [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) + { + if (operation.isCancelled) return; + + if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) + { + if (image && options & SDWebImageRefreshCached) + { + // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image + // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. + completedBlock(image, nil, cacheType, YES); + } + + // download if no image or requested to refresh anyway, and download allowed by delegate + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; + if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; + if (image && options & SDWebImageRefreshCached) + { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + __block id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) + { + if (weakOperation.cancelled) + { + completedBlock(nil, nil, SDImageCacheTypeNone, finished); + } + else if (error) + { + completedBlock(nil, error, SDImageCacheTypeNone, finished); + + if (error.code != NSURLErrorNotConnectedToInternet) + { + @synchronized(self.failedURLs) + { + [self.failedURLs addObject:url]; + } + } + } + else + { + BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); + + if (options & SDWebImageRefreshCached && image && !downloadedImage) + { + // Image refresh hit the NSURLCache cache, do not call the completion block + } + else if (downloadedImage && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) + { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ + { + UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; + + dispatch_async(dispatch_get_main_queue(), ^ + { + completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished); + }); + + if (transformedImage && finished) + { + [self.imageCache storeImage:transformedImage imageData:nil forKey:key toDisk:cacheOnDisk]; + } + }); + } + else + { + completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished); + + if (downloadedImage && finished) + { + [self.imageCache storeImage:downloadedImage imageData:data forKey:key toDisk:cacheOnDisk]; + } + } + } + + if (finished) + { + @synchronized(self.runningOperations) + { + [self.runningOperations removeObject:operation]; + } + } + }]; + operation.cancelBlock = ^{[subOperation cancel];}; + } + else if (image) + { + completedBlock(image, nil, cacheType, YES); + @synchronized(self.runningOperations) + { + [self.runningOperations removeObject:operation]; + } + } + else + { + // Image not in cache and download disallowed by delegate + completedBlock(nil, nil, SDImageCacheTypeNone, YES); + @synchronized(self.runningOperations) + { + [self.runningOperations removeObject:operation]; + } + } + }]; + + return operation; +} + +- (void)cancelAll +{ + @synchronized(self.runningOperations) + { + [self.runningOperations makeObjectsPerformSelector:@selector(cancel)]; + [self.runningOperations removeAllObjects]; + } +} + +- (BOOL)isRunning +{ + return self.runningOperations.count > 0; +} + +@end + +@implementation SDWebImageCombinedOperation + +- (void)setCancelBlock:(void (^)())cancelBlock +{ + if (self.isCancelled) + { + if (cancelBlock) cancelBlock(); + } + else + { + _cancelBlock = [cancelBlock copy]; + } +} + +- (void)cancel +{ + self.cancelled = YES; + if (self.cancelBlock) + { + self.cancelBlock(); + self.cancelBlock = nil; + } +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImageOperation.h b/PSCollectionViewDemo/SDWebImage/SDWebImageOperation.h new file mode 100644 index 0000000..71094ee --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImageOperation.h @@ -0,0 +1,15 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +@protocol SDWebImageOperation + +- (void)cancel; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.h b/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.h new file mode 100644 index 0000000..7695f57 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1,58 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +/** + * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. + */ +@interface SDWebImagePrefetcher : NSObject + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentDownloads; + +/** + * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. + */ +@property (nonatomic, assign) SDWebImageOptions options; + + +/** + * Return the global image prefetcher instance. + */ ++ (SDWebImagePrefetcher *)sharedImagePrefetcher; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + */ +- (void)prefetchURLs:(NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list + * + * @param urls list of URLs to prefetch + * @param completionBlock block to be called when prefetching is completed + */ +- (void)prefetchURLs:(NSArray *)urls completed:(void (^)(NSUInteger finishedCount, NSUInteger skippedCount))completionBlock; + +/** + * Remove and cancel queued list + */ +- (void)cancelPrefetching; + + +@end diff --git a/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.m b/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.m new file mode 100644 index 0000000..c029e8d --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/SDWebImagePrefetcher.m @@ -0,0 +1,127 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImagePrefetcher.h" +#import "SDWebImageManager.h" + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic) SDWebImageManager *manager; +@property (strong, nonatomic) NSArray *prefetchURLs; +@property (assign, nonatomic) NSUInteger requestedCount; +@property (assign, nonatomic) NSUInteger skippedCount; +@property (assign, nonatomic) NSUInteger finishedCount; +@property (assign, nonatomic) NSTimeInterval startedTime; +@property (copy, nonatomic) void (^completionBlock)(NSUInteger, NSUInteger); + +@end + +@implementation SDWebImagePrefetcher + ++ (SDWebImagePrefetcher *)sharedImagePrefetcher +{ + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{instance = self.new;}); + return instance; +} + +- (id)init +{ + if ((self = [super init])) + { + _manager = SDWebImageManager.new; + _options = SDWebImageLowPriority; + self.maxConcurrentDownloads = 3; + } + return self; +} + +- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads +{ + self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; +} + +- (NSUInteger)maxConcurrentDownloads +{ + return self.manager.imageDownloader.maxConcurrentDownloads; +} + +- (void)startPrefetchingAtIndex:(NSUInteger)index +{ + if (index >= self.prefetchURLs.count) return; + self.requestedCount++; + [self.manager downloadWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) + { + if (!finished) return; + self.finishedCount++; + + if (image) + { + NSLog(@"Prefetched %d out of %d", self.finishedCount, self.prefetchURLs.count); + } + else + { + NSLog(@"Prefetched %d out of %d (Failed)", self.finishedCount, [self.prefetchURLs count]); + + // Add last failed + self.skippedCount++; + } + + if (self.prefetchURLs.count > self.requestedCount) + { + [self startPrefetchingAtIndex:self.requestedCount]; + } + else if (self.finishedCount == self.requestedCount) + { + [self reportStatus]; + if (self.completionBlock) + { + self.completionBlock(self.finishedCount, self.skippedCount); + self.completionBlock = nil; + } + } + }]; +} + +- (void)reportStatus +{ + NSUInteger total = [self.prefetchURLs count]; + NSLog(@"Finished prefetching (%d successful, %d skipped, timeElasped %.2f)", total - self.skippedCount, self.skippedCount, CFAbsoluteTimeGetCurrent() - self.startedTime); +} + +- (void)prefetchURLs:(NSArray *)urls +{ + [self prefetchURLs:urls completed:nil]; +} + +- (void)prefetchURLs:(NSArray *)urls completed:(void (^)(NSUInteger, NSUInteger))completionBlock +{ + [self cancelPrefetching]; // Prevent duplicate prefetch request + self.startedTime = CFAbsoluteTimeGetCurrent(); + self.prefetchURLs = urls; + self.completionBlock = completionBlock; + + // Starts prefetching from the very first image on the list with the max allowed concurrency + NSUInteger listCount = self.prefetchURLs.count; + for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) + { + [self startPrefetchingAtIndex:i]; + } +} + +- (void)cancelPrefetching +{ + self.prefetchURLs = nil; + self.skippedCount = 0; + self.requestedCount = 0; + self.finishedCount = 0; + [self.manager cancelAll]; +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.h b/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.h new file mode 100644 index 0000000..2b3348e --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.h @@ -0,0 +1,173 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. + */ +@interface UIButton (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; + +/** + * Set the backgroundImageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the backgroundImageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param success A block to be executed when the image request succeed This block has no return value and takes the retrieved image as argument. + * @param failure A block object to be executed when the image request failed. This block has no return value and takes the error object describing the network or parsing error that occurred (may be nil). + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param success A block to be executed when the image request succeed This block has no return value and takes the retrieved image as argument. + * @param failure A block object to be executed when the image request failed. This block has no return value and takes the error object describing the network or parsing error that occurred (may be nil). + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the backgroundImageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param success A block to be executed when the image request succeed This block has no return value and takes the retrieved image as argument. + * @param failure A block object to be executed when the image request failed. This block has no return value and takes the error object describing the network or parsing error that occurred (may be nil). + */ +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Cancel the current download + */ +- (void)cancelCurrentImageLoad; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.m b/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.m new file mode 100644 index 0000000..53c99a5 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/UIButton+WebCache.m @@ -0,0 +1,129 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIButton+WebCache.h" +#import "objc/runtime.h" + +static char operationKey; + +@implementation UIButton (WebCache) + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state +{ + [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder +{ + [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options +{ + [self setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock +{ + [self cancelCurrentImageLoad]; + + [self setImage:placeholder forState:state]; + + if (url) + { + __weak UIButton *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) + { + __strong UIButton *sself = wself; + if (!sself) return; + if (image) + { + [sself setImage:image forState:state]; + } + if (completedBlock && finished) + { + completedBlock(image, error, cacheType); + } + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state +{ + [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder +{ + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options +{ + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock +{ + [self cancelCurrentImageLoad]; + + [self setBackgroundImage:placeholder forState:state]; + + if (url) + { + __weak UIButton *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) + { + __strong UIButton *sself = wself; + if (!sself) return; + if (image) + { + [sself setBackgroundImage:image forState:state]; + } + if (completedBlock && finished) + { + completedBlock(image, error, cacheType); + } + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + + +- (void)cancelCurrentImageLoad +{ + // Cancel in progress downloader from queue + id operation = objc_getAssociatedObject(self, &operationKey); + if (operation) + { + [operation cancel]; + objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +@end diff --git a/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.h b/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.h new file mode 100644 index 0000000..ed6427a --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1,140 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + * + * Usage with a UITableViewCell sub-class: + * + * #import + * + * ... + * + * - (UITableViewCell *)tableView:(UITableView *)tableView + * cellForRowAtIndexPath:(NSIndexPath *)indexPath + * { + * static NSString *MyIdentifier = @"MyIdentifier"; + * + * UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + * + * if (cell == nil) + * { + * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault + * reuseIdentifier:MyIdentifier] autorelease]; + * } + * + * // Here we use the provided setImageWithURL: method to load the web image + * // Ensure you use a placeholder image otherwise cells will be initialized with no image + * [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] + * placeholderImage:[UIImage imageNamed:@"placeholder"]]; + * + * cell.textLabel.text = @"My Text"; + * return cell; + * } + * + */ +@interface UIImageView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see setImageWithURL:placeholderImage:options: + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; + +/** + * Set the imageView `image` with an `url`. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The downloand is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @param completedBlock A block called when operation has been completed. This block as no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrived from the local cache of from the network. + */ +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; + +/** + * Cancel the current download + */ +- (void)cancelCurrentImageLoad; + +@end diff --git a/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.m b/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.m new file mode 100644 index 0000000..01eab54 --- /dev/null +++ b/PSCollectionViewDemo/SDWebImage/UIImageView+WebCache.m @@ -0,0 +1,84 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+WebCache.h" +#import "objc/runtime.h" + +static char operationKey; + +@implementation UIImageView (WebCache) + +- (void)setImageWithURL:(NSURL *)url +{ + [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder +{ + [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options +{ + [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock +{ + [self setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; +{ + [self cancelCurrentImageLoad]; + + self.image = placeholder; + + if (url) + { + __weak UIImageView *wself = self; + id operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) + { + __strong UIImageView *sself = wself; + if (!sself) return; + if (image) + { + sself.image = image; + [sself setNeedsLayout]; + } + if (completedBlock && finished) + { + completedBlock(image, error, cacheType); + } + }]; + objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +- (void)cancelCurrentImageLoad +{ + // Cancel in progress downloader from queue + id operation = objc_getAssociatedObject(self, &operationKey); + if (operation) + { + [operation cancel]; + objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } +} + +@end diff --git a/PSCollectionViewDemo/ViewController.h b/PSCollectionViewDemo/ViewController.h index de581dc..0cfd0e1 100644 --- a/PSCollectionViewDemo/ViewController.h +++ b/PSCollectionViewDemo/ViewController.h @@ -7,7 +7,14 @@ // #import +#import "PSCollectionView.h" +#import "AppDelegate.h" +#import "JSONKit.h" -@interface ViewController : UIViewController +@interface ViewController : UIViewController { + PSCollectionView *waterflowView; +} + +@property (nonatomic, retain) PSCollectionView *waterflowView; @end diff --git a/PSCollectionViewDemo/ViewController.m b/PSCollectionViewDemo/ViewController.m index dbb9b41..4f41d51 100644 --- a/PSCollectionViewDemo/ViewController.m +++ b/PSCollectionViewDemo/ViewController.m @@ -7,17 +7,41 @@ // #import "ViewController.h" +#import "WaterflowViewCell.h" @interface ViewController () +@property (nonatomic, strong) NSMutableArray *waterflowViewData; + @end @implementation ViewController +@synthesize waterflowViewData = waterflowViewData; +@synthesize waterflowView; + - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. + + self.waterflowView = [[PSCollectionView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; + self.waterflowView.delegate = self; // This is for UIScrollViewDelegate + self.waterflowView.collectionViewDelegate = self; + self.waterflowView.collectionViewDataSource = self; + self.waterflowView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + + if ([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) { + self.waterflowView.numColsPortrait = 2; + self.waterflowView.numColsLandscape = 4; + } else { + self.waterflowView.numColsPortrait = 2; + self.waterflowView.numColsLandscape = 4; + } + + [self.view addSubview:waterflowView]; + + [self loadDataSource]; } - (void)didReceiveMemoryWarning @@ -26,4 +50,58 @@ - (void)didReceiveMemoryWarning // Dispose of any resources that can be recreated. } +#pragma mark - Request + +- (void)loadDataSource { + // Request + + MKNetworkOperation *op = [[AppDelegate instance].networkEngine operationWithPath:@"gallery.json" + params:nil + httpMethod:@"POST" ssl:NO]; + [op addCompletionHandler:^(MKNetworkOperation *operation) { + self.waterflowViewData = [[[operation responseData] objectFromJSONData] objectForKey:@"data"]; + NSLog(@"items is %@", self.waterflowViewData); + [self dataSourceDidLoad]; + } errorHandler:^(MKNetworkOperation *errorOp, NSError* error) { + [self dataSourceDidError]; + }]; + + [[AppDelegate instance].networkEngine enqueueOperation:op]; +} + +- (void)dataSourceDidLoad { + [waterflowView reloadData]; +} + +- (void)dataSourceDidError { + [waterflowView reloadData]; +} + +#pragma mark - PSCollection Delegate and DataSource + +- (NSInteger)numberOfRowsInCollectionView:(PSCollectionView *)collectionView { + return [self.waterflowViewData count]; +} + +- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index { + WaterflowViewCell *v = (WaterflowViewCell *)[waterflowView dequeueReusableViewForClass:nil]; + if (!v) { + v = [[WaterflowViewCell alloc] initWithFrame:CGRectZero]; + } + + [v collectionView:waterflowView fillCellWithObject:self.waterflowViewData atIndex:index]; + + return v; +} + +- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index { + NSDictionary *item = [self.waterflowViewData objectAtIndex:index]; + + return [WaterflowViewCell heightForViewWithObject:item inColumnWidth:waterflowView.colWidth]; +} + +- (void)collectionView:(PSCollectionView *)collectionView didSelectCell:(PSCollectionViewCell *)cell atIndex:(NSInteger)index { + +} + @end diff --git a/PSCollectionViewDemo/WaterflowViewCell.h b/PSCollectionViewDemo/WaterflowViewCell.h new file mode 100644 index 0000000..0b3850b --- /dev/null +++ b/PSCollectionViewDemo/WaterflowViewCell.h @@ -0,0 +1,18 @@ +// +// WaterflowViewCell.h +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import "PSCollectionViewCell.h" + +@interface WaterflowViewCell : PSCollectionViewCell { + UIImageView *funnyImage; + UILabel *funnyDescriptions; +} + ++ (CGFloat)heightForViewWithObject:(id)object inColumnWidth:(CGFloat)columnWidth; + +@end diff --git a/PSCollectionViewDemo/WaterflowViewCell.m b/PSCollectionViewDemo/WaterflowViewCell.m new file mode 100644 index 0000000..807300b --- /dev/null +++ b/PSCollectionViewDemo/WaterflowViewCell.m @@ -0,0 +1,135 @@ +// +// WaterflowViewCell.m +// PSCollectionViewDemo +// +// Created by Venus on 13-4-18. +// Copyright (c) 2013年 opomelo. All rights reserved. +// + +#import "WaterflowViewCell.h" +#import "UIImageView+WebCache.h" +#import + +#define MARGIN 8.0 + +@implementation WaterflowViewCell + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + // Initialization code + funnyImage = [[UIImageView alloc] initWithFrame:CGRectZero]; + funnyDescriptions = [[UILabel alloc] initWithFrame:CGRectZero]; + + funnyDescriptions.font = [UIFont boldSystemFontOfSize:14.0]; + funnyDescriptions.numberOfLines = 0; + funnyDescriptions.backgroundColor = [UIColor clearColor]; + + [self addSubview:funnyImage]; + [self addSubview:funnyDescriptions]; + + self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0]; + self.layer.masksToBounds = YES; + self.layer.borderWidth = 1.0f; + self.layer.cornerRadius = 10.0f; + self.layer.borderColor= [[UIColor colorWithRed:207.0f/255.0f green:207.0f/255.0f blue:207.0f/255.0f alpha:1] CGColor]; + } + return self; +} + +/* +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect +{ + // Drawing code +} +*/ + +- (void)prepareForReuse { + [super prepareForReuse]; + + funnyImage.image = nil; + funnyDescriptions.text = nil; +} + +- (void)layoutSubviews { + // NSLog(@"object is %@", self.object); + [super layoutSubviews]; + + CGFloat width = self.frame.size.width - MARGIN * 2; + CGFloat top = MARGIN; + CGFloat left = MARGIN; + + // Image + CGFloat objectWidth, objectHeight; + if ([[self.object objectForKey:@"width"] floatValue] == 0) { + objectWidth = 200.0f; + } else { + objectWidth = [[self.object objectForKey:@"width"] floatValue]; + } + if ([[self.object objectForKey:@"height"] floatValue] == 0) { + objectHeight = 200.0f; + } else { + objectHeight = [[self.object objectForKey:@"height"] floatValue]; + } + CGFloat scaledHeight = floorf(objectHeight / (objectWidth / width)); + funnyImage.frame = CGRectMake(left, top, width, scaledHeight); + + // Label + CGSize labelSize = CGSizeZero; + labelSize = [funnyDescriptions.text sizeWithFont:funnyDescriptions.font constrainedToSize:CGSizeMake(width, INT_MAX) lineBreakMode:funnyDescriptions.lineBreakMode]; + + funnyDescriptions.frame = CGRectMake(left, funnyImage.frame.origin.y + funnyImage.frame.size.height + MARGIN, labelSize.width, labelSize.height); +} + ++ (CGFloat)heightForViewWithObject:(id)object inColumnWidth:(CGFloat)columnWidth { + CGFloat height = 0.0; + CGFloat width = columnWidth - MARGIN * 2; + + height += MARGIN; + + // Image + CGFloat objectWidth = [[object objectForKey:@"width"] floatValue]; + CGFloat objectHeight = [[object objectForKey:@"height"] floatValue]; + CGFloat scaledHeight = floorf(objectHeight / (objectWidth / width)); + height += scaledHeight; + + // Label + NSString *caption = [object objectForKey:@"title"]; + CGSize labelSize = CGSizeZero; + UIFont *labelFont = [UIFont boldSystemFontOfSize:14.0]; + labelSize = [caption sizeWithFont:labelFont constrainedToSize:CGSizeMake(width, INT_MAX) lineBreakMode:NSLineBreakByWordWrapping]; + height += labelSize.height; + + height += MARGIN; + + return height; +} + +- (void)collectionView:(PSCollectionView *)collectionView fillCellWithObject:(id)object atIndex:(NSInteger)index { + [super collectionView:collectionView fillCellWithObject:object atIndex:index]; + + NSURL *showPicURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://imgur.com/%@%@", [[object objectAtIndex:index] objectForKey:@"hash"], [[object objectAtIndex:index] objectForKey:@"ext"]]]; + + SDWebImageManager *manager = [SDWebImageManager sharedManager]; + [manager downloadWithURL:showPicURL + options:0 + progress:^(NSUInteger receivedSize, long long expectedSize) { + // progression tracking code + // DLog(@"receivedSize is %u, expectedSize is %lld", receivedSize, expectedSize); + } + completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { + if (image && finished) { + + funnyImage.image = image; + } + + NSLog(@"cache Type is %i", cacheType); + }]; + + funnyDescriptions.text = [[object objectAtIndex:index] objectForKey:@"title"]; +} + +@end