diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb52a10..a23cefd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,20 +1,130 @@
# JSONKit Changelog
-## Version 1.4 2011/28/02
+## 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;
+ - (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.
@@ -26,39 +136,50 @@
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;
+ - (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;
+ - (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 (JSONKit)`–
+* 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;
+ - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
-* The following methods were added to `NSData (JSONKit)`–
+* 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;
+ - (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
@@ -173,6 +294,7 @@
* 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
@@ -262,5 +384,6 @@ No change log information was kept for versions prior to 1.2.
[-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/JSONKit.h b/JSONKit.h
index 45a86c3..71bd0c3 100644
--- a/JSONKit.h
+++ b/JSONKit.h
@@ -1,7 +1,8 @@
//
// JSONKit.h
// http://github.com/johnezang/JSONKit
-// Licensed under the terms of the BSD License, as specified below.
+// 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.
//
/*
@@ -36,6 +37,22 @@
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
@@ -109,10 +126,11 @@ enum {
typedef JKFlags JKParseOptionFlags;
enum {
- JKSerializeOptionNone = 0,
- JKSerializeOptionPretty = (1 << 0), // Not implemented yet...
- JKSerializeOptionEscapeUnicode = (1 << 1),
- JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode),
+ JKSerializeOptionNone = 0,
+ JKSerializeOptionPretty = (1 << 0),
+ JKSerializeOptionEscapeUnicode = (1 << 1),
+ JKSerializeOptionEscapeForwardSlashes = (1 << 4),
+ JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes),
};
typedef JKFlags JKSerializeOptionFlags;
@@ -153,7 +171,11 @@ typedef struct JKParseState JKParseState; // Opaque internal, private type.
@end
-@interface NSString (JSONKit)
+////////////
+#pragma mark Deserializing methods
+////////////
+
+@interface NSString (JSONKitDeserializing)
- (id)objectFromJSONString;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@@ -162,7 +184,7 @@ typedef struct JKParseState JKParseState; // Opaque internal, private type.
- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
-@interface NSData (JSONKit)
+@interface NSData (JSONKitDeserializing)
// The NSData MUST be UTF8 encoded JSON.
- (id)objectFromJSONData;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
@@ -172,20 +194,54 @@ typedef struct JKParseState JKParseState; // Opaque internal, private type.
- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
-@interface NSArray (JSONKit)
+////////////
+#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 (JSONKit)
+@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_
diff --git a/JSONKit.m b/JSONKit.m
index 012aca6..0e9331f 100644
--- a/JSONKit.m
+++ b/JSONKit.m
@@ -1,7 +1,8 @@
//
// JSONKit.m
// http://github.com/johnezang/JSONKit
-// Licensed under the terms of the BSD License, as specified below.
+// 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.
//
/*
@@ -36,6 +37,22 @@
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:
@@ -107,6 +124,10 @@ The code in isValidCodePoint() is derived from the ICU code in
#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
@@ -115,6 +136,10 @@ The code in isValidCodePoint() is derived from the ICU code in
#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.
@@ -150,7 +175,7 @@ The code in isValidCodePoint() is derived from the ICU code in
#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
+// 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)
@@ -299,16 +324,18 @@ The code in isValidCodePoint() is derived from the ICU code in
typedef NSUInteger JKValueType;
enum {
- JKEncodeAsData = 1,
- JKEncodeAsString = 2,
+ JKEncodeOptionAsData = 1,
+ JKEncodeOptionAsString = 2,
+ JKEncodeOptionAsTypeMask = 0x7,
+ JKEncodeOptionCollectionObj = (1 << 3),
+ JKEncodeOptionStringObj = (1 << 4),
+ JKEncodeOptionStringObjTrimQuotes = (1 << 5),
+
};
-typedef NSUInteger JKEncodeAsType;
+typedef NSUInteger JKEncodeOptionType;
typedef NSUInteger JKHash;
-typedef id (*NSNumberAllocImp)(id object, SEL selector);
-typedef id (*NSNumberInitWithUnsignedLongLongImp)(id object, SEL selector, unsigned long long value);
-
typedef struct JKTokenCacheItem JKTokenCacheItem;
typedef struct JKTokenCache JKTokenCache;
typedef struct JKTokenValue JKTokenValue;
@@ -326,6 +353,13 @@ The code in isValidCodePoint() is derived from the ICU code in
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;
@@ -438,9 +472,34 @@ The code in isValidCodePoint() is derived from the ICU code in
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;
@@ -489,12 +548,7 @@ The code in isValidCodePoint() is derived from the ICU code in
#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length]))
-static void jk_swizzleInstanceMethod(Class fromClass, Class toClass, SEL selector);
-static void jk_swizzleClassMethod(Class fromClass, Class toClass, SEL selector);
-
static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection);
-static NSUInteger _JKArrayCount(JKArray *array);
-static void _JKArrayIncrementMutations(JKArray *array);
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);
@@ -504,13 +558,10 @@ The code in isValidCodePoint() is derived from the ICU code in
static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection);
static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary);
static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary);
-static NSUInteger _JKDictionaryCount(JKDictionary *dictionary);
-static void _JKDictionaryIncrementMutations(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 NSUInteger _JKDictionaryGetKeysAndObjects(JKDictionary *dictionary, NSUInteger arrayLength, id keys[arrayLength], id objects[arrayLength]);
static void _JSONDecoderCleanup(JSONDecoder *decoder);
@@ -545,36 +596,69 @@ The code in isValidCodePoint() is derived from the ICU code in
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_write1(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);
-static id jk_encode(void *object, JKSerializeOptionFlags optionFlags, JKEncodeAsType encodeAs, NSError **error);
+
+#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 calculateHash(JKHash currentHash, unsigned char c);
+JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c);
-#pragma mark -
-#pragma mark ObjC Voodoo
+// 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.
-// These two functions are used to perform some ObjC swizzeling voodoo to implement our mutable collection classes.
-static void jk_swizzleInstanceMethod(Class fromClass, Class toClass, SEL selector) {
- fromClass = class_isMetaClass(fromClass) ? objc_getClass(class_getName(fromClass)) : fromClass;
- toClass = class_isMetaClass(toClass) ? objc_getClass(class_getName(toClass)) : toClass;
- class_replaceMethod(fromClass, selector, method_getImplementation(class_getInstanceMethod(toClass, selector)), method_getTypeEncoding(class_getInstanceMethod(toClass, selector)));
-}
-static void jk_swizzleClassMethod(Class fromClass, Class toClass, SEL selector) {
- fromClass = class_isMetaClass(fromClass) ? fromClass : objc_getMetaClass(class_getName(fromClass));
- toClass = class_isMetaClass(toClass) ? toClass : objc_getMetaClass(class_getName(toClass));
- class_replaceMethod(fromClass, selector, method_getImplementation(class_getClassMethod(toClass, selector)), method_getTypeEncoding(class_getClassMethod(toClass, selector)));
+// 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 : NSArray {
+@interface JKArray : NSMutableArray {
id *objects;
NSUInteger count, capacity, mutations;
}
@@ -582,22 +666,6 @@ @interface JKArray : NSArray {
@implementation JKArray
-static Class _JKArrayClass = NULL;
-static Class _JKMutableArrayClass = NULL;
-static size_t _JKArrayInstanceSize = 0UL;
-
-+ (void)load
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
-
- _JKArrayClass = objc_getClass("JKArray");
- _JKMutableArrayClass = objc_getClass("JKMutableArray");
- _JKArrayInstanceSize = class_getInstanceSize(_JKArrayClass);
- if(_JKArrayInstanceSize < 16UL) { _JKArrayInstanceSize = 16UL; }
-
- [pool release]; pool = NULL;
-}
-
+ (id)allocWithZone:(NSZone *)zone
{
#pragma unused(zone)
@@ -609,35 +677,29 @@ + (id)allocWithZone:(NSZone *)zone
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 = (mutableCollection == NO) ? _JKArrayClass : _JKMutableArrayClass;
+ 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);
}
-static NSUInteger _JKArrayCount(JKArray *array) {
- NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity));
- return(array->count);
-}
-
-static void _JKArrayIncrementMutations(JKArray *array) {
- NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity));
- array->mutations++;
-}
-
// 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))) { return; }
- array->count++;
- if(array->count >= array->capacity) {
+ 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;
- if((array->objects = (id *)reallocf(array->objects, sizeof(id) * array->capacity)) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; }
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;
}
@@ -645,18 +707,18 @@ static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger
// 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))) { return; }
+ 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 <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL));
- if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; }
+ 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] = 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--;
}
@@ -680,20 +742,23 @@ - (NSUInteger)count
- (void)getObjects:(id *)objectsPtr range:(NSRange)range
{
NSParameterAssert((objects != NULL) && (count <= capacity));
- if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; }
+ 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), objectIndex, count]; }
+ 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((objects != NULL) && (count <= capacity));
+ 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); }
@@ -703,101 +768,52 @@ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state object
return(enumeratedCount);
}
-- (id)copyWithZone:(NSZone *)zone
-{
-#pragma unused(zone)
- NSParameterAssert((objects != NULL) && (count <= capacity));
- return([self retain]);
-}
-
-- (id)mutableCopyWithZone:(NSZone *)zone
-{
- NSParameterAssert((objects != NULL) && (count <= capacity));
- return([[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
-}
-
-@end
-
-#pragma mark -
-@interface JKMutableArray : NSMutableArray
-@end
-
-@implementation JKMutableArray
-
-+ (void)load
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
-
- Class JKMutableArrayClass = objc_getClass("JKMutableArray"); Class JKArrayClass = objc_getClass("JKArray");
-
- // We swizzle the methods from JKArray in to this class (JKArrayDictionary).
-
- jk_swizzleClassMethod(JKMutableArrayClass, JKArrayClass, @selector(allocWithZone:));
-
- jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(dealloc));
- jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(count));
- jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(objectAtIndex:));
- jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(getObjects:range:));
- jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(countByEnumeratingWithState:objects:count:));
-
- [pool release]; pool = NULL;
-}
-
- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex
{
- if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
- if(objectIndex > _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, _JKArrayCount((JKArray *)self) + 1UL]; }
+ 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];
- _JKArrayInsertObjectAtIndex((JKArray *)self, anObject, objectIndex);
- _JKArrayIncrementMutations((JKArray *)self);
-}
-
-/*
-- (void)addObject:(id)anObject
-{
- [self insertObject:anObject atIndex:_JKArrayCount((JKArray *)self)];
+#endif
+ _JKArrayInsertObjectAtIndex(self, anObject, objectIndex);
+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
}
-*/
- (void)removeObjectAtIndex:(NSUInteger)objectIndex
{
- if(objectIndex >= _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, _JKArrayCount((JKArray *)self)]; }
- _JKArrayRemoveObjectAtIndex((JKArray *)self, objectIndex);
- _JKArrayIncrementMutations((JKArray *)self);
+ 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)removeLastObject
-{
- [self removeObjectAtIndex:_JKArrayCount((JKArray *)self) == 0UL ? 0UL : (_JKArrayCount((JKArray *)self) - 1UL)];
-}
-*/
-
- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject
{
- if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
- if(objectIndex >= _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, _JKArrayCount((JKArray *)self)]; }
+ 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];
- _JKArrayReplaceObjectAtIndexWithObject((JKArray *)self, objectIndex, anObject);
- _JKArrayIncrementMutations((JKArray *)self);
+#endif
+ _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject);
+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
}
- (id)copyWithZone:(NSZone *)zone
{
- NSUInteger arrayCount = [self count];
- if(arrayCount == 0UL) { return([[NSArray allocWithZone:zone] init]); }
- id stackObjects[arrayCount];
- [self getObjects:stackObjects range:NSMakeRange(0UL, arrayCount)];
- return([[NSArray allocWithZone:zone] initWithObjects:stackObjects count:arrayCount]);
+ NSParameterAssert((objects != NULL) && (count <= capacity));
+ return((mutations == 0UL) ? [self retain] : [(NSArray *)[NSArray allocWithZone:zone] initWithObjects:objects count:count]);
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
- NSUInteger arrayCount = [self count];
- if(arrayCount == 0UL) { return([[NSMutableArray allocWithZone:zone] init]); }
- id stackObjects[arrayCount];
- [self getObjects:stackObjects range:NSMakeRange(0UL, arrayCount)];
- return([[NSMutableArray allocWithZone:zone] initWithObjects:stackObjects count:arrayCount]);
+ NSParameterAssert((objects != NULL) && (count <= capacity));
+ return([(NSMutableArray *)[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
}
@end
@@ -834,7 +850,7 @@ - (void)dealloc
- (NSArray *)allObjects
{
NSParameterAssert(collection != NULL);
- NSUInteger count = [collection count], atObject = 0UL;
+ NSUInteger count = [(NSDictionary *)collection count], atObject = 0UL;
id objects[count];
while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; }
@@ -857,7 +873,7 @@ - (id)nextObject
@end
#pragma mark -
-@interface JKDictionary : NSDictionary {
+@interface JKDictionary : NSMutableDictionary {
NSUInteger count, capacity, mutations;
JKHashTableEntry *entry;
}
@@ -865,22 +881,6 @@ @interface JKDictionary : NSDictionary bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } }
return(jk_dictionaryCapacities[bottom]);
}
@@ -921,14 +921,15 @@ static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
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 JKArray instance via calloc.
- dictionary->isa = (mutableCollection == NO) ? _JKDictionaryClass : _JKMutableDictionaryClass;
+ 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;
@@ -936,6 +937,8 @@ static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
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);
}
@@ -965,22 +968,31 @@ static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) {
return(dictionary->capacity);
}
-static NSUInteger _JKDictionaryCount(JKDictionary *dictionary) {
- NSCParameterAssert(dictionary != NULL);
- return(dictionary->count);
-}
-
-static void _JKDictionaryIncrementMutations(JKDictionary *dictionary) {
- NSCParameterAssert(dictionary != NULL);
- if(++dictionary->mutations == 0UL) { dictionary->mutations = 1UL; }
-}
-
static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) {
- NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL));
+ 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) {
@@ -990,7 +1002,7 @@ static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash,
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)) { atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; }
+ 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.
@@ -1005,47 +1017,41 @@ - (NSUInteger)count
static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) {
NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
- if(aKey == NULL) { return(NULL); }
+ 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); break; }
- if(JK_EXPECT_F(atEntry->key == NULL)) { NSCParameterAssert(atEntry->object == NULL); atEntry = NULL; break; } // If the key was in the table, we would have found it by now.
+ 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(atEntry);
+ return(NULL);
}
- (id)objectForKey:(id)aKey
{
- JKHashTableEntry *atEntry = _JKDictionaryHashTableEntryForKey(self, aKey);
- return((atEntry != NULL) ? atEntry->object : NULL);
+ NSParameterAssert((entry != NULL) && (count <= capacity));
+ JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey);
+ return((entryForKey != NULL) ? entryForKey->object : NULL);
}
-static NSUInteger _JKDictionaryGetKeysAndObjects(JKDictionary *dictionary, NSUInteger arrayLength, id keys[arrayLength], id objects[arrayLength]) {
- NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
+- (void)getObjects:(id *)objects andKeys:(id *)keys
+{
+ NSParameterAssert((entry != NULL) && (count <= capacity));
NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL;
- for(atEntry = 0UL; (atEntry < dictionary->capacity) && (arrayIdx < arrayLength); atEntry++) {
- if(JK_EXPECT_T(dictionary->entry[atEntry].key != NULL)) {
- NSCParameterAssert((dictionary->entry[atEntry].object != NULL) && (arrayIdx < dictionary->count));
- if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = dictionary->entry[atEntry].key; }
- if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = dictionary->entry[atEntry].object; }
+ 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++;
}
}
- NSCParameterAssert(arrayIdx == dictionary->count);
- return(arrayIdx);
-}
-
-- (void)getObjects:(id *)objects andKeys:(id *)keys
-{
- NSParameterAssert((entry != NULL) && (count <= capacity));
- _JKDictionaryGetKeysAndObjects(self, count, keys, objects);
}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
{
- NSParameterAssert((entry != NULL) && (count <= capacity));
+ 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); }
@@ -1060,88 +1066,42 @@ - (NSEnumerator *)keyEnumerator
return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]);
}
-- (id)copyWithZone:(NSZone *)zone
-{
-#pragma unused(zone)
- NSParameterAssert((entry != NULL) && (count <= capacity));
- return([self retain]);
-}
-
-- (id)mutableCopyWithZone:(NSZone *)zone
-{
- NSParameterAssert((entry != NULL) && (count <= capacity));
- id stackKeys[count], stackObjects[count];
- NSUInteger gotCount = _JKDictionaryGetKeysAndObjects(self, count, stackKeys, stackObjects);
- NSParameterAssert(gotCount == count);
- return([[NSMutableDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
-}
-
-@end
-
-
-#pragma mark -
-@interface JKMutableDictionary : NSMutableDictionary
-@end
-
-@implementation JKMutableDictionary
-
-+ (void)load
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
-
- Class JKMutableDictionaryClass = objc_getClass("JKMutableDictionary"), JKDictionaryClass = objc_getClass("JKDictionary");
-
- // We swizzle the methods from JKDictionary in to this class (JKMutableDictionary).
-
- jk_swizzleClassMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(allocWithZone:));
-
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(dealloc));
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(count));
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(objectForKey:));
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(getObjects:andKeys:));
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(keyEnumerator));
- jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(countByEnumeratingWithState:objects:count:));
-
- [pool release]; pool = NULL;
-}
-
- (void)setObject:(id)anObject forKey:(id)aKey
{
- 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]; }
+ 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((JKDictionary *)self);
- aKey = [aKey copy];
- anObject = [anObject retain];
- _JKDictionaryAddObject((JKDictionary *)self, CFHash(aKey), aKey, anObject);
- _JKDictionaryIncrementMutations((JKDictionary *)self);
+ _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
{
- JKHashTableEntry *entry = _JKDictionaryHashTableEntryForKey((JKDictionary *)self, aKey);
- if(entry != NULL) {
- _JKDictionaryRemoveObjectWithEntry((JKDictionary *)self, entry);
- _JKDictionaryIncrementMutations((JKDictionary *)self);
+ 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
{
- NSUInteger dictionaryCount = _JKDictionaryCount((JKDictionary *)self);
- id stackKeys[dictionaryCount], stackObjects[dictionaryCount];
- NSUInteger gotCount = _JKDictionaryGetKeysAndObjects((JKDictionary *)self, dictionaryCount, stackKeys, stackObjects);
- NSParameterAssert(gotCount == dictionaryCount);
- return([[NSDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
+ NSParameterAssert((entry != NULL) && (count <= capacity));
+ return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]);
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
- NSUInteger dictionaryCount = _JKDictionaryCount((JKDictionary *)self);
- id stackKeys[dictionaryCount], stackObjects[dictionaryCount];
- NSUInteger gotCount = _JKDictionaryGetKeysAndObjects((JKDictionary *)self, dictionaryCount, stackKeys, stackObjects);
- NSParameterAssert(gotCount == dictionaryCount);
- return([[NSMutableDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
+ NSParameterAssert((entry != NULL) && (count <= capacity));
+ return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]);
}
@end
@@ -1153,7 +1113,8 @@ - (id)mutableCopyWithZone:(NSZone *)zone
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 calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); }
+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));
@@ -1450,7 +1411,7 @@ JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, ui
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 = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); }
+ while(*tokenBufferIdx < nextIdx) { *stringHash = jk_calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); }
return(0);
}
@@ -1484,8 +1445,8 @@ static int jk_parse_string(JKParseState *parseState) {
ConversionResult result;
if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; }
- stringHash = calculateHash(stringHash, currentChar);
- while(atStringCharacter < nextValidCharacter) { stringHash = calculateHash(stringHash, *atStringCharacter++); }
+ 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; }
@@ -1502,7 +1463,7 @@ static int jk_parse_string(JKParseState *parseState) {
if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; }
- stringHash = calculateHash(stringHash, currentChar);
+ stringHash = jk_calculateHash(stringHash, currentChar);
}
}
@@ -1518,9 +1479,9 @@ static int jk_parse_string(JKParseState *parseState) {
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 = JSONStringStateEscape; continue; }
if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; }
- stringHash = calculateHash(stringHash, currentChar);
+ if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; }
+ stringHash = jk_calculateHash(stringHash, currentChar);
tokenBuffer[tokenBufferIdx++] = currentChar;
continue;
} else { // UTF8 sequence
@@ -1535,7 +1496,7 @@ static int jk_parse_string(JKParseState *parseState) {
atStringCharacter = nextValidCharacter - 1;
continue;
} else {
- while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); }
+ while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = jk_calculateHash(stringHash, *atStringCharacter++); }
atStringCharacter--;
continue;
}
@@ -1563,7 +1524,7 @@ static int jk_parse_string(JKParseState *parseState) {
parsedEscapedChar:
stringState = JSONStringStateParsing;
- stringHash = calculateHash(stringHash, escapedChar);
+ stringHash = jk_calculateHash(stringHash, escapedChar);
tokenBuffer[tokenBufferIdx++] = escapedChar;
break;
@@ -1623,7 +1584,7 @@ static int jk_parse_string(JKParseState *parseState) {
break;
case JSONStringStateEscapedNeedEscapeForSurrogate:
- if((currentChar == '\\')) { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; }
+ 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; } }
@@ -1716,7 +1677,7 @@ static int jk_parse_number(JKParseState *parseState) {
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);
+ 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);
@@ -1741,17 +1702,17 @@ static int jk_parse_number(JKParseState *parseState) {
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;
- 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;
+ 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 = calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); }
+ 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."); }
@@ -1836,25 +1797,19 @@ static int jk_parse_next_token(JKParseState *parseState) {
if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) {
currentCharacter = *atCharacterPtr;
- switch(currentCharacter) {
- case '{': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); break;
- case '}': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); break;
- case '[': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); break;
- case ']': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); break;
- case ',': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); break;
- case ':': jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); break;
-
- case '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); } break;
- case '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); } break;
- case '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); } break;
-
- case '"': 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); } break;
-
- case '-': // fall-thru
- case '0' ... '9': 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); } break;
-
- default: stopParsing = 1; /* XXX Add error message */ break;
- }
+ 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'."); }
@@ -1943,12 +1898,8 @@ static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSStr
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((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);
- }
+ 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;
@@ -2024,7 +1975,7 @@ static id json_parse_it(JKParseState *parseState) {
#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.
+// 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);
@@ -2035,9 +1986,8 @@ JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
//
// 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. The age is the number of rightmost 1 bits, i.e. 0000 = 0, 0001 = 1, 0011 = 2, 0111 = 3, 1111 = 4.
-// This allows us to use left and right shifts to add or subtract from an items age. Add = (age << 1) | 1. Subtract = age >> 0. Subtract is synonymous with "age" (i.e., age an item).
-// The reason for this is it allows us to perform saturated adds and subtractions and is branchless.
+// 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.
@@ -2052,12 +2002,12 @@ JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
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(strncmp((const char *)parseState->cache.items[bucket].bytes, (const char *)parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) {
- parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U;
+ 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));
@@ -2127,26 +2077,6 @@ JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
#pragma mark -
@implementation JSONDecoder
-static Class _jk_NSNumberClass;
-static NSNumberAllocImp _jk_NSNumberAllocImp;
-static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp;
-
-+ (void)load
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
-
- _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;
-}
-
+ (id)decoder
{
return([self decoderWithParseOptions:JKParseOptionStrict]);
@@ -2269,37 +2199,38 @@ static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections,
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 parseUTF8String:string length:length error:NULL]);
+ 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
{
- 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, length, error));
+ return([self objectWithUTF8String:string length:length error:error]);
}
// Deprecated in JSONKit v1.4. Use objectWithData: instead.
- (id)parseJSONData:(NSData *)jsonData
{
- return([self parseJSONData:jsonData error:NULL]);
+ return([self objectWithData:jsonData error:NULL]);
}
// Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error
{
- if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
- return([self parseUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
+ return([self objectWithData:jsonData error:error]);
}
+////////////
+#pragma mark Methods that return immutable collection objects
+////////////
-
-// Methods that return immutable collection objects.
- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
{
return([self objectWithUTF8String:string length:length error:NULL]);
@@ -2320,11 +2251,14 @@ - (id)objectWithData:(NSData *)jsonData
- (id)objectWithData:(NSData *)jsonData error:(NSError **)error
{
- if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
+ 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]);
}
-// Methods that return mutable collection objects.
+////////////
+#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]);
@@ -2345,7 +2279,7 @@ - (id)mutableObjectWithData:(NSData *)jsonData
- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error
{
- if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
+ 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]);
}
@@ -2386,7 +2320,7 @@ - (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error
autorelease limbo, but we've done our best to minimize that impact, so it all balances out.
*/
-@implementation NSString (JSONKit)
+@implementation NSString (JSONKitDeserializing)
static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) {
id returnObject = NULL;
@@ -2446,7 +2380,7 @@ - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptio
@end
-@implementation NSData (JSONKit)
+@implementation NSData (JSONKitDeserializing)
- (id)objectFromJSONData
{
@@ -2507,63 +2441,81 @@ static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) {
}
}
-
+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;
+ va_list varArgsList, varArgsListCopy;
va_start(varArgsList, format);
- va_end(varArgsList);
+ va_copy(varArgsListCopy, varArgsList);
- if( encodeState->stringBuffer.bytes.length < encodeState->atIndex) { jk_encode_error(encodeState, @"Internal inconsistency error: atIndex > buffer length. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); return(1); }
- if((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < 1024L) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } }
+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
- char *atPtr = (char *)encodeState->stringBuffer.bytes.ptr + encodeState->atIndex;
- ssize_t remaining = encodeState->stringBuffer.bytes.length - encodeState->atIndex;
+ ssize_t formattedStringLength = 0L;
+ int returnValue = 0;
- int printfAdded = vsnprintf(atPtr, remaining, format, varArgsList);
-
- while(printfAdded > remaining) {
- if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->stringBuffer.bytes.length + (printfAdded * 2UL) + 1024UL) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); }
- remaining = encodeState->stringBuffer.bytes.length - encodeState->atIndex;
- printfAdded = vsnprintf(atPtr, remaining, format, varArgsList);
+ 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; }
}
-
- encodeState->atIndex += printfAdded;
- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
- return(0);
+
+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) {
-#ifndef NS_BLOCK_ASSERTIONS
- if(JK_EXPECT_F(encodeState->stringBuffer.bytes.length < encodeState->atIndex)) { jk_encode_error(encodeState, @"Internal inconsistency error: atIndex > buffer length. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); return(1); }
-#endif
- if(JK_EXPECT_F((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < 1024L)) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } }
+ 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); }
- char *atPtr = (char *)encodeState->stringBuffer.bytes.ptr + encodeState->atIndex;
- ssize_t remaining = encodeState->stringBuffer.bytes.length - encodeState->atIndex;
+ 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);
+}
- ssize_t idx = 0L, added = 0L;
- for(added = 0L, idx = 0L; format[added] != 0; added++) { if(JK_EXPECT_T(idx < remaining)) { atPtr[idx++] = format[added]; } }
+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);
+}
- if(JK_EXPECT_F(added > remaining)) {
- if(JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + added + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); }
- for(added = 0L, idx = 0L; format[added] != 0; added++) { if(JK_EXPECT_T(idx < remaining)) { atPtr[idx++] = format[added]; } }
+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); } }
}
-
- atPtr[idx] = 0;
- encodeState->atIndex += added;
- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
+ NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
return(0);
}
-static int jk_encode_write1(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) {
- if((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; }
- else { if(JK_EXPECT_F(jk_encode_write(encodeState, cacheSlot, startingAtIndex, object, format))) { return(1); } }
- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
+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;
@@ -2575,20 +2527,10 @@ JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) {
return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) );
}
-JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) {
- NSCParameterAssert((encodeState != NULL) && ((cacheSlot == NULL) ? 1 : object != NULL));
- if(JK_EXPECT_T(cacheSlot != NULL)) {
- cacheSlot->object = object;
- cacheSlot->offset = startingAtIndex;
- cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex);
- }
-}
-
static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) {
- NSCParameterAssert((encodeState != NULL) && (objectPtr != NULL));
- NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL));
- id object = (id)objectPtr;
+ id object = (id)objectPtr, encodeCacheObject = object;
int isClass = JKClassUnknown;
size_t startingAtIndex = encodeState->atIndex;
@@ -2596,39 +2538,109 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
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);
}
- if(object->isa == encodeState->fastClassLookup.stringClass) { isClass = JKClassString; }
- else if(object->isa == encodeState->fastClassLookup.numberClass) { isClass = JKClassNumber; }
- else if(object->isa == encodeState->fastClassLookup.dictionaryClass) { isClass = JKClassDictionary; }
- else if(object->isa == encodeState->fastClassLookup.arrayClass) { isClass = JKClassArray; }
- else if(object->isa == encodeState->fastClassLookup.nullClass) { isClass = JKClassNull; }
+ // 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 {
- if([object isKindOfClass:[NSString class]]) { encodeState->fastClassLookup.stringClass = object->isa; isClass = JKClassString; }
- else if([object isKindOfClass:[NSNumber class]]) { encodeState->fastClassLookup.numberClass = object->isa; isClass = JKClassNumber; }
- else if([object isKindOfClass:[NSDictionary class]]) { encodeState->fastClassLookup.dictionaryClass = object->isa; isClass = JKClassDictionary; }
- else if([object isKindOfClass:[NSArray class]]) { encodeState->fastClassLookup.arrayClass = object->isa; isClass = JKClassArray; }
- else if([object isKindOfClass:[NSNull class]]) { encodeState->fastClassLookup.nullClass = object->isa; isClass = JKClassNull; }
- else { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); }
+ 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) {
- size_t utf8Idx = 0UL;
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); }
- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"';
+ 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);
@@ -2640,16 +2652,16 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
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_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx])) { return(1); } 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] == '\\')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; }
+ 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);
- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"';
- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
return(0);
}
}
@@ -2659,7 +2671,7 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
CFIndex stringLength = CFStringGetLength((CFStringRef)object);
CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L;
- if(((size_t)maxStringUTF8Length > encodeState->utf8ConversionBuffer.bytes.length) && (jk_managedBuffer_resize(&encodeState->utf8ConversionBuffer, maxStringUTF8Length + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); }
+ 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);
@@ -2670,7 +2682,7 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr;
size_t utf8Idx = 0UL;
- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"';
+ 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);
@@ -2682,7 +2694,7 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
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_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx])) { return(1); } 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)) {
@@ -2693,18 +2705,18 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
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(u32ch <= 0xffffU) { if(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch)) { return(1); } }
- else { if(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x\\u%4.4x", (0xd7c0U + (u32ch >> 10)), (0xdc00U + (u32ch & 0x3ffU)))) { return(1); } }
+ 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((utf8String[utf8Idx] == '\"') || (utf8String[utf8Idx] == '\\')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; }
+ 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);
- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"';
- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
return(0);
}
}
@@ -2712,30 +2724,31 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
case JKClassNumber:
{
- if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "true", 4UL)); }
- else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "false", 5UL)); }
+ 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':
+ case 'c': case 'i': case 's': case 'l': case 'q':
if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) {
- if(llv < 0LL) { llv = -llv; isNegative = 1; }
- if(JK_EXPECT_F(llv < 10LL)) { *--aptr = llv + '0'; } else { while(JK_EXPECT_T(llv > 0LL)) { *--aptr = (llv % 10LL) + '0'; llv /= 10LL; NSCParameterAssert(aptr > anum); } }
- if(isNegative) { *--aptr = '-'; }
- NSCParameterAssert(aptr > anum);
- return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, aptr, &anum[255] - aptr));
+ 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, object, aptr, &anum[255] - aptr));
+ 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':
@@ -2743,7 +2756,7 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
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, object, "%.17g", dv));
+ 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;
@@ -2756,15 +2769,15 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
{
int printComma = 0;
CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L;
- if(jk_encode_write1(encodeState, NULL, 0UL, NULL, "[")) { return(1); }
- if(arrayCount > 1020L) {
- for(id arrayObject in object) { if(printComma) { if(jk_encode_write1(encodeState, NULL, 0UL, NULL, ",")) { return(1); } } printComma = 1; if(jk_encode_add_atom_to_buffer(encodeState, arrayObject)) { return(1); } }
+ 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(printComma) { if(jk_encode_write1(encodeState, NULL, 0UL, NULL, ",")) { return(1); } } printComma = 1; if(jk_encode_add_atom_to_buffer(encodeState, objects[idx])) { return(1); } }
+ 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); } }
}
- if(jk_encode_write1(encodeState, NULL, 0UL, NULL, "]")) { return(1); }
+ return(jk_encode_write1(encodeState, -1L, "]"));
}
break;
@@ -2772,34 +2785,37 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
{
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, NULL, 0UL, NULL, "{"))) { return(1); }
- if(JK_EXPECT_F(dictionaryCount > 1020L)) {
- for(id keyObject in object) {
- if(printComma) { if(JK_EXPECT_F(jk_encode_write1(encodeState, NULL, 0UL, NULL, ","))) { return(1); } }
+ 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;
- if(JK_EXPECT_F((keyObject->isa != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(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, NULL, 0UL, NULL, ":"))) { 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_F(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, NULL, 0UL, NULL, ","))) { return(1); } }
+ if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
printComma = 1;
- if(JK_EXPECT_F(((id)keys[idx])->isa != 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); }
+ 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, NULL, 0UL, NULL, ":"))) { 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); }
}
}
- if(JK_EXPECT_F(jk_encode_write1(encodeState, NULL, 0UL, NULL, "}"))) { return(1); }
+ return(jk_encode_write1(encodeState, -1L, "}"));
}
break;
- case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "null", 4UL)); 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;
}
@@ -2808,121 +2824,242 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object
}
-static id jk_encode(void *object, JKSerializeOptionFlags optionFlags, JKEncodeAsType encodeAs, NSError **error) {
- NSCParameterAssert(object != NULL);
- id returnObject = NULL;
+@implementation JKSerializer
- if((error != NULL) && (*error != NULL)) { *error = NULL; }
++ (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]);
+}
- JKEncodeState encodeState;
- memset(&encodeState, 0, sizeof(JKEncodeState));
+- (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));
- encodeState.serializeOptionFlags = optionFlags;
+ 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); }
- encodeState.stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL);
- encodeState.utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL;
+ 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));
+ 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(jk_encode_add_atom_to_buffer(&encodeState, object) == 0) {
- switch(encodeAs) {
- case JKEncodeAsData: {
- NSData *jsonData = NULL;
- if((encodeState.stringBuffer.flags & JKManagedBufferMustFree) == 0) {
- if((jsonData = [(NSData *)CFDataCreate(NULL, encodeState.stringBuffer.bytes.ptr, encodeState.atIndex) autorelease]) == NULL) { jk_encode_error(&encodeState, @"Unable to create NSData object"); }
- } else {
- if((encodeState.stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState.stringBuffer.bytes.ptr, encodeState.atIndex)) != NULL) {
- if((jsonData = [(NSData *)CFDataCreateWithBytesNoCopy(NULL, encodeState.stringBuffer.bytes.ptr, encodeState.atIndex, NULL) autorelease]) == NULL) { jk_encode_error(&encodeState, @"Unable to create NSData object"); }
- }
- if((jsonData != NULL) || (encodeState.stringBuffer.bytes.ptr == NULL)) {
- encodeState.stringBuffer.flags &= ~JKManagedBufferMustFree;
- encodeState.stringBuffer.bytes.ptr = NULL;
- encodeState.stringBuffer.bytes.length = 0UL;
- }
- }
- returnObject = jsonData;
- }
+ 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 JKEncodeAsString: {
- NSString *jsonString = NULL;
- if((encodeState.stringBuffer.flags & JKManagedBufferMustFree) == 0) {
- if((jsonString = [(NSString *)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((encodeState.stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState.stringBuffer.bytes.ptr, encodeState.atIndex + 256UL)) != NULL) {
- encodeState.stringBuffer.bytes.ptr[encodeState.atIndex + 1UL] = 0;
- if((jsonString = [(NSString *)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"); }
- }
- if((jsonString != NULL) || (encodeState.stringBuffer.bytes.ptr == NULL)) {
- encodeState.stringBuffer.flags &= ~JKManagedBufferMustFree;
- encodeState.stringBuffer.bytes.ptr = NULL;
- encodeState.stringBuffer.bytes.length = 0UL;
- }
- }
- returnObject = jsonString;
- }
+ 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;
+ 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; }
}
- if((error != NULL) && (encodeState.error != NULL)) { *error = encodeState.error; }
- jk_managedBuffer_release(&encodeState.stringBuffer);
- jk_managedBuffer_release(&encodeState.utf8ConversionBuffer);
+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 (JSONKit)
+@implementation NSArray (JSONKitSerializing)
+
+// NSData returning methods...
- (NSData *)JSONData
{
- return([self JSONDataWithOptions:JKSerializeOptionNone error:NULL]);
+ 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(jk_encode(self, serializeOptions, JKEncodeAsData, 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([self JSONStringWithOptions:JKSerializeOptionNone error:NULL]);
+ 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(jk_encode(self, serializeOptions, JKEncodeAsString, 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 (JSONKit)
+@implementation NSDictionary (JSONKitSerializing)
+
+// NSData returning methods...
- (NSData *)JSONData
{
- return([self JSONDataWithOptions:JKSerializeOptionNone error:NULL]);
+ 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(jk_encode(self, serializeOptions, JKEncodeAsData, 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([self JSONStringWithOptions:JKSerializeOptionNone error:NULL]);
+ 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(jk_encode(self, serializeOptions, JKEncodeAsString, 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/README.md b/README.md
index da99954..8b4a4d9 100644
--- a/README.md
+++ b/README.md
@@ -1,15 +1,16 @@
# JSONKit
-JSONKit is licensed under the terms of the BSD License. Copyright © 2011, John Engelhart.
+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
-
-| Parsing | Serializing |
- |
- |
-23% Faster than Binary .plist ! | 549% Faster than Binary .plist ! |
-
+**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
+:---------:|:-------------:
+
|
+*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`.
@@ -21,6 +22,8 @@ JSONKit is licensed under the terms of the BSD License. Copyright © 2011,
* 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][].
@@ -36,15 +39,14 @@ JSON provides the following primitive types:
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].
@@ -69,7 +71,7 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S
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.`
+ [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].
@@ -83,21 +85,45 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S
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 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] is focused capatability with the [Unicode Standard][], 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`.
+ 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
-* 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.
+* 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.
-* 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.
+* 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.
-* 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.
### Reporting Bugs
@@ -107,11 +133,13 @@ The author requests that you do not file a bug report with JSONKit regarding pro
### Important Details
-* JSONKit is not designed to be used with the Mac OS X Garbage Collection. The behavior of JSONKit when compiled with `-fobj-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 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 `-parseJSONData:` 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`.
+* 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.
@@ -119,91 +147,139 @@ The author requests that you do not file a bug report with JSONKit regarding pro
* 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 uses the [`-UTF8String`][NSString_UTF8String] method to obtain a `UTF8` encoded version of a [`NSString`][NSString], and while the details of how a strings performs that conversion are an internal implementation detail, it is likely that this conversion carries a cost both in terms of time and the memory needed to store the conversion result. Therefore, if speed is a priority, you should avoid using the [`NSString`][NSString] convenience methods if possible.
+* 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 `-parseUTF8String: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 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 `parseJSONData:` 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 `parseJSONData:` method repeatedly, you can avoid this overhead.
+* 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:** `parseUTF8String:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `parseUTF8String` is `NULL`.
-**Important:** `parseJSONData:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `jsonData` is `NULL`.
+**Important:** `objectWithUTF8String:` and `mutableObjectWithUTF8String:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `string` is `NULL`.
+**Important:** `objectWithData:` and `mutableObjectWithData:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `jsonData` is `NULL`.
-+ (id)decoder;
+```objective-c
++ (id)decoder;
+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (void)clearCache;
-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length;
-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error;
+- (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)parseJSONData:(NSData *)jsonData;
-- (id)parseJSONData:(NSData *)jsonData 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
-- (id)objectFromJSONString;
+```objective-c
+- (id)objectFromJSONString;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+- (id)mutableObjectFromJSONString;
+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+```
#### NSData Interface
-- (id)objectFromJSONData;
+```objective-c
+- (id)objectFromJSONData;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+- (id)mutableObjectFromJSONData;
+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
+```
#### JKParseOptionFlags
| Parsing Option | Description |
- JKParseOptionNone | This 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. |
- JKParseOptionStrict | The JSON will be parsed in strict accordance with the RFC 4627 specification. |
- JKParseOptionComments | Allow 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. |
- JKParseOptionUnicodeNewlines | Allow 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. |
- 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, as specified in The Unicode 6.0 standard, Chapter 3, section 3.9 Unicode Encoding Forms. |
- JKParseOptionPermitTextAfterValidJSON | Normally, white-space that follows the JSON is interpreted as a parsing failure. This option allows for any trailing white-space to be ignored and not cause a parsing error. |
+ JKParseOptionNone | This 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. |
+ JKParseOptionStrict | The JSON will be parsed in strict accordance with the RFC 4627 specification. |
+ JKParseOptionComments | Allow 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. |
+ JKParseOptionUnicodeNewlines | Allow 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. |
+ 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, as specified in The Unicode 6.0 standard, Chapter 3, section 3.9 Unicode Encoding Forms. |
+ JKParseOptionPermitTextAfterValidJSON | Normally, 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
-**Note:** The bytes contained in the returned [`NSData`][NSData] object is `UTF8` encoded.
+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
-- (NSData *)JSONData;
+```objective-c
+- (NSData *)JSONData;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSString *)JSONString;
-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
+- (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 Option | Description |
- JKSerializeOptionNone | This 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. |
- JKSerializeOptionEscapeUnicode | When 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)"] |
+ JKSerializeOptionNone | This 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. |
+ JKSerializeOptionPretty | Normally 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. |
+ JKSerializeOptionEscapeUnicode | When 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)"] |
+ JKSerializeOptionEscapeForwardSlashes | According 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
-[Double Precision]: http://en.wikipedia.org/wiki/Double_precision
+[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
@@ -219,12 +295,16 @@ The author requests that you do not file a bug report with JSONKit regarding pro
[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
-[NSCParameterAssert]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/macro/NSCParameterAssert
-[UnicodeNewline]: http://en.wikipedia.org/wiki/Newline#Unicode
-[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy
+[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