Merge lp:~rockstar/ubuntuone-ios-music/ios5-round-one into lp:ubuntuone-ios-music

Proposed by Paul Hummer
Status: Merged
Approved by: Paul Hummer
Approved revision: 232
Merged at revision: 230
Proposed branch: lp:~rockstar/ubuntuone-ios-music/ios5-round-one
Merge into: lp:ubuntuone-ios-music
Diff against target: 4126 lines (+8/-3998)
7 files modified
Dependencies/JSONKit/CHANGELOG.md (+0/-389)
Dependencies/JSONKit/JSONKit.h (+0/-251)
Dependencies/JSONKit/JSONKit.m (+0/-3022)
Dependencies/JSONKit/README.md (+0/-307)
U1Music.xcodeproj/project.pbxproj (+4/-22)
utilities/operations/UOJSONFetchOperation.m (+1/-4)
view_controllers/UOMusicLoginController.m (+3/-3)
To merge this branch: bzr merge lp:~rockstar/ubuntuone-ios-music/ios5-round-one
Reviewer Review Type Date Requested Status
Zachery Bir Approve
Review via email: mp+121514@code.launchpad.net

Commit message

Remove JSONKit dependency, bump to iOS 5

Description of the change

Bump to iOS 5.0. Remove JSONKit dependency (much easier than I expected)

To post a comment you must log in.
Revision history for this message
Zachery Bir (urbanape) wrote :

Go for it. It's time to go 5.0+ (sorry, Martin)

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== removed file 'Dependencies/JSONKit/CHANGELOG.md'
2--- Dependencies/JSONKit/CHANGELOG.md 2011-07-10 22:17:52 +0000
3+++ Dependencies/JSONKit/CHANGELOG.md 1970-01-01 00:00:00 +0000
4@@ -1,389 +0,0 @@
5-# JSONKit Changelog
6-
7-## Version 1.X ????/??/??
8-
9-**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.
10-
11-### New Features
12-
13-* When `JKSerializeOptionPretty` is enabled, JSONKit now sorts the keys.
14-
15-* 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.
16-
17- 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.
18-
19- 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.
20-
21- This greatly simplifies things when you have a complex, nested objects with objects that do not belong to the classes that JSONKit can serialize.
22-
23- 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).
24-
25- To serialize NSArray or NSDictionary objects using a delegate–
26-
27- **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:`).
28- **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail.
29-
30- <pre>
31- &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
32- &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
33- </pre>
34-
35- To serialize NSArray or NSDictionary objects using a `^` block&ndash;
36-
37- **NOTE:** The block is passed a single argument, the object with the unsupported class.
38- **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail.
39-
40- <pre>
41- &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(&#x005E;)(id object))block error:(NSError \*\*)error;
42- &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(&#x005E;)(id object))block error:(NSError \*\*)error;
43- </pre>
44-
45- Example using the delegate way:
46-
47- <pre>
48- @interface MYFormatter : NSObject {
49- NSDateFormatter \*outputFormatter;
50- }
51- @end
52- &#x200b;
53- @implementation MYFormatter
54- -(id)init
55- {
56- if((self = [super init]) == NULL) { return(NULL); }
57- if((outputFormatter = [[NSDateFormatter alloc] init]) == NULL) { [self autorelease]; return(NULL); }
58- [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
59- return(self);
60- }
61- &#x200b;
62- -(void)dealloc
63- {
64- if(outputFormatter != NULL) { [outputFormatter release]; outputFormatter = NULL; }
65- [super dealloc];
66- }
67- &#x200b;
68- -(id)formatObject:(id)object
69- {
70- if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
71- return(NULL);
72- }
73- @end
74- &#x200b;
75- {
76- MYFormatter \*myFormatter = [[[MYFormatter alloc] init] autorelease];
77- NSArray \*array = [NSArray arrayWithObject:[NSDate dateWithTimeIntervalSinceNow:0.0]];
78-
79- NSString \*jsonString = NULL;
80- jsonString = [array JSONStringWithOptions:JKSerializeOptionNone
81- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;serializeUnsupportedClassesUsingDelegate:myFormatter
82- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;selector:@selector(formatObject:)
83- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error:NULL];
84- NSLog(@"jsonString: '%@'", jsonString);
85- // 2011-03-25 11:42:16.175 formatter_example[59120:903] jsonString: '["2011-03-25T11:42:16.175-0400"]'
86- }
87- </pre>
88-
89- Example using the `^` block way:
90-
91- <pre>
92- {
93- NSDateFormatter \*outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
94- [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
95- &#x200b;
96- jsonString = [array JSONStringWithOptions:encodeOptions
97- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;serializeUnsupportedClassesUsingBlock:&#x005E;id(id object) {
98- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
99- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return(NULL);
100- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
101- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error:NULL];
102- NSLog(@"jsonString: '%@'", jsonString);
103- // 2011-03-25 11:49:56.434 json_parse[59167:903] jsonString: '["2011-03-25T11:49:56.434-0400"]'
104- }
105- </pre>
106-
107-### Major Changes
108-
109-* 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.
110-
111-## Version 1.4 2011/23/03
112-
113-### Highlights
114-
115-* 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.
116-
117-### New Features
118-
119-* JSONKit can now return mutable collection classes.
120-* The `JKSerializeOptionFlags` option `JKSerializeOptionPretty` was implemented.
121-* It is now possible to serialize a single [`NSString`][NSString]. This functionality was requested in issue #4 and issue #11.
122-
123-### Deprecated Methods
124-
125-* The following `JSONDecoder` methods are deprecated beginning with JSONKit v1.4 and will be removed in a later release&ndash;
126-
127- <pre>
128- &#x200b;- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length;
129- &#x200b;- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length error:(NSError \*\*)error;
130- &#x200b;- (id)parseJSONData:(NSData \*)jsonData;
131- &#x200b;- (id)parseJSONData:(NSData \*)jsonData error:(NSError \*\*)error;
132- </pre>
133-
134- The JSONKit v1.4 <code>objectWith&hellip;</code> methods should be used instead.
135-
136-### NEW API's
137-
138-* The following methods were added to `JSONDecoder`&ndash;
139-
140- These methods replace their deprecated <code>parse&hellip;</code> counterparts and return immutable collection objects.
141-
142- <pre>
143- &#x200b;- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
144- &#x200b;- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
145- &#x200b;- (id)objectWithData:(NSData \*)jsonData;
146- &#x200b;- (id)objectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
147- </pre>
148-
149- These methods are the same as their <code>objectWith&hellip;</code> counterparts except they return mutable collection objects.
150-
151- <pre>
152- &#x200b;- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
153- &#x200b;- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
154- &#x200b;- (id)mutableObjectWithData:(NSData \*)jsonData;
155- &#x200b;- (id)mutableObjectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
156- </pre>
157-
158-* The following methods were added to `NSString (JSONKitDeserializing)`&ndash;
159-
160- These methods are the same as their <code>objectFrom&hellip;</code> counterparts except they return mutable collection objects.
161-
162- <pre>
163- &#x200b;- (id)mutableObjectFromJSONString;
164- &#x200b;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
165- &#x200b;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
166- </pre>
167-
168-* The following methods were added to `NSData (JSONKitDeserializing)`&ndash;
169-
170- These methods are the same as their <code>objectFrom&hellip;</code> counterparts except they return mutable collection objects.
171-
172- <pre>
173- &#x200b;- (id)mutableObjectFromJSONData;
174- &#x200b;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
175- &#x200b;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
176- </pre>
177-
178-* The following methods were added to `NSString (JSONKitSerializing)`&ndash;
179-
180- These methods are for those uses that need to serialize a single [`NSString`][NSString]&ndash;
181-
182- <pre>
183- &#x200b;- (NSData \*)JSONData;
184- &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
185- &#x200b;- (NSString \*)JSONString;
186- &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
187- </pre>
188-
189-### Bug Fixes
190-
191-* JSONKit has a fast and a slow path for parsing JSON Strings. The slow path is needed whenever special string processing is required, such as the conversion of `\` escape sequences or ill-formed UTF-8. Although the slow path had a check for characters < `0x20`, which are not permitted by the [RFC 4627][], there was a bug such that the condition was never actually checked. As a result, JSONKit would have incorrectly accepted JSON that contained characters < `0x20` if it was using the slow path to process a JSON String.
192-* The low surrogate in a <code>\u<i><b>high</b></i>\u<i><b>low</b></i></code> escape sequence in a JSON String was incorrectly treating `dfff` as ill-formed Unicode. This was due to a comparison that used `>= 0xdfff` instead of `> 0xdfff` as it should have.
193-* `JKParseOptionLooseUnicode` was not properly honored when parsing some types of ill-formed Unicode in <code>\u<i><b>HHHH</b></i></code> escapes in JSON Strings.
194-
195-### Important Notes
196-
197-* JSONKit v1.4 now uses custom concrete subclasses of [`NSArray`][NSArray], [`NSMutableArray`][NSMutableArray], [`NSDictionary`][NSDictionary], and [`NSMutableDictionary`][NSMutableDictionary]&mdash; `JKArray`, `JKMutableArray`, `JKDictionary`, and `JKMutableDictionary`. respectively. These classes are internal and private to JSONKit, you should not instantiate objects from these classes directly.
198-
199- In theory, these custom classes should behave exactly the same as the respective Foundation / Cocoa counterparts.
200-
201- As usual, in practice may have non-linear excursions from what theory predicts. It is also virtually impossible to properly test or predict how these custom classes will interact with software in the wild.
202-
203- Most likely, if you do encounter a problem, it will happen very quickly, and you should report a bug via the [github.com JSONKit Issue Tracker][bugtracker].
204-
205- In addition to the required class cluster primitive methods, the custom collection classes also include support for [`NSFastEnumeration`][NSFastEnumeration], along with methods that support the bulk retrieval of the objects contents.
206-
207- #### Exceptions Thrown
208-
209- The JSONKit collection classes will throw the same exceptions for the same conditions as their respective Foundation counterparts. If you find a discrepancy, please report a bug via the [github.com JSONKit Issue Tracker][bugtracker].
210-
211- #### Multithreading Safety
212-
213- The same multithreading rules and caveats for the Foundation collection classes apply to the JSONKit collection classes. Specifically, it should be safe to use the immutable collections from multiple threads concurrently.
214-
215- The mutable collections can be used from multiple threads as long as you provide some form of mutex barrier that ensures that if a thread needs to mutate the collection, then it has exclusive access to the collection&ndash; no other thread can be reading from or writing to the collection until the mutating thread has finished. Failure to ensure that there are no other threads reading or writing from the mutable collection when a thread mutates the collection will result in `undefined` behavior.
216-
217- #### Mutable Collection Notes
218-
219- The mutable versions of the collection classes are meant to be used when you need to make minor modifications to the collection. Neither `JKMutableArray` or `JKMutableDictionary` have been optimized for nor are they intended to be used in situations where you are adding a large number of objects or new keys&ndash; these types of operations will cause both classes to frequently reallocate the memory used to hold the objects in the collection.
220-
221- #### `JKMutableArray` Usage Notes
222-
223- * You should minimize the number of new objects you added to the array. The array is not designed for high performance insertion and removal of objects. If the array does not have any extra capacity it must reallocate the backing store. When the array is forced to grow the backing store, it currently adds an additional 16 slots worth of spare capacity. The array is instantiated without any extra capacity on the assumption that dictionaries are going to be mutated more than arrays. The array never shrinks the backing store.
224-
225- * Replacing objects in the array via [`-replaceObjectAtIndex:withObject:`][-replaceObjectAtIndex:withObject:] is very fast since the array simply releases the current object at the index and replaces it with the new object.
226-
227- * Inserting an object in to the array via [`-insertObject:atIndex:`][-insertObject:atIndex:] cause the array to [`memmove()`][memmove] all the objects up one slot from the insertion index. This means this operation is fastest when inserting objects at the last index since no objects need to be moved.
228-
229- * Removing an object from the array via [`-removeObjectAtIndex:`][-removeObjectAtIndex:] causes the array to [`memmove()`][memmove] all the objects down one slot from the removal index. This means this operation is fastest when removing objects at the last index since no objects need to be moved. The array will not resize its backing store to a smaller size.
230-
231- * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSArray`][NSArray] or [`NSMutableArray`][NSMutableArray] class object, respectively, with the contents of the receiver.
232-
233- #### `JKMutableDictionary` Usage Notes
234-
235- * You should minimize the number of new keys you add to the dictionary. If the number of items in the dictionary exceeds a threshold value it will trigger a resizing operation. To do this, the dictionary must allocate a new, larger backing store, and then re-add all the items in the dictionary by rehashing them to the size of the newer, larger store. This is an expensive operation. While this is a limitation of nearly all hash tables, the capacity for the hash table used by `JKMutableDictionary` has been chosen to minimize the amount of memory used since it is anticipated that most dictionaries will not grow significantly once they are instantiated.
236-
237- * If the key already exists in the dictionary and you change the object associated with it via [`-setObject:forKey:`][-setObject:forKey:], this will not cause any performance problems or trigger a hash table resize.
238-
239- * Removing a key from the dictionary via [`-removeObjectForKey:`][-removeObjectForKey:] will not cause any performance problems. However, the dictionary will not resize its backing store to the smaller size.
240-
241- * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSDictionary`][NSDictionary] or [`NSMutableDictionary`][NSMutableDictionary] class object, respectively, with the contents of the receiver.
242-
243-### Major Changes
244-
245-* The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag that was added to JSONKit v1.3 has been removed.
246-
247- `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was added in JSONKit v1.3 as a temporary work around. While the author was aware of other ways to fix the particular problem caused by the usage of "transfer of ownership callbacks" with Core Foundation classes, the fix provided in JSONKit v1.3 was trivial to implement. This allowed people who needed that functionality to use JSONKit while a proper solution to the problem was worked on. JSONKit v1.4 is the result of that work.
248-
249- JSONKit v1.4 no longer uses the Core Foundation collection classes [`CFArray`][CFArray] and [`CFDictionary`][CFDictionary]. Instead, JSONKit v1.4 contains a concrete subclass of [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary]&ndash; `JKArray` and `JKDictionary`, respectively. As a result, JSONKit has complete control over the behavior of how items are added and managed within an instantiated collection object. The `JKArray` and `JKDictionary` classes are private to JSONKit, you should not instantiate them direction. Since they are concrete subclasses of their respective collection class cluster, they behave and act exactly the same as [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary].
250-
251- The first benefit is that the "transfer of ownership" object ownership policy can now be safely used. Because the JSONKit collection objects understand that some methods, such as [`-mutableCopy`][-mutableCopy], should not inherit the same "transfer of ownership" object ownership policy, but must follow the standard Cocoa object ownership policy. The "transfer of ownership" object ownership policy reduces the number of [`-retain`][-retain] and [`-release`][-release] calls needed to add an object to a collection, and when creating a large number of objects very quickly (as you would expect when parsing JSON), this can result in a non-trivial amount of time. Eliminating these calls means faster JSON parsing.
252-
253- A second benefit is that the author encountered some unexpected behavior when using the [`CFDictionaryCreate`][CFDictionaryCreate] function to create a dictionary and the `keys` argument contained duplicate keys. This required JSONKit to de-duplicate the keys and values before calling [`CFDictionaryCreate`][CFDictionaryCreate]. Unfortunately, JSONKit always had to scan all the keys to make sure there were no duplicates, even though 99.99% of the time there were none. This was less than optimal, particularly because one of the solutions to this particular problem is to use a hash table to perform the de-duplication. Now JSONKit can do the de-duplication while it is instantiating the dictionary collection, solving two problems at once.
254-
255- Yet another benefit is that the recently instantiated object cache that JSONKit uses can be used to cache information about the keys used to create dictionary collections, in particular a keys [`-hash`][-hash] value. For a lot of real world JSON, this effectively means that the [`-hash`][-hash] for a key is calculated once, and that value is reused again and again when creating dictionaries. Because all the information required to create the hash table used by `JKDictionary` is already determined at the time the `JKDictionary` object is instantiated, populating the `JKDictionary` is now a very tight loop that only has to call [`-isEqual:`][-isEqual:] on the rare occasions that the JSON being parsed contains duplicate keys. Since the functions that handle this logic are all declared `static` and are internal to JSONKit, the compiler can heavily optimize this code.
256-
257- What does this mean in terms of performance? JSONKit was already fast, but now, it's even faster. Below is some benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json] in [samsoffes / json-benchmarks](https://github.com/samsoffes/json-benchmarks), where _read_ means to convert the JSON to native Objective-C objects, and _write_ means to convert the native Objective-C to JSON&mdash;
258-
259- <pre>
260- v1.3 read : min: 456.000 us, avg: 460.056 us, char/s: 53341332.36 / 50.870 MB/s
261- v1.3 write: min: 150.000 us, avg: 151.816 us, char/s: 161643041.58 / 154.155 MB/s</pre>
262-
263- <pre>
264- v1.4 read : min: 285.000 us, avg: 288.603 us, char/s: 85030301.14 / 81.091 MB/s
265- v1.4 write: min: 127.000 us, avg: 129.617 us, char/s: 189327017.29 / 180.556 MB/s</pre>
266-
267- JSONKit v1.4 is nearly 60% faster at reading and 17% faster at writing than v1.3.
268-
269- The following is the JSON test file taken from the project available at [this blog post](http://psionides.jogger.pl/2010/12/12/cocoa-json-parsing-libraries-part-2/). The keys and information contained in the JSON was anonymized with random characters. Since JSONKit relies on its recently instantiated object cache for a lot of its performance, this JSON happens to be "the worst corner case possible".
270-
271- <pre>
272- v1.3 read : min: 5222.000 us, avg: 5262.344 us, char/s: 15585260.10 / 14.863 MB/s
273- v1.3 write: min: 1253.000 us, avg: 1259.914 us, char/s: 65095712.88 / 62.080 MB/s</pre>
274-
275- <pre>
276- v1.4 read : min: 4096.000 us, avg: 4122.240 us, char/s: 19895736.30 / 18.974 MB/s
277- v1.4 write: min: 1319.000 us, avg: 1335.538 us, char/s: 61409709.05 / 58.565 MB/s</pre>
278-
279- JSONKit v1.4 is 28% faster at reading and 6% faster at writing that v1.3 in this worst-case torture test.
280-
281- While your milage may vary, you will likely see improvements in the 50% for reading and 10% for writing on your real world JSON. The nature of JSONKits cache means performance improvements is statistical in nature and depends on the particular properties of the JSON being parsed.
282-
283- For comparison, [json-framework][], a popular Objective-C JSON parsing library, turns in the following benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json]&mdash;
284-
285- <pre>
286- &#x200b; read : min: 1670.000 us, avg: 1682.461 us, char/s: 14585776.43 / 13.910 MB/s
287- &#x200b; write: min: 1021.000 us, avg: 1028.970 us, char/s: 23849091.81 / 22.744 MB/s</pre>
288-
289- Since the benchmark for JSONKit and [json-framework][] was done on the same computer, it's safe to compare the timing results. The version of [json-framework][] used was the latest v3.0 available via the master branch at the time of this writing on github.com.
290-
291- JSONKit v1.4 is 483% faster at reading and 694% faster at writing than [json-framework][].
292-
293-### Other Changes
294-
295-* Added a `__clang_analyzer__` pre-processor conditional around some code that the `clang` static analyzer was giving false positives for. However, `clang` versions &le; 1.5 do not define `__clang_analyzer__` and therefore will continue to emit analyzer warnings.
296-* The cache now uses a Galois Linear Feedback Shift Register PRNG to select which item in the cache to randomly age. This should age items in the cache more fairly.
297-* To promote better L1 cache locality, the cache age structure was rearranged slightly along with modifying when an item is randomly chosen to be aged.
298-* Removed a lot of internal and private data structures from `JSONKit.h` and put them in `JSONKit.m`.
299-* 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.
300-* The usual sundry of inconsequential tidies and what not, such as updating the `README.md`, etc.
301-* The catagory additions to the Cocoa classes were changed from `JSONKit` to `JSONKitDeserializing` and `JSONKitSerializing`, as appropriate.
302-
303-## Version 1.3 2011/05/02
304-
305-### New Features
306-
307-* Added the `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag.
308-
309- This is typically enabled by adding `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to the compilers command line arguments or in `Xcode.app` by adding `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to a projects / targets `Pre-Processor Macros` settings.
310-
311- The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` option enables the use of custom Core Foundation collection call backs which omit the [`CFRetain`][CFRetain] calls. This results in saving several [`CFRetain`][CFRetain] and [`CFRelease`][CFRelease] calls typically needed for every single object from the parsed JSON. While the author has used this technique for years without any issues, an unexpected interaction with the Foundation [`-mutableCopy`][-mutableCopy] method and Core Foundation Toll-Free Bridging resulting in a condition in which the objects contained in the collection to be over released. This problem does not occur with the use of [`-copy`][-copy] due to the fact that the objects created by JSONKit are immutable, and therefore [`-copy`][-copy] does not require creating a completely new object and copying the contents, instead [`-copy`][-copy] simply returns a [`-retain`][-retain]'d version of the immutable object which is significantly faster along with the obvious reduction in memory usage.
312-
313- Prior to version 1.3, JSONKit always used custom "Transfer of Ownership Collection Callbacks", and thus `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was effectively implicitly defined.
314-
315- Beginning with version 1.3, the default behavior of JSONKit is to use the standard Core Foundation collection callbacks ([`kCFTypeArrayCallBacks`][kCFTypeArrayCallBacks], [`kCFTypeDictionaryKeyCallBacks`][kCFTypeDictionaryKeyCallBacks], and [`kCFTypeDictionaryValueCallBacks`][kCFTypeDictionaryValueCallBacks]). The intention is to follow "the principle of least surprise", and the author believes the use of the standard Core Foundation collection callbacks as the default behavior for JSONKit results in the least surprise.
316-
317- **NOTE**: `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to `(CF|NS)` `Dictionary` and `Array` class objects.
318-
319- For the vast majority of users, the author believes JSONKits custom "Transfer of Ownership Collection Callbacks" will not cause any problems. As previously stated, the author has used this technique in performance critical code for years and has never had a problem. Until a user reported a problem with [`-mutableCopy`][-mutableCopy], the author was unaware that the use of the custom callbacks could even cause a problem. This is probably due to the fact that the vast majority of time the typical usage pattern tends to be "iterate the contents of the collection" and very rarely mutate the returned collection directly (although this last part is likely to vary significantly from programmer to programmer). The author tends to avoid the use of [`-mutableCopy`][-mutableCopy] as it results in a significant performance and memory consumption penalty. The reason for this is in "typical" Cocoa coding patterns, using [`-mutableCopy`][-mutableCopy] will instantiate an identical, albeit mutable, version of the original object. This requires both memory for the new object and time to iterate the contents of the original object and add them to the new object. Furthermore, under "typical" Cocoa coding patterns, the original collection object continues to consume memory until the autorelease pool is released. However, clearly there are cases where the use of [`-mutableCopy`][-mutableCopy] makes sense or may be used by an external library which is out of your direct control.
320-
321- The use of the standard Core Foundation collection callbacks results in a 9% to 23% reduction in parsing performance, with an "eye-balled average" of around 13% according to some benchmarking done by the author using Real World&trade; JSON (i.e., actual JSON from various web services, such as Twitter, etc) using `gcc-4.2 -arch x86_64 -O3 -DNS_BLOCK_ASSERTIONS` with the only change being the addition of `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`.
322-
323- `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to parsing / deserializing (i.e. converting from) of JSON. Serializing (i.e., converting to JSON) is completely unaffected by this change.
324-
325-### Bug Fixes
326-
327-* Fixed a [bug report regarding `-mutableCopy`](https://github.com/johnezang/JSONKit/issues#issue/3). This is related to the addition of the pre-processor define flag `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`.
328-
329-### Other Changes
330-
331-* Added `JK_EXPECTED` optimization hints around several conditionals.
332-* When serializing objects, JSONKit first starts with a small, on stack buffer. If the encoded JSON exceeds the size of the stack buffer, JSONKit switches to a heap allocated buffer. If JSONKit switched to a heap allocated buffer, [`CFDataCreateWithBytesNoCopy`][CFDataCreateWithBytesNoCopy] is used to create the [`NSData`][NSData] object, which in most cases causes the heap allocated buffer to "transfer" to the [`NSData`][NSData] object which is substantially faster than allocating a new buffer and copying the bytes.
333-* Added a pre-processor check in `JSONKit.m` to see if Objective-C Garbage Collection is enabled and issue a `#error` notice that JSONKit does not support Objective-C Garbage Collection.
334-* Various other minor or trivial modifications, such as updating `README.md`.
335-
336-### Other Issues
337-
338-* When using the `clang` static analyzer (the version used at the time of this writing was `Apple clang version 1.5 (tags/Apple/clang-60)`), the static analyzer reports a number of problems with `JSONKit.m`.
339-
340- The author has investigated these issues and determined that the problems reported by the current version of the static analyzer are "false positives". Not only that, the reported problems are not only "false positives", they are very clearly and obviously wrong. Therefore, the author has made the decision that no action will be taken on these non-problems, which includes not modifying the code for the sole purpose of silencing the static analyzer. The justification for this is "the dog wags the tail, not the other way around."
341-
342-## Version 1.2 2011/01/08
343-
344-### Bug Fixes
345-
346-* When JSONKit attempted to parse and decode JSON that contained `{"key": value}` dictionaries that contained the same key more than once would likely result in a crash. This was a serious bug.
347-* Under some conditions, JSONKit could potentially leak memory.
348-* There was an off by one error in the code that checked whether or not the parser was at the end of the `UTF8` buffer. This could result in JSONKit reading one by past the buffer bounds in some cases.
349-
350-### Other Changes
351-
352-* Some of the methods were missing `NULL` pointer checks for some of their arguments. This was fixed. In generally, when JSONKit encounters invalid arguments, it throws a `NSInvalidArgumentException` exception.
353-* Various other minor changes such as tightening up numeric literals with `UL` or `L` qualification, assertion check tweaks and additions, etc.
354-* The README.md file was updated with additional information.
355-
356-### Version 1.1
357-
358-No change log information was kept for versions prior to 1.2.
359-
360-[bugtracker]: https://github.com/johnezang/JSONKit/issues
361-[RFC 4627]: http://tools.ietf.org/html/rfc4627
362-[twitter_public_timeline.json]: https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json
363-[json-framework]: https://github.com/stig/json-framework
364-[Single Precision]: http://en.wikipedia.org/wiki/Single_precision
365-[kCFTypeArrayCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html#//apple_ref/c/data/kCFTypeArrayCallBacks
366-[kCFTypeDictionaryKeyCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryKeyCallBacks
367-[kCFTypeDictionaryValueCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryValueCallBacks
368-[CFRetain]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRetain
369-[CFRelease]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRelease
370-[CFDataCreateWithBytesNoCopy]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDataRef/Reference/reference.html#//apple_ref/c/func/CFDataCreateWithBytesNoCopy
371-[CFArray]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html
372-[CFDictionary]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html
373-[CFDictionaryCreate]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/func/CFDictionaryCreate
374-[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy
375-[-copy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/copy
376-[-retain]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retain
377-[-release]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/release
378-[-isEqual:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:
379-[-hash]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/hash
380-[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html
381-[NSMutableArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html
382-[-insertObject:atIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/insertObject:atIndex:
383-[-removeObjectAtIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/removeObjectAtIndex:
384-[-replaceObjectAtIndex:withObject:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/replaceObjectAtIndex:withObject:
385-[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html
386-[NSMutableDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/index.html
387-[-setObject:forKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/setObject:forKey:
388-[-removeObjectForKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/removeObjectForKey:
389-[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html
390-[NSFastEnumeration]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/Reference/NSFastEnumeration.html
391-[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html
392-[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html
393-[memmove]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/memmove.3.html
394
395=== removed file 'Dependencies/JSONKit/JSONKit.h'
396--- Dependencies/JSONKit/JSONKit.h 2011-07-10 22:17:52 +0000
397+++ Dependencies/JSONKit/JSONKit.h 1970-01-01 00:00:00 +0000
398@@ -1,251 +0,0 @@
399-//
400-// JSONKit.h
401-// http://github.com/johnezang/JSONKit
402-// Dual licensed under either the terms of the BSD License, or alternatively
403-// under the terms of the Apache License, Version 2.0, as specified below.
404-//
405-
406-/*
407- Copyright (c) 2011, John Engelhart
408-
409- All rights reserved.
410-
411- Redistribution and use in source and binary forms, with or without
412- modification, are permitted provided that the following conditions are met:
413-
414- * Redistributions of source code must retain the above copyright
415- notice, this list of conditions and the following disclaimer.
416-
417- * Redistributions in binary form must reproduce the above copyright
418- notice, this list of conditions and the following disclaimer in the
419- documentation and/or other materials provided with the distribution.
420-
421- * Neither the name of the Zang Industries nor the names of its
422- contributors may be used to endorse or promote products derived from
423- this software without specific prior written permission.
424-
425- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
426- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
427- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
428- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
429- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
430- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
431- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
432- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
433- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
434- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
435- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
436-*/
437-
438-/*
439- Copyright 2011 John Engelhart
440-
441- Licensed under the Apache License, Version 2.0 (the "License");
442- you may not use this file except in compliance with the License.
443- You may obtain a copy of the License at
444-
445- http://www.apache.org/licenses/LICENSE-2.0
446-
447- Unless required by applicable law or agreed to in writing, software
448- distributed under the License is distributed on an "AS IS" BASIS,
449- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
450- See the License for the specific language governing permissions and
451- limitations under the License.
452-*/
453-
454-#include <stddef.h>
455-#include <stdint.h>
456-#include <limits.h>
457-#include <TargetConditionals.h>
458-#include <AvailabilityMacros.h>
459-
460-#ifdef __OBJC__
461-#import <Foundation/NSArray.h>
462-#import <Foundation/NSData.h>
463-#import <Foundation/NSDictionary.h>
464-#import <Foundation/NSError.h>
465-#import <Foundation/NSObjCRuntime.h>
466-#import <Foundation/NSString.h>
467-#endif // __OBJC__
468-
469-#ifdef __cplusplus
470-extern "C" {
471-#endif
472-
473-
474-// For Mac OS X < 10.5.
475-#ifndef NSINTEGER_DEFINED
476-#define NSINTEGER_DEFINED
477-#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
478-typedef long NSInteger;
479-typedef unsigned long NSUInteger;
480-#define NSIntegerMin LONG_MIN
481-#define NSIntegerMax LONG_MAX
482-#define NSUIntegerMax ULONG_MAX
483-#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
484-typedef int NSInteger;
485-typedef unsigned int NSUInteger;
486-#define NSIntegerMin INT_MIN
487-#define NSIntegerMax INT_MAX
488-#define NSUIntegerMax UINT_MAX
489-#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
490-#endif // NSINTEGER_DEFINED
491-
492-
493-#ifndef _JSONKIT_H_
494-#define _JSONKIT_H_
495-
496-#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465)
497-#define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated))
498-#else
499-#define JK_DEPRECATED_ATTRIBUTE
500-#endif
501-
502-#define JSONKIT_VERSION_MAJOR 1
503-#define JSONKIT_VERSION_MINOR 4
504-
505-typedef NSUInteger JKFlags;
506-
507-/*
508- JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON.
509- JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines.
510- JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode.
511- This option allows JSON with malformed Unicode to be parsed without reporting an error.
512- Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER".
513- */
514-
515-enum {
516- JKParseOptionNone = 0,
517- JKParseOptionStrict = 0,
518- JKParseOptionComments = (1 << 0),
519- JKParseOptionUnicodeNewlines = (1 << 1),
520- JKParseOptionLooseUnicode = (1 << 2),
521- JKParseOptionPermitTextAfterValidJSON = (1 << 3),
522- JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON),
523-};
524-typedef JKFlags JKParseOptionFlags;
525-
526-enum {
527- JKSerializeOptionNone = 0,
528- JKSerializeOptionPretty = (1 << 0),
529- JKSerializeOptionEscapeUnicode = (1 << 1),
530- JKSerializeOptionEscapeForwardSlashes = (1 << 4),
531- JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes),
532-};
533-typedef JKFlags JKSerializeOptionFlags;
534-
535-#ifdef __OBJC__
536-
537-typedef struct JKParseState JKParseState; // Opaque internal, private type.
538-
539-// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict
540-
541-@interface JSONDecoder : NSObject {
542- JKParseState *parseState;
543-}
544-+ (id)decoder;
545-+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
546-- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
547-- (void)clearCache;
548-
549-// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods.
550-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
551-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
552-// The NSData MUST be UTF8 encoded JSON.
553-- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead.
554-- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
555-
556-// Methods that return immutable collection objects.
557-- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
558-- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
559-// The NSData MUST be UTF8 encoded JSON.
560-- (id)objectWithData:(NSData *)jsonData;
561-- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
562-
563-// Methods that return mutable collection objects.
564-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
565-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
566-// The NSData MUST be UTF8 encoded JSON.
567-- (id)mutableObjectWithData:(NSData *)jsonData;
568-- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
569-
570-@end
571-
572-////////////
573-#pragma mark Deserializing methods
574-////////////
575-
576-@interface NSString (JSONKitDeserializing)
577-- (id)objectFromJSONString;
578-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
579-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
580-- (id)mutableObjectFromJSONString;
581-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
582-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
583-@end
584-
585-@interface NSData (JSONKitDeserializing)
586-// The NSData MUST be UTF8 encoded JSON.
587-- (id)objectFromJSONData;
588-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
589-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
590-- (id)mutableObjectFromJSONData;
591-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
592-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
593-@end
594-
595-////////////
596-#pragma mark Serializing methods
597-////////////
598-
599-@interface NSString (JSONKitSerializing)
600-// 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).
601-// 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:
602-// includeQuotes:YES `a "test"...` -> `"a \"test\"..."`
603-// includeQuotes:NO `a "test"...` -> `a \"test\"...`
604-- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES
605-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
606-- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES
607-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
608-@end
609-
610-@interface NSArray (JSONKitSerializing)
611-- (NSData *)JSONData;
612-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
613-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
614-- (NSString *)JSONString;
615-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
616-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
617-@end
618-
619-@interface NSDictionary (JSONKitSerializing)
620-- (NSData *)JSONData;
621-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
622-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
623-- (NSString *)JSONString;
624-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
625-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
626-@end
627-
628-#ifdef __BLOCKS__
629-
630-@interface NSArray (JSONKitSerializingBlockAdditions)
631-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
632-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
633-@end
634-
635-@interface NSDictionary (JSONKitSerializingBlockAdditions)
636-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
637-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
638-@end
639-
640-#endif
641-
642-
643-#endif // __OBJC__
644-
645-#endif // _JSONKIT_H_
646-
647-#ifdef __cplusplus
648-} // extern "C"
649-#endif
650
651=== removed file 'Dependencies/JSONKit/JSONKit.m'
652--- Dependencies/JSONKit/JSONKit.m 2012-08-16 16:39:29 +0000
653+++ Dependencies/JSONKit/JSONKit.m 1970-01-01 00:00:00 +0000
654@@ -1,3022 +0,0 @@
655-//
656-// JSONKit.m
657-// http://github.com/johnezang/JSONKit
658-// Dual licensed under either the terms of the BSD License, or alternatively
659-// under the terms of the Apache License, Version 2.0, as specified below.
660-//
661-
662-/*
663- Copyright (c) 2011, John Engelhart
664-
665- All rights reserved.
666-
667- Redistribution and use in source and binary forms, with or without
668- modification, are permitted provided that the following conditions are met:
669-
670- * Redistributions of source code must retain the above copyright
671- notice, this list of conditions and the following disclaimer.
672-
673- * Redistributions in binary form must reproduce the above copyright
674- notice, this list of conditions and the following disclaimer in the
675- documentation and/or other materials provided with the distribution.
676-
677- * Neither the name of the Zang Industries nor the names of its
678- contributors may be used to endorse or promote products derived from
679- this software without specific prior written permission.
680-
681- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
682- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
683- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
684- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
685- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
686- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
687- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
688- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
689- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
690- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
691- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
692-*/
693-
694-/*
695- Copyright 2011 John Engelhart
696-
697- Licensed under the Apache License, Version 2.0 (the "License");
698- you may not use this file except in compliance with the License.
699- You may obtain a copy of the License at
700-
701- http://www.apache.org/licenses/LICENSE-2.0
702-
703- Unless required by applicable law or agreed to in writing, software
704- distributed under the License is distributed on an "AS IS" BASIS,
705- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
706- See the License for the specific language governing permissions and
707- limitations under the License.
708-*/
709-
710-
711-/*
712- Acknowledgments:
713-
714- The bulk of the UTF8 / UTF32 conversion and verification comes
715- from ConvertUTF.[hc]. It has been modified from the original sources.
716-
717- The original sources were obtained from http://www.unicode.org/.
718- However, the web site no longer seems to host the files. Instead,
719- the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4
720- points to International Components for Unicode (ICU)
721- http://site.icu-project.org/ as an example of how to write a UTF
722- converter.
723-
724- The decision to use the ConvertUTF.[ch] code was made to leverage
725- "proven" code. Hopefully the local modifications are bug free.
726-
727- The code in isValidCodePoint() is derived from the ICU code in
728- utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR.
729-
730- From the original ConvertUTF.[ch]:
731-
732- * Copyright 2001-2004 Unicode, Inc.
733- *
734- * Disclaimer
735- *
736- * This source code is provided as is by Unicode, Inc. No claims are
737- * made as to fitness for any particular purpose. No warranties of any
738- * kind are expressed or implied. The recipient agrees to determine
739- * applicability of information provided. If this file has been
740- * purchased on magnetic or optical media from Unicode, Inc., the
741- * sole remedy for any claim will be exchange of defective media
742- * within 90 days of receipt.
743- *
744- * Limitations on Rights to Redistribute This Code
745- *
746- * Unicode, Inc. hereby grants the right to freely use the information
747- * supplied in this file in the creation of products supporting the
748- * Unicode Standard, and to make copies of this file in any form
749- * for internal or external distribution as long as this notice
750- * remains attached.
751-
752-*/
753-
754-#include <stdio.h>
755-#include <stdlib.h>
756-#include <stdint.h>
757-#include <string.h>
758-#include <assert.h>
759-#include <sys/errno.h>
760-#include <math.h>
761-#include <limits.h>
762-#include <objc/runtime.h>
763-
764-#import "JSONKit.h"
765-
766-//#include <CoreFoundation/CoreFoundation.h>
767-#include <CoreFoundation/CFString.h>
768-#include <CoreFoundation/CFArray.h>
769-#include <CoreFoundation/CFDictionary.h>
770-#include <CoreFoundation/CFNumber.h>
771-
772-//#import <Foundation/Foundation.h>
773-#import <Foundation/NSArray.h>
774-#import <Foundation/NSAutoreleasePool.h>
775-#import <Foundation/NSData.h>
776-#import <Foundation/NSDictionary.h>
777-#import <Foundation/NSException.h>
778-#import <Foundation/NSNull.h>
779-#import <Foundation/NSObjCRuntime.h>
780-
781-#ifndef __has_feature
782-#define __has_feature(x) 0
783-#endif
784-
785-#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS
786-#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option.
787-#endif
788-
789-#ifdef __OBJC_GC__
790-#error JSONKit does not support Objective-C Garbage Collection
791-#endif
792-
793-#if __has_feature(objc_arc)
794-#error JSONKit does not support Objective-C Automatic Reference Counting (ARC)
795-#endif
796-
797-// The following checks are really nothing more than sanity checks.
798-// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety.
799-// 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.
800-// Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be.
801-
802-#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL))
803-#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively.
804-#endif
805-
806-#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT))
807-#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures.
808-#endif
809-
810-// Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t
811-
812-#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN)
813-#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type.
814-#endif
815-
816-#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX)
817-#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type.
818-#endif
819-
820-
821-// For DJB hash.
822-#define JK_HASH_INIT (1402737925UL)
823-
824-// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup.
825-#define JK_FAST_TRAILING_BYTES
826-
827-// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots.
828-#define JK_CACHE_SLOTS_BITS (10)
829-#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS)
830-// JK_CACHE_PROBES is the number of probe attempts.
831-#define JK_CACHE_PROBES (4UL)
832-// JK_INIT_CACHE_AGE must be (1 << AGE) - 1
833-#define JK_INIT_CACHE_AGE (0)
834-
835-// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes)
836-#define JK_TOKENBUFFER_SIZE (1024UL * 2UL)
837-
838-// JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary.
839-#define JK_STACK_OBJS (1024UL * 1UL)
840-
841-#define JK_JSONBUFFER_SIZE (1024UL * 4UL)
842-#define JK_UTF8BUFFER_SIZE (1024UL * 16UL)
843-
844-#define JK_ENCODE_CACHE_SLOTS (1024UL)
845-
846-
847-#if defined (__GNUC__) && (__GNUC__ >= 4)
848-#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__))
849-#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect))
850-#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U)
851-#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U)
852-#define JK_PREFETCH(ptr) __builtin_prefetch(ptr)
853-#else // defined (__GNUC__) && (__GNUC__ >= 4)
854-#define JK_ATTRIBUTES(attr, ...)
855-#define JK_EXPECTED(cond, expect) (cond)
856-#define JK_EXPECT_T(cond) (cond)
857-#define JK_EXPECT_F(cond) (cond)
858-#define JK_PREFETCH(ptr)
859-#endif // defined (__GNUC__) && (__GNUC__ >= 4)
860-
861-#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline)
862-#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg))
863-#define JK_UNUSED_ARG JK_ATTRIBUTES(unused)
864-#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result)
865-#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const)
866-#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure)
867-#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel)
868-#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__))
869-#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__))
870-#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__))
871-#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__))
872-
873-#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
874-#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as))
875-#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
876-#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__))
877-#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
878-
879-
880-@class JKArray, JKDictionaryEnumerator, JKDictionary;
881-
882-enum {
883- JSONNumberStateStart = 0,
884- JSONNumberStateFinished = 1,
885- JSONNumberStateError = 2,
886- JSONNumberStateWholeNumberStart = 3,
887- JSONNumberStateWholeNumberMinus = 4,
888- JSONNumberStateWholeNumberZero = 5,
889- JSONNumberStateWholeNumber = 6,
890- JSONNumberStatePeriod = 7,
891- JSONNumberStateFractionalNumberStart = 8,
892- JSONNumberStateFractionalNumber = 9,
893- JSONNumberStateExponentStart = 10,
894- JSONNumberStateExponentPlusMinus = 11,
895- JSONNumberStateExponent = 12,
896-};
897-
898-enum {
899- JSONStringStateStart = 0,
900- JSONStringStateParsing = 1,
901- JSONStringStateFinished = 2,
902- JSONStringStateError = 3,
903- JSONStringStateEscape = 4,
904- JSONStringStateEscapedUnicode1 = 5,
905- JSONStringStateEscapedUnicode2 = 6,
906- JSONStringStateEscapedUnicode3 = 7,
907- JSONStringStateEscapedUnicode4 = 8,
908- JSONStringStateEscapedUnicodeSurrogate1 = 9,
909- JSONStringStateEscapedUnicodeSurrogate2 = 10,
910- JSONStringStateEscapedUnicodeSurrogate3 = 11,
911- JSONStringStateEscapedUnicodeSurrogate4 = 12,
912- JSONStringStateEscapedNeedEscapeForSurrogate = 13,
913- JSONStringStateEscapedNeedEscapedUForSurrogate = 14,
914-};
915-
916-enum {
917- JKParseAcceptValue = (1 << 0),
918- JKParseAcceptComma = (1 << 1),
919- JKParseAcceptEnd = (1 << 2),
920- JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd),
921- JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd),
922-};
923-
924-enum {
925- JKClassUnknown = 0,
926- JKClassString = 1,
927- JKClassNumber = 2,
928- JKClassArray = 3,
929- JKClassDictionary = 4,
930- JKClassNull = 5,
931-};
932-
933-enum {
934- JKManagedBufferOnStack = 1,
935- JKManagedBufferOnHeap = 2,
936- JKManagedBufferLocationMask = (0x3),
937- JKManagedBufferLocationShift = (0),
938-
939- JKManagedBufferMustFree = (1 << 2),
940-};
941-typedef JKFlags JKManagedBufferFlags;
942-
943-enum {
944- JKObjectStackOnStack = 1,
945- JKObjectStackOnHeap = 2,
946- JKObjectStackLocationMask = (0x3),
947- JKObjectStackLocationShift = (0),
948-
949- JKObjectStackMustFree = (1 << 2),
950-};
951-typedef JKFlags JKObjectStackFlags;
952-
953-enum {
954- JKTokenTypeInvalid = 0,
955- JKTokenTypeNumber = 1,
956- JKTokenTypeString = 2,
957- JKTokenTypeObjectBegin = 3,
958- JKTokenTypeObjectEnd = 4,
959- JKTokenTypeArrayBegin = 5,
960- JKTokenTypeArrayEnd = 6,
961- JKTokenTypeSeparator = 7,
962- JKTokenTypeComma = 8,
963- JKTokenTypeTrue = 9,
964- JKTokenTypeFalse = 10,
965- JKTokenTypeNull = 11,
966- JKTokenTypeWhiteSpace = 12,
967-};
968-typedef NSUInteger JKTokenType;
969-
970-// These are prime numbers to assist with hash slot probing.
971-enum {
972- JKValueTypeNone = 0,
973- JKValueTypeString = 5,
974- JKValueTypeLongLong = 7,
975- JKValueTypeUnsignedLongLong = 11,
976- JKValueTypeDouble = 13,
977-};
978-typedef NSUInteger JKValueType;
979-
980-enum {
981- JKEncodeOptionAsData = 1,
982- JKEncodeOptionAsString = 2,
983- JKEncodeOptionAsTypeMask = 0x7,
984- JKEncodeOptionCollectionObj = (1 << 3),
985- JKEncodeOptionStringObj = (1 << 4),
986- JKEncodeOptionStringObjTrimQuotes = (1 << 5),
987-
988-};
989-typedef NSUInteger JKEncodeOptionType;
990-
991-typedef NSUInteger JKHash;
992-
993-typedef struct JKTokenCacheItem JKTokenCacheItem;
994-typedef struct JKTokenCache JKTokenCache;
995-typedef struct JKTokenValue JKTokenValue;
996-typedef struct JKParseToken JKParseToken;
997-typedef struct JKPtrRange JKPtrRange;
998-typedef struct JKObjectStack JKObjectStack;
999-typedef struct JKBuffer JKBuffer;
1000-typedef struct JKConstBuffer JKConstBuffer;
1001-typedef struct JKConstPtrRange JKConstPtrRange;
1002-typedef struct JKRange JKRange;
1003-typedef struct JKManagedBuffer JKManagedBuffer;
1004-typedef struct JKFastClassLookup JKFastClassLookup;
1005-typedef struct JKEncodeCache JKEncodeCache;
1006-typedef struct JKEncodeState JKEncodeState;
1007-typedef struct JKObjCImpCache JKObjCImpCache;
1008-typedef struct JKHashTableEntry JKHashTableEntry;
1009-
1010-typedef id (*NSNumberAllocImp)(id receiver, SEL selector);
1011-typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value);
1012-typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object);
1013-#ifdef __BLOCKS__
1014-typedef id (^JKClassFormatterBlock)(id formatObject);
1015-#endif
1016-
1017-
1018-struct JKPtrRange {
1019- unsigned char *ptr;
1020- size_t length;
1021-};
1022-
1023-struct JKConstPtrRange {
1024- const unsigned char *ptr;
1025- size_t length;
1026-};
1027-
1028-struct JKRange {
1029- size_t location, length;
1030-};
1031-
1032-struct JKManagedBuffer {
1033- JKPtrRange bytes;
1034- JKManagedBufferFlags flags;
1035- size_t roundSizeUpToMultipleOf;
1036-};
1037-
1038-struct JKObjectStack {
1039- void **objects, **keys;
1040- CFHashCode *cfHashes;
1041- size_t count, index, roundSizeUpToMultipleOf;
1042- JKObjectStackFlags flags;
1043-};
1044-
1045-struct JKBuffer {
1046- JKPtrRange bytes;
1047-};
1048-
1049-struct JKConstBuffer {
1050- JKConstPtrRange bytes;
1051-};
1052-
1053-struct JKTokenValue {
1054- JKConstPtrRange ptrRange;
1055- JKValueType type;
1056- JKHash hash;
1057- union {
1058- long long longLongValue;
1059- unsigned long long unsignedLongLongValue;
1060- double doubleValue;
1061- } number;
1062- JKTokenCacheItem *cacheItem;
1063-};
1064-
1065-struct JKParseToken {
1066- JKConstPtrRange tokenPtrRange;
1067- JKTokenType type;
1068- JKTokenValue value;
1069- JKManagedBuffer tokenBuffer;
1070-};
1071-
1072-struct JKTokenCacheItem {
1073- void *object;
1074- JKHash hash;
1075- CFHashCode cfHash;
1076- size_t size;
1077- unsigned char *bytes;
1078- JKValueType type;
1079-};
1080-
1081-struct JKTokenCache {
1082- JKTokenCacheItem *items;
1083- size_t count;
1084- unsigned int prng_lfsr;
1085- unsigned char age[JK_CACHE_SLOTS];
1086-};
1087-
1088-struct JKObjCImpCache {
1089- Class NSNumberClass;
1090- NSNumberAllocImp NSNumberAlloc;
1091- NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong;
1092-};
1093-
1094-struct JKParseState {
1095- JKParseOptionFlags parseOptionFlags;
1096- JKConstBuffer stringBuffer;
1097- size_t atIndex, lineNumber, lineStartIndex;
1098- size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex;
1099- JKParseToken token;
1100- JKObjectStack objectStack;
1101- JKTokenCache cache;
1102- JKObjCImpCache objCImpCache;
1103- NSError *error;
1104- int errorIsPrev;
1105- BOOL mutableCollections;
1106-};
1107-
1108-struct JKFastClassLookup {
1109- void *stringClass;
1110- void *numberClass;
1111- void *arrayClass;
1112- void *dictionaryClass;
1113- void *nullClass;
1114-};
1115-
1116-struct JKEncodeCache {
1117- id object;
1118- size_t offset;
1119- size_t length;
1120-};
1121-
1122-struct JKEncodeState {
1123- JKManagedBuffer utf8ConversionBuffer;
1124- JKManagedBuffer stringBuffer;
1125- size_t atIndex;
1126- JKFastClassLookup fastClassLookup;
1127- JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS];
1128- JKSerializeOptionFlags serializeOptionFlags;
1129- JKEncodeOptionType encodeOption;
1130- size_t depth;
1131- NSError *error;
1132- id classFormatterDelegate;
1133- SEL classFormatterSelector;
1134- JKClassFormatterIMP classFormatterIMP;
1135-#ifdef __BLOCKS__
1136- JKClassFormatterBlock classFormatterBlock;
1137-#endif
1138-};
1139-
1140-// This is a JSONKit private class.
1141-@interface JKSerializer : NSObject {
1142- JKEncodeState *encodeState;
1143-}
1144-
1145-#ifdef __BLOCKS__
1146-#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object)
1147-#else
1148-#define JKSERIALIZER_BLOCKS_PROTO id
1149-#endif
1150-
1151-+ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
1152-- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
1153-- (void)releaseState;
1154-
1155-@end
1156-
1157-struct JKHashTableEntry {
1158- NSUInteger keyHash;
1159- id key, object;
1160-};
1161-
1162-
1163-typedef uint32_t UTF32; /* at least 32 bits */
1164-typedef uint16_t UTF16; /* at least 16 bits */
1165-typedef uint8_t UTF8; /* typically 8 bits */
1166-
1167-typedef enum {
1168- conversionOK, /* conversion successful */
1169- sourceExhausted, /* partial character in source, but hit end */
1170- targetExhausted, /* insuff. room in target for conversion */
1171- sourceIllegal /* source sequence is illegal/malformed */
1172-} ConversionResult;
1173-
1174-#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
1175-#define UNI_MAX_BMP (UTF32)0x0000FFFF
1176-#define UNI_MAX_UTF16 (UTF32)0x0010FFFF
1177-#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
1178-#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
1179-#define UNI_SUR_HIGH_START (UTF32)0xD800
1180-#define UNI_SUR_HIGH_END (UTF32)0xDBFF
1181-#define UNI_SUR_LOW_START (UTF32)0xDC00
1182-#define UNI_SUR_LOW_END (UTF32)0xDFFF
1183-
1184-
1185-#if !defined(JK_FAST_TRAILING_BYTES)
1186-static const char trailingBytesForUTF8[256] = {
1187- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1188- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1189- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1190- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1191- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1192- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1193- 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1194- 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
1195-};
1196-#endif
1197-
1198-static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
1199-static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
1200-
1201-#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex]))
1202-#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length]))
1203-
1204-
1205-static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection);
1206-static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex);
1207-static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject);
1208-static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex);
1209-
1210-
1211-static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count);
1212-static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection);
1213-static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary);
1214-static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary);
1215-static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary);
1216-static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry);
1217-static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object);
1218-static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey);
1219-
1220-
1221-static void _JSONDecoderCleanup(JSONDecoder *decoder);
1222-
1223-static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection);
1224-
1225-
1226-static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer);
1227-static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length);
1228-static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize);
1229-static void jk_objectStack_release(JKObjectStack *objectStack);
1230-static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count);
1231-static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount);
1232-
1233-static void jk_error(JKParseState *parseState, NSString *format, ...);
1234-static int jk_parse_string(JKParseState *parseState);
1235-static int jk_parse_number(JKParseState *parseState);
1236-static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr);
1237-JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState);
1238-JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState);
1239-static int jk_parse_next_token(JKParseState *parseState);
1240-static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String);
1241-static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex);
1242-static void *jk_parse_dictionary(JKParseState *parseState);
1243-static void *jk_parse_array(JKParseState *parseState);
1244-static void *jk_object_for_token(JKParseState *parseState);
1245-static void *jk_cachedObjects(JKParseState *parseState);
1246-JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState);
1247-JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy);
1248-
1249-
1250-static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...);
1251-static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...);
1252-static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format);
1253-static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState);
1254-static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format);
1255-static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format);
1256-static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length);
1257-JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr);
1258-JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object);
1259-static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr);
1260-
1261-#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))
1262-
1263-
1264-JK_STATIC_INLINE size_t jk_min(size_t a, size_t b);
1265-JK_STATIC_INLINE size_t jk_max(size_t a, size_t b);
1266-JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c);
1267-
1268-// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type.
1269-// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the
1270-// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection
1271-// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable.
1272-// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4.
1273-
1274-
1275-// This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23
1276-// Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly.
1277-// 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.
1278-
1279-static Class _JKArrayClass = NULL;
1280-static size_t _JKArrayInstanceSize = 0UL;
1281-static Class _JKDictionaryClass = NULL;
1282-static size_t _JKDictionaryInstanceSize = 0UL;
1283-
1284-// For JSONDecoder...
1285-static Class _jk_NSNumberClass = NULL;
1286-static NSNumberAllocImp _jk_NSNumberAllocImp = NULL;
1287-static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL;
1288-
1289-extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor));
1290-
1291-void jk_collectionClassLoadTimeInitialization(void) {
1292- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal.
1293-
1294- _JKArrayClass = objc_getClass("JKArray");
1295- _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass));
1296-
1297- _JKDictionaryClass = objc_getClass("JKDictionary");
1298- _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass));
1299-
1300- // For JSONDecoder...
1301- _jk_NSNumberClass = [NSNumber class];
1302- _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)];
1303-
1304- // Hacktacular. Need to do it this way due to the nature of class clusters.
1305- id temp_NSNumber = [NSNumber alloc];
1306- _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)];
1307- [[temp_NSNumber init] release];
1308- temp_NSNumber = NULL;
1309-
1310- [pool release]; pool = NULL;
1311-}
1312-
1313-
1314-#pragma mark -
1315-@interface JKArray : NSMutableArray <NSCopying, NSMutableCopying, NSFastEnumeration> {
1316- id *objects;
1317- NSUInteger count, capacity, mutations;
1318-}
1319-@end
1320-
1321-@implementation JKArray
1322-
1323-+ (id)allocWithZone:(NSZone *)zone
1324-{
1325-#pragma unused(zone)
1326- [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])];
1327- return(NULL);
1328-}
1329-
1330-static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) {
1331- NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL));
1332- JKArray *array = NULL;
1333- if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc.
1334- array->isa = _JKArrayClass;
1335- if((array = [array init]) == NULL) { return(NULL); }
1336- array->capacity = count;
1337- array->count = count;
1338- if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); }
1339- memcpy(array->objects, objects, array->capacity * sizeof(id));
1340- array->mutations = (mutableCollection == NO) ? 0UL : 1UL;
1341- }
1342- return(array);
1343-}
1344-
1345-// Note: The caller is responsible for -retaining the object that is to be added.
1346-static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) {
1347- NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL));
1348- if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; }
1349- array->count++;
1350- if(array->count >= array->capacity) {
1351- array->capacity += 16UL;
1352- id *newObjects = NULL;
1353- if((newObjects = (id *)realloc(array->objects, sizeof(id) * array->capacity)) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; }
1354- array->objects = newObjects;
1355- memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count));
1356- }
1357- if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; }
1358- array->objects[objectIndex] = newObject;
1359-}
1360-
1361-// Note: The caller is responsible for -retaining the object that is to be added.
1362-static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) {
1363- NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL));
1364- if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; }
1365- CFRelease(array->objects[objectIndex]);
1366- array->objects[objectIndex] = NULL;
1367- array->objects[objectIndex] = newObject;
1368-}
1369-
1370-static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) {
1371- NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL));
1372- if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; }
1373- CFRelease(array->objects[objectIndex]);
1374- array->objects[objectIndex] = NULL;
1375- if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count] = NULL; }
1376- array->count--;
1377-}
1378-
1379-- (void)dealloc
1380-{
1381- if(JK_EXPECT_T(objects != NULL)) {
1382- NSUInteger atObject = 0UL;
1383- for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } }
1384- free(objects); objects = NULL;
1385- }
1386-
1387- [super dealloc];
1388-}
1389-
1390-- (NSUInteger)count
1391-{
1392- NSParameterAssert((objects != NULL) && (count <= capacity));
1393- return(count);
1394-}
1395-
1396-- (void)getObjects:(id *)objectsPtr range:(NSRange)range
1397-{
1398- NSParameterAssert((objects != NULL) && (count <= capacity));
1399- if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %u", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range)]; }
1400- if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%u) beyond bounds (%u)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; }
1401- memcpy(objectsPtr, objects + range.location, range.length * sizeof(id));
1402-}
1403-
1404-- (id)objectAtIndex:(NSUInteger)objectIndex
1405-{
1406- if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%u) beyond bounds (%u)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1407- NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL));
1408- return(objects[objectIndex]);
1409-}
1410-
1411-- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
1412-{
1413- NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity));
1414- if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
1415- if(JK_EXPECT_F(state->state >= count)) { return(0UL); }
1416-
1417- NSUInteger enumeratedCount = 0UL;
1418- while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; }
1419-
1420- return(enumeratedCount);
1421-}
1422-
1423-- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex
1424-{
1425- if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1426- if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1427- if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%u) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count + 1UL]; }
1428-#ifdef __clang_analyzer__
1429- [anObject retain]; // Stupid clang analyzer... Issue #19.
1430-#else
1431- anObject = [anObject retain];
1432-#endif
1433- _JKArrayInsertObjectAtIndex(self, anObject, objectIndex);
1434- mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1435-}
1436-
1437-- (void)removeObjectAtIndex:(NSUInteger)objectIndex
1438-{
1439- if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1440- if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%u) beyond bounds (%u)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1441- _JKArrayRemoveObjectAtIndex(self, objectIndex);
1442- mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1443-}
1444-
1445-- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject
1446-{
1447- if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1448- if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1449- if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%u) beyond bounds (%u)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1450-#ifdef __clang_analyzer__
1451- [anObject retain]; // Stupid clang analyzer... Issue #19.
1452-#else
1453- anObject = [anObject retain];
1454-#endif
1455- _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject);
1456- mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1457-}
1458-
1459-- (id)copyWithZone:(NSZone *)zone
1460-{
1461- NSParameterAssert((objects != NULL) && (count <= capacity));
1462- return((mutations == 0UL) ? [self retain] : [[NSArray allocWithZone:zone] initWithObjects:objects count:count]);
1463-}
1464-
1465-- (id)mutableCopyWithZone:(NSZone *)zone
1466-{
1467- NSParameterAssert((objects != NULL) && (count <= capacity));
1468- return([[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
1469-}
1470-
1471-@end
1472-
1473-
1474-#pragma mark -
1475-@interface JKDictionaryEnumerator : NSEnumerator {
1476- id collection;
1477- NSUInteger nextObject;
1478-}
1479-
1480-- (id)initWithJKDictionary:(JKDictionary *)initDictionary;
1481-- (NSArray *)allObjects;
1482-- (id)nextObject;
1483-
1484-@end
1485-
1486-@implementation JKDictionaryEnumerator
1487-
1488-- (id)initWithJKDictionary:(JKDictionary *)initDictionary
1489-{
1490- NSParameterAssert(initDictionary != NULL);
1491- if((self = [super init]) == NULL) { return(NULL); }
1492- if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); }
1493- return(self);
1494-}
1495-
1496-- (void)dealloc
1497-{
1498- if(collection != NULL) { CFRelease(collection); collection = NULL; }
1499- [super dealloc];
1500-}
1501-
1502-- (NSArray *)allObjects
1503-{
1504- NSParameterAssert(collection != NULL);
1505- NSUInteger count = [collection count], atObject = 0UL;
1506- id objects[count];
1507-
1508- while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; }
1509-
1510- return([NSArray arrayWithObjects:objects count:atObject]);
1511-}
1512-
1513-- (id)nextObject
1514-{
1515- NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL));
1516- JKHashTableEntry *entry = _JKDictionaryHashEntry(collection);
1517- NSUInteger capacity = _JKDictionaryCapacity(collection);
1518- id returnObject = NULL;
1519-
1520- if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } }
1521-
1522- return(returnObject);
1523-}
1524-
1525-@end
1526-
1527-#pragma mark -
1528-@interface JKDictionary : NSMutableDictionary <NSCopying, NSMutableCopying, NSFastEnumeration> {
1529- NSUInteger count, capacity, mutations;
1530- JKHashTableEntry *entry;
1531-}
1532-@end
1533-
1534-@implementation JKDictionary
1535-
1536-+ (id)allocWithZone:(NSZone *)zone
1537-{
1538-#pragma unused(zone)
1539- [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])];
1540- return(NULL);
1541-}
1542-
1543-// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too.
1544-static const NSUInteger jk_dictionaryCapacities[] = {
1545- 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL,
1546- 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL,
1547- 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL,
1548- 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL,
1549- 111638519UL, 180634607UL, 292272623UL, 472907251UL
1550-};
1551-
1552-static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) {
1553- NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33));
1554- while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } }
1555- return(jk_dictionaryCapacities[bottom]);
1556-}
1557-
1558-static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
1559- NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
1560-
1561- NSUInteger capacityForCount = 0UL;
1562- if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize
1563- NSUInteger oldCapacity = dictionary->capacity;
1564-#ifndef NS_BLOCK_ASSERTIONS
1565- NSUInteger oldCount = dictionary->count;
1566-#endif
1567- JKHashTableEntry *oldEntry = dictionary->entry;
1568- if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; }
1569- dictionary->capacity = capacityForCount;
1570- dictionary->count = 0UL;
1571-
1572- NSUInteger idx = 0UL;
1573- 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; } }
1574- NSCParameterAssert((oldCount == dictionary->count));
1575- free(oldEntry); oldEntry = NULL;
1576- }
1577-}
1578-
1579-static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) {
1580- NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL));
1581- JKDictionary *dictionary = NULL;
1582- if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc.
1583- dictionary->isa = _JKDictionaryClass;
1584- if((dictionary = [dictionary init]) == NULL) { return(NULL); }
1585- dictionary->capacity = _JKDictionaryCapacityForCount(count);
1586- dictionary->count = 0UL;
1587-
1588- if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); }
1589-
1590- NSUInteger idx = 0UL;
1591- for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); }
1592-
1593- dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL;
1594- }
1595- return(dictionary);
1596-}
1597-
1598-- (void)dealloc
1599-{
1600- if(JK_EXPECT_T(entry != NULL)) {
1601- NSUInteger atEntry = 0UL;
1602- for(atEntry = 0UL; atEntry < capacity; atEntry++) {
1603- if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; }
1604- if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; }
1605- }
1606-
1607- free(entry); entry = NULL;
1608- }
1609-
1610- [super dealloc];
1611-}
1612-
1613-static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) {
1614- NSCParameterAssert(dictionary != NULL);
1615- return(dictionary->entry);
1616-}
1617-
1618-static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) {
1619- NSCParameterAssert(dictionary != NULL);
1620- return(dictionary->capacity);
1621-}
1622-
1623-static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) {
1624- NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity));
1625- CFRelease(entry->key); entry->key = NULL;
1626- CFRelease(entry->object); entry->object = NULL;
1627- entry->keyHash = 0UL;
1628- dictionary->count--;
1629- // 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.
1630- NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL;
1631- NSCParameterAssert((removeIdx < dictionary->capacity));
1632- for(idx = 0UL; idx < dictionary->capacity; idx++) {
1633- NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity;
1634- JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
1635- if(atEntry->key == NULL) { break; }
1636- NSUInteger keyHash = atEntry->keyHash;
1637- id key = atEntry->key, object = atEntry->object;
1638- NSCParameterAssert(object != NULL);
1639- atEntry->keyHash = 0UL;
1640- atEntry->key = NULL;
1641- atEntry->object = NULL;
1642- NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL;
1643- for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) {
1644- JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)];
1645- if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; }
1646- }
1647- }
1648-}
1649-
1650-static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) {
1651- NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL));
1652- NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL;
1653- for(idx = 0UL; idx < dictionary->capacity; idx++) {
1654- NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity;
1655- JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
1656- 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); }
1657- 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; }
1658- }
1659-
1660- // We should never get here. If we do, we -release the key / object because it's our responsibility.
1661- CFRelease(key);
1662- CFRelease(object);
1663-}
1664-
1665-- (NSUInteger)count
1666-{
1667- return(count);
1668-}
1669-
1670-static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) {
1671- NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
1672- if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); }
1673- NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL;
1674- JKHashTableEntry *atEntry = NULL;
1675- for(idx = 0UL; idx < dictionary->capacity; idx++) {
1676- atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity];
1677- 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; }
1678- 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.
1679- }
1680- return(NULL);
1681-}
1682-
1683-- (id)objectForKey:(id)aKey
1684-{
1685- NSParameterAssert((entry != NULL) && (count <= capacity));
1686- JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey);
1687- return((entryForKey != NULL) ? entryForKey->object : NULL);
1688-}
1689-
1690-- (void)getObjects:(id *)objects andKeys:(id *)keys
1691-{
1692- NSParameterAssert((entry != NULL) && (count <= capacity));
1693- NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL;
1694- for(atEntry = 0UL; atEntry < capacity; atEntry++) {
1695- if(JK_EXPECT_T(entry[atEntry].key != NULL)) {
1696- NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count));
1697- if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; }
1698- if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; }
1699- arrayIdx++;
1700- }
1701- }
1702-}
1703-
1704-- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
1705-{
1706- NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity));
1707- if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
1708- if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); }
1709-
1710- NSUInteger enumeratedCount = 0UL;
1711- while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < capacity)) { if(JK_EXPECT_T(entry[state->state].key != NULL)) { stackbuf[enumeratedCount++] = entry[state->state].key; } state->state++; }
1712-
1713- return(enumeratedCount);
1714-}
1715-
1716-- (NSEnumerator *)keyEnumerator
1717-{
1718- return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]);
1719-}
1720-
1721-- (void)setObject:(id)anObject forKey:(id)aKey
1722-{
1723- if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1724- if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1725- if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; }
1726-
1727- _JKDictionaryResizeIfNeccessary(self);
1728-#ifndef __clang_analyzer__
1729- aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak",
1730- anObject = [anObject retain]; // but this -retain doesn't!?
1731-#endif // __clang_analyzer__
1732- _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject);
1733- mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1734-}
1735-
1736-- (void)removeObjectForKey:(id)aKey
1737-{
1738- if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1739- if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1740- JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey);
1741- if(entryForKey != NULL) {
1742- _JKDictionaryRemoveObjectWithEntry(self, entryForKey);
1743- mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1744- }
1745-}
1746-
1747-- (id)copyWithZone:(NSZone *)zone
1748-{
1749- NSParameterAssert((entry != NULL) && (count <= capacity));
1750- return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]);
1751-}
1752-
1753-- (id)mutableCopyWithZone:(NSZone *)zone
1754-{
1755- NSParameterAssert((entry != NULL) && (count <= capacity));
1756- return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]);
1757-}
1758-
1759-@end
1760-
1761-
1762-
1763-#pragma mark -
1764-
1765-JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); }
1766-JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); }
1767-
1768-JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); }
1769-
1770-static void jk_error(JKParseState *parseState, NSString *format, ...) {
1771- NSCParameterAssert((parseState != NULL) && (format != NULL));
1772-
1773- va_list varArgsList;
1774- va_start(varArgsList, format);
1775- NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
1776- va_end(varArgsList);
1777-
1778-#if 0
1779- const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex;
1780- const unsigned char *lineEnd = lineStart;
1781- const unsigned char *atCharacterPtr = NULL;
1782-
1783- for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } }
1784-
1785- NSString *lineString = @"", *carretString = @"";
1786- if(lineStart < JK_END_STRING_PTR(parseState)) {
1787- lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease];
1788- carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "];
1789- }
1790-#endif
1791-
1792- if(parseState->error == NULL) {
1793- parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
1794- [NSDictionary dictionaryWithObjectsAndKeys:
1795- formatString, NSLocalizedDescriptionKey,
1796- [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey",
1797- [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey",
1798- //lineString, @"JKErrorLine0Key",
1799- //carretString, @"JKErrorLine1Key",
1800- NULL]];
1801- }
1802-}
1803-
1804-#pragma mark -
1805-#pragma mark Buffer and Object Stack management functions
1806-
1807-static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) {
1808- if((managedBuffer->flags & JKManagedBufferMustFree)) {
1809- if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; }
1810- managedBuffer->flags &= ~JKManagedBufferMustFree;
1811- }
1812-
1813- managedBuffer->bytes.ptr = NULL;
1814- managedBuffer->bytes.length = 0UL;
1815- managedBuffer->flags &= ~JKManagedBufferLocationMask;
1816-}
1817-
1818-static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) {
1819- jk_managedBuffer_release(managedBuffer);
1820- managedBuffer->bytes.ptr = ptr;
1821- managedBuffer->bytes.length = length;
1822- managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack;
1823-}
1824-
1825-static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) {
1826- size_t roundedUpNewSize = newSize;
1827-
1828- if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); }
1829-
1830- if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) {
1831- if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) {
1832- NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0);
1833- unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr;
1834-
1835- if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); }
1836- memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize));
1837- managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree);
1838- managedBuffer->bytes.ptr = newBuffer;
1839- managedBuffer->bytes.length = roundedUpNewSize;
1840- } else {
1841- NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap));
1842- if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); }
1843- managedBuffer->bytes.length = roundedUpNewSize;
1844- }
1845- }
1846-
1847- return(managedBuffer->bytes.ptr);
1848-}
1849-
1850-
1851-
1852-static void jk_objectStack_release(JKObjectStack *objectStack) {
1853- NSCParameterAssert(objectStack != NULL);
1854-
1855- NSCParameterAssert(objectStack->index <= objectStack->count);
1856- size_t atIndex = 0UL;
1857- for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) {
1858- if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; }
1859- if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; }
1860- }
1861- objectStack->index = 0UL;
1862-
1863- if(objectStack->flags & JKObjectStackMustFree) {
1864- NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap);
1865- if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; }
1866- if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; }
1867- if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; }
1868- objectStack->flags &= ~JKObjectStackMustFree;
1869- }
1870-
1871- objectStack->objects = NULL;
1872- objectStack->keys = NULL;
1873- objectStack->cfHashes = NULL;
1874-
1875- objectStack->count = 0UL;
1876- objectStack->flags &= ~JKObjectStackLocationMask;
1877-}
1878-
1879-static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) {
1880- NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL));
1881- jk_objectStack_release(objectStack);
1882- objectStack->objects = objects;
1883- objectStack->keys = keys;
1884- objectStack->cfHashes = cfHashes;
1885- objectStack->count = count;
1886- objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack;
1887-#ifndef NS_BLOCK_ASSERTIONS
1888- size_t idx;
1889- for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
1890-#endif
1891-}
1892-
1893-static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) {
1894- size_t roundedUpNewCount = newCount;
1895- int returnCode = 0;
1896-
1897- void **newObjects = NULL, **newKeys = NULL;
1898- CFHashCode *newCFHashes = NULL;
1899-
1900- if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); }
1901-
1902- if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) {
1903- if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) {
1904- NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0);
1905-
1906- if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
1907- memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
1908- if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
1909- memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
1910-
1911- if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; }
1912- memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode));
1913-
1914- objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree);
1915- objectStack->objects = newObjects; newObjects = NULL;
1916- objectStack->keys = newKeys; newKeys = NULL;
1917- objectStack->cfHashes = newCFHashes; newCFHashes = NULL;
1918- objectStack->count = roundedUpNewCount;
1919- } else {
1920- NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap));
1921- if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; }
1922- if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; }
1923- if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; }
1924-
1925-#ifndef NS_BLOCK_ASSERTIONS
1926- size_t idx;
1927- for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
1928-#endif
1929- objectStack->count = roundedUpNewCount;
1930- }
1931- }
1932-
1933- errorExit:
1934- if(newObjects != NULL) { free(newObjects); newObjects = NULL; }
1935- if(newKeys != NULL) { free(newKeys); newKeys = NULL; }
1936- if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; }
1937-
1938- return(returnCode);
1939-}
1940-
1941-////////////
1942-#pragma mark -
1943-#pragma mark Unicode related functions
1944-
1945-JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) {
1946- ConversionResult result = conversionOK;
1947- UTF32 ch = *u32CodePoint;
1948-
1949- if(JK_EXPECT_F(ch >= UNI_SUR_HIGH_START) && (JK_EXPECT_T(ch <= UNI_SUR_LOW_END))) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; }
1950- if(JK_EXPECT_F(ch >= 0xFDD0U) && (JK_EXPECT_F(ch <= 0xFDEFU) || JK_EXPECT_F((ch & 0xFFFEU) == 0xFFFEU)) && JK_EXPECT_T(ch <= 0x10FFFFU)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; }
1951- if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; }
1952-
1953- finished:
1954- *u32CodePoint = ch;
1955- return(result);
1956-}
1957-
1958-
1959-static int isLegalUTF8(const UTF8 *source, size_t length) {
1960- const UTF8 *srcptr = source + length;
1961- UTF8 a;
1962-
1963- switch(length) {
1964- default: return(0); // Everything else falls through when "true"...
1965- case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
1966- case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
1967- case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); }
1968-
1969- switch(*source) { // no fall-through in this inner switch
1970- case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break;
1971- case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break;
1972- case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break;
1973- case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break;
1974- default: if(JK_EXPECT_F(a < 0x80)) { return(0); }
1975- }
1976-
1977- case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); }
1978- }
1979-
1980- if(JK_EXPECT_F(*source > 0xF4)) { return(0); }
1981-
1982- return(1);
1983-}
1984-
1985-static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) {
1986- ConversionResult result = conversionOK;
1987- const UTF8 *source = sourceStart;
1988- UTF32 ch = 0UL;
1989-
1990-#if !defined(JK_FAST_TRAILING_BYTES)
1991- unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
1992-#else
1993- unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25);
1994-#endif
1995-
1996- if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) {
1997- source++;
1998- while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; }
1999- NSCParameterAssert(source <= sourceEnd);
2000- result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal;
2001- ch = UNI_REPLACEMENT_CHAR;
2002- goto finished;
2003- }
2004-
2005- switch(extraBytesToRead) { // The cases all fall through.
2006- case 5: ch += *source++; ch <<= 6;
2007- case 4: ch += *source++; ch <<= 6;
2008- case 3: ch += *source++; ch <<= 6;
2009- case 2: ch += *source++; ch <<= 6;
2010- case 1: ch += *source++; ch <<= 6;
2011- case 0: ch += *source++;
2012- }
2013- ch -= offsetsFromUTF8[extraBytesToRead];
2014-
2015- result = isValidCodePoint(&ch);
2016-
2017- finished:
2018- *nextUTF8 = source;
2019- *convertedUTF32 = ch;
2020-
2021- return(result);
2022-}
2023-
2024-
2025-static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) {
2026- const UTF32 byteMask = 0xBF, byteMark = 0x80;
2027- ConversionResult result = conversionOK;
2028- UTF8 *target = *targetStart;
2029- UTF32 ch = u32CodePoint;
2030- unsigned short bytesToWrite = 0;
2031-
2032- result = isValidCodePoint(&ch);
2033-
2034- // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars.
2035- if(ch < (UTF32)0x80) { bytesToWrite = 1; }
2036- else if(ch < (UTF32)0x800) { bytesToWrite = 2; }
2037- else if(ch < (UTF32)0x10000) { bytesToWrite = 3; }
2038- else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; }
2039- else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; }
2040-
2041- target += bytesToWrite;
2042- if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; }
2043-
2044- switch (bytesToWrite) { // note: everything falls through.
2045- case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2046- case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2047- case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2048- case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
2049- }
2050-
2051- target += bytesToWrite;
2052-
2053- finished:
2054- *targetStart = target;
2055- return(result);
2056-}
2057-
2058-JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) {
2059- UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx];
2060- ConversionResult result;
2061-
2062- if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } }
2063- size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len;
2064-
2065- while(*tokenBufferIdx < nextIdx) { *stringHash = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); }
2066-
2067- return(0);
2068-}
2069-
2070-////////////
2071-#pragma mark -
2072-#pragma mark Decoding / parsing / deserializing functions
2073-
2074-static int jk_parse_string(JKParseState *parseState) {
2075- NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2076- const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1;
2077- const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
2078- const unsigned char *atStringCharacter = stringStart;
2079- unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr;
2080- size_t tokenStartIndex = parseState->atIndex;
2081- size_t tokenBufferIdx = 0UL;
2082-
2083- int onlySimpleString = 1, stringState = JSONStringStateStart;
2084- uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U;
2085- uint32_t escapedUnicodeCodePoint = 0U;
2086- JKHash stringHash = JK_HASH_INIT;
2087-
2088- while(1) {
2089- unsigned long currentChar;
2090-
2091- if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; }
2092-
2093- if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) {
2094- const unsigned char *nextValidCharacter = NULL;
2095- UTF32 u32ch = 0U;
2096- ConversionResult result;
2097-
2098- if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; }
2099- stringHash = calculateHash(stringHash, currentChar);
2100- while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = calculateHash(stringHash, *atStringCharacter++); }
2101- continue;
2102- } else {
2103- if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; }
2104-
2105- if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) {
2106- switchToSlowPath:
2107- onlySimpleString = 0;
2108- stringState = JSONStringStateParsing;
2109- tokenBufferIdx = (atStringCharacter - stringStart) - 1L;
2110- if(JK_EXPECT_F((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length)) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } }
2111- memcpy(tokenBuffer, stringStart, tokenBufferIdx);
2112- goto slowMatch;
2113- }
2114-
2115- if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; }
2116-
2117- stringHash = calculateHash(stringHash, currentChar);
2118- }
2119- }
2120-
2121- slowMatch:
2122-
2123- for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) {
2124- if((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } }
2125-
2126- NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length);
2127-
2128- unsigned long currentChar = (*atStringCharacter), escapedChar;
2129-
2130- if(JK_EXPECT_T(stringState == JSONStringStateParsing)) {
2131- if(JK_EXPECT_T(currentChar >= 0x20UL)) {
2132- if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence
2133- if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; }
2134- if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; }
2135- stringHash = calculateHash(stringHash, currentChar);
2136- tokenBuffer[tokenBufferIdx++] = currentChar;
2137- continue;
2138- } else { // UTF8 sequence
2139- const unsigned char *nextValidCharacter = NULL;
2140- UTF32 u32ch = 0U;
2141- ConversionResult result;
2142-
2143- if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) {
2144- if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
2145- if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
2146- if(jk_string_add_unicodeCodePoint(parseState, u32ch, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; }
2147- atStringCharacter = nextValidCharacter - 1;
2148- continue;
2149- } else {
2150- while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); }
2151- atStringCharacter--;
2152- continue;
2153- }
2154- }
2155- } else { // currentChar < 0x20
2156- jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing;
2157- }
2158-
2159- } else { // stringState != JSONStringStateParsing
2160- int isSurrogate = 1;
2161-
2162- switch(stringState) {
2163- case JSONStringStateEscape:
2164- switch(currentChar) {
2165- case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break;
2166-
2167- case 'b': escapedChar = '\b'; goto parsedEscapedChar;
2168- case 'f': escapedChar = '\f'; goto parsedEscapedChar;
2169- case 'n': escapedChar = '\n'; goto parsedEscapedChar;
2170- case 'r': escapedChar = '\r'; goto parsedEscapedChar;
2171- case 't': escapedChar = '\t'; goto parsedEscapedChar;
2172- case '\\': escapedChar = '\\'; goto parsedEscapedChar;
2173- case '/': escapedChar = '/'; goto parsedEscapedChar;
2174- case '"': escapedChar = '"'; goto parsedEscapedChar;
2175-
2176- parsedEscapedChar:
2177- stringState = JSONStringStateParsing;
2178- stringHash = calculateHash(stringHash, escapedChar);
2179- tokenBuffer[tokenBufferIdx++] = escapedChar;
2180- break;
2181-
2182- default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break;
2183- }
2184- break;
2185-
2186- case JSONStringStateEscapedUnicode1:
2187- case JSONStringStateEscapedUnicode2:
2188- case JSONStringStateEscapedUnicode3:
2189- case JSONStringStateEscapedUnicode4: isSurrogate = 0;
2190- case JSONStringStateEscapedUnicodeSurrogate1:
2191- case JSONStringStateEscapedUnicodeSurrogate2:
2192- case JSONStringStateEscapedUnicodeSurrogate3:
2193- case JSONStringStateEscapedUnicodeSurrogate4:
2194- {
2195- uint16_t hexValue = 0U;
2196-
2197- switch(currentChar) {
2198- case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex;
2199- case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex;
2200- case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex;
2201-
2202- parsedHex:
2203- if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; }
2204-
2205- if(stringState == JSONStringStateEscapedUnicode4) {
2206- if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) {
2207- if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; }
2208- else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) {
2209- if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
2210- else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2211- }
2212- }
2213- else { escapedUnicodeCodePoint = escapedUnicode1; }
2214- }
2215-
2216- if(stringState == JSONStringStateEscapedUnicodeSurrogate4) {
2217- if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) {
2218- if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
2219- else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2220- }
2221- else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; }
2222- }
2223-
2224- if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) {
2225- if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2226- stringState = JSONStringStateParsing;
2227- if(jk_string_add_unicodeCodePoint(parseState, escapedUnicodeCodePoint, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; }
2228- }
2229- else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; }
2230- break;
2231-
2232- default: jk_error(parseState, @"Unexpected character found in \\u Unicode escape sequence. Found '%c', expected [0-9a-fA-F].", currentChar); stringState = JSONStringStateError; goto finishedParsing; break;
2233- }
2234- }
2235- break;
2236-
2237- case JSONStringStateEscapedNeedEscapeForSurrogate:
2238- if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; }
2239- else {
2240- 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; }
2241- 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; } }
2242- }
2243- break;
2244-
2245- case JSONStringStateEscapedNeedEscapedUForSurrogate:
2246- if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; }
2247- else {
2248- 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; }
2249- else { stringState = JSONStringStateParsing; atStringCharacter -= 2; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } }
2250- }
2251- break;
2252-
2253- default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break;
2254- }
2255- }
2256- }
2257-
2258-finishedParsing:
2259-
2260- if(JK_EXPECT_T(stringState == JSONStringStateFinished)) {
2261- NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter);
2262-
2263- parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex;
2264- parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr);
2265-
2266- if(JK_EXPECT_T(onlySimpleString)) {
2267- NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer));
2268- parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1;
2269- parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL;
2270- } else {
2271- parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr;
2272- parseState->token.value.ptrRange.length = tokenBufferIdx;
2273- }
2274-
2275- parseState->token.value.hash = stringHash;
2276- parseState->token.value.type = JKValueTypeString;
2277- parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr);
2278- }
2279-
2280- if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); }
2281- return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1);
2282-}
2283-
2284-static int jk_parse_number(JKParseState *parseState) {
2285- NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2286- const unsigned char *numberStart = JK_AT_STRING_PTR(parseState);
2287- const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
2288- const unsigned char *atNumberCharacter = NULL;
2289- int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0;
2290- size_t startingIndex = parseState->atIndex;
2291-
2292- for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) {
2293- unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL;
2294-
2295- switch(numberState) {
2296- case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; }
2297- case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; }
2298- else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; }
2299- else { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
2300- case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; }
2301- case JSONNumberStateFractionalNumberStart:
2302- case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
2303- else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; }
2304- else { numberState = JSONNumberStateExponent; } break; }
2305- case JSONNumberStateWholeNumberZero:
2306- case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; }
2307- case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; }
2308- case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; }
2309- break;
2310- default: /* XXX Add error message */ numberState = JSONNumberStateError; break;
2311- }
2312- }
2313-
2314- parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex;
2315- parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup;
2316- parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr;
2317-
2318- if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) {
2319- unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL];
2320- unsigned char *endOfNumber = NULL;
2321-
2322- memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length);
2323- numberTempBuf[parseState->token.tokenPtrRange.length] = 0;
2324-
2325- errno = 0;
2326-
2327- // Treat "-0" as a floating point number, which is capable of representing negative zeros.
2328- if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; }
2329-
2330- if(isFloatingPoint) {
2331- 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).
2332- parseState->token.value.type = JKValueTypeDouble;
2333- parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue;
2334- parseState->token.value.ptrRange.length = sizeof(double);
2335- parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type);
2336- } else {
2337- if(isNegative) {
2338- parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10);
2339- parseState->token.value.type = JKValueTypeLongLong;
2340- parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue;
2341- parseState->token.value.ptrRange.length = sizeof(long long);
2342- parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue;
2343- } else {
2344- parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10);
2345- parseState->token.value.type = JKValueTypeUnsignedLongLong;
2346- parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue;
2347- parseState->token.value.ptrRange.length = sizeof(unsigned long long);
2348- parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue;
2349- }
2350- }
2351-
2352- if(JK_EXPECT_F(errno != 0)) {
2353- numberState = JSONNumberStateError;
2354- if(errno == ERANGE) {
2355- switch(parseState->token.value.type) {
2356- 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.
2357- case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break;
2358- case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break;
2359- default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2360- }
2361- }
2362- }
2363- 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."); }
2364-
2365- size_t hashIndex = 0UL;
2366- 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]); }
2367- }
2368-
2369- if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); }
2370- return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1);
2371-}
2372-
2373-JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) {
2374- parseState->token.tokenPtrRange.ptr = ptr;
2375- parseState->token.tokenPtrRange.length = length;
2376- parseState->token.type = type;
2377- parseState->atIndex += advanceBy;
2378-}
2379-
2380-static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) {
2381- NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState)));
2382- const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2383-
2384- if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); }
2385-
2386- if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); }
2387- if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); }
2388- if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) {
2389- if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); }
2390- if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); }
2391- }
2392-
2393- return(0UL);
2394-}
2395-
2396-JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) {
2397- size_t newlineAdvanceAtIndex = 0UL;
2398- if(JK_EXPECT_F((newlineAdvanceAtIndex = jk_parse_is_newline(parseState, JK_AT_STRING_PTR(parseState))) > 0UL)) { parseState->lineNumber++; parseState->atIndex += (newlineAdvanceAtIndex - 1UL); parseState->lineStartIndex = parseState->atIndex + 1UL; return(1); }
2399- return(0);
2400-}
2401-
2402-JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) {
2403-#ifndef __clang_analyzer__
2404- NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2405- const unsigned char *atCharacterPtr = NULL;
2406- const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2407-
2408- for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
2409- if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; }
2410- if(jk_parse_skip_newline(parseState)) { continue; }
2411- if(parseState->parseOptionFlags & JKParseOptionComments) {
2412- if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) {
2413- if((*(atCharacterPtr + 1)) == '/') {
2414- parseState->atIndex++;
2415- for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { break; } }
2416- continue;
2417- }
2418- if((*(atCharacterPtr + 1)) == '*') {
2419- parseState->atIndex++;
2420- for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
2421- if(jk_parse_skip_newline(parseState)) { continue; }
2422- if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; }
2423- }
2424- continue;
2425- }
2426- }
2427- }
2428- break;
2429- }
2430-#endif
2431-}
2432-
2433-static int jk_parse_next_token(JKParseState *parseState) {
2434- NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2435- const unsigned char *atCharacterPtr = NULL;
2436- const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2437- unsigned char currentCharacter = 0U;
2438- int stopParsing = 0;
2439-
2440- parseState->prev_atIndex = parseState->atIndex;
2441- parseState->prev_lineNumber = parseState->lineNumber;
2442- parseState->prev_lineStartIndex = parseState->lineStartIndex;
2443-
2444- jk_parse_skip_whitespace(parseState);
2445-
2446- if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; }
2447-
2448- if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) {
2449- currentCharacter = *atCharacterPtr;
2450-
2451- 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); } }
2452- else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); }
2453- else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); }
2454- 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); } }
2455- else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); }
2456- else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); }
2457- else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); }
2458- else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); }
2459-
2460- 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); } }
2461- 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); } }
2462- 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); } }
2463- else { stopParsing = 1; /* XXX Add error message */ }
2464- }
2465-
2466- if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); }
2467- return(stopParsing);
2468-}
2469-
2470-static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) {
2471- NSString *acceptStrings[16];
2472- int acceptIdx = 0;
2473- if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; }
2474- if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; }
2475- if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; }
2476- if(acceptIdx == 1) { jk_error(parseState, @"Expected %@, not '%*.*s'", acceptStrings[0], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); }
2477- else if(acceptIdx == 2) { jk_error(parseState, @"Expected %@ or %@, not '%*.*s'", acceptStrings[0], acceptStrings[1], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); }
2478- else if(acceptIdx == 3) { jk_error(parseState, @"Expected %@, %@, or %@, not '%*.*s", acceptStrings[0], acceptStrings[1], acceptStrings[2], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); }
2479-}
2480-
2481-static void *jk_parse_array(JKParseState *parseState) {
2482- size_t startingObjectIndex = parseState->objectStack.index;
2483- int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0;
2484- void *parsedArray = NULL;
2485-
2486- while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
2487- if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [array] objectsIndex > %zu, resize failed? %@ line %#ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } }
2488-
2489- if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) {
2490- void *object = NULL;
2491-#ifndef NS_BLOCK_ASSERTIONS
2492- parseState->objectStack.objects[parseState->objectStack.index] = NULL;
2493- parseState->objectStack.keys [parseState->objectStack.index] = NULL;
2494-#endif
2495- switch(parseState->token.type) {
2496- case JKTokenTypeNumber:
2497- case JKTokenTypeString:
2498- case JKTokenTypeTrue:
2499- case JKTokenTypeFalse:
2500- case JKTokenTypeNull:
2501- case JKTokenTypeArrayBegin:
2502- case JKTokenTypeObjectBegin:
2503- if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
2504- if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL"); stopParsing = 1; break; } else { parseState->objectStack.objects[parseState->objectStack.index++] = object; arrayState = JKParseAcceptCommaOrEnd; }
2505- break;
2506- case JKTokenTypeArrayEnd: if(JK_EXPECT_T(arrayState & JKParseAcceptEnd)) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedArray = (void *)_JKArrayCreate((id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ']'."); } stopParsing = 1; break;
2507- case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break;
2508- default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break;
2509- }
2510- }
2511- }
2512-
2513- if(JK_EXPECT_F(parsedArray == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } }
2514-#if !defined(NS_BLOCK_ASSERTIONS)
2515- else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
2516-#endif
2517-
2518- parseState->objectStack.index = startingObjectIndex;
2519- return(parsedArray);
2520-}
2521-
2522-static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) {
2523- void *parsedDictionary = NULL;
2524-
2525- parseState->objectStack.index--;
2526-
2527- parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections);
2528-
2529- return(parsedDictionary);
2530-}
2531-
2532-static void *jk_parse_dictionary(JKParseState *parseState) {
2533- size_t startingObjectIndex = parseState->objectStack.index;
2534- int dictState = JKParseAcceptValueOrEnd, stopParsing = 0;
2535- void *parsedDictionary = NULL;
2536-
2537- while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
2538- if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [dictionary] objectsIndex > %zu, resize failed? %@ line #%ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } }
2539-
2540- size_t objectStackIndex = parseState->objectStack.index++;
2541- parseState->objectStack.keys[objectStackIndex] = NULL;
2542- parseState->objectStack.objects[objectStackIndex] = NULL;
2543- void *key = NULL, *object = NULL;
2544-
2545- if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) {
2546- switch(parseState->token.type) {
2547- case JKTokenTypeString:
2548- if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; }
2549- if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; }
2550- else {
2551- parseState->objectStack.keys[objectStackIndex] = key;
2552- 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; }
2553- else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); }
2554- }
2555- break;
2556-
2557- case JKTokenTypeObjectEnd: if((JK_EXPECT_T(dictState & JKParseAcceptEnd))) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedDictionary = jk_create_dictionary(parseState, startingObjectIndex); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected '}'."); } stopParsing = 1; break;
2558- case JKTokenTypeComma: if((JK_EXPECT_T(dictState & JKParseAcceptComma))) { dictState = JKParseAcceptValue; parseState->objectStack.index--; continue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break;
2559-
2560- default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break;
2561- }
2562- }
2563-
2564- if(JK_EXPECT_T(stopParsing == 0)) {
2565- if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { if(JK_EXPECT_F(parseState->token.type != JKTokenTypeSeparator)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Expected ':'."); stopParsing = 1; } }
2566- }
2567-
2568- if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
2569- switch(parseState->token.type) {
2570- case JKTokenTypeNumber:
2571- case JKTokenTypeString:
2572- case JKTokenTypeTrue:
2573- case JKTokenTypeFalse:
2574- case JKTokenTypeNull:
2575- case JKTokenTypeArrayBegin:
2576- case JKTokenTypeObjectBegin:
2577- if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
2578- if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL."); stopParsing = 1; break; } else { parseState->objectStack.objects[objectStackIndex] = object; dictState = JKParseAcceptCommaOrEnd; }
2579- break;
2580- default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break;
2581- }
2582- }
2583- }
2584-
2585- if(JK_EXPECT_F(parsedDictionary == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.keys[idx] != NULL) { CFRelease(parseState->objectStack.keys[idx]); parseState->objectStack.keys[idx] = NULL; } if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } }
2586-#if !defined(NS_BLOCK_ASSERTIONS)
2587- else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
2588-#endif
2589-
2590- parseState->objectStack.index = startingObjectIndex;
2591- return(parsedDictionary);
2592-}
2593-
2594-static id json_parse_it(JKParseState *parseState) {
2595- id parsedObject = NULL;
2596- int stopParsing = 0;
2597-
2598- while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) {
2599- if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
2600- switch(parseState->token.type) {
2601- case JKTokenTypeArrayBegin:
2602- case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break;
2603- default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break;
2604- }
2605- }
2606- }
2607-
2608- NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2609-
2610- if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); }
2611- if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); }
2612-
2613- if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
2614- jk_parse_skip_whitespace(parseState);
2615- if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
2616- jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining.");
2617- parsedObject = NULL;
2618- }
2619- }
2620-
2621- return(parsedObject);
2622-}
2623-
2624-////////////
2625-#pragma mark -
2626-#pragma mark Object cache
2627-
2628-// 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.
2629-// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value.
2630-JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
2631- NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U));
2632- parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U);
2633- parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1;
2634-}
2635-
2636-// The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts.
2637-//
2638-// 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].
2639-//
2640-// 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.
2641-// 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).
2642-// The reason for this is it allows us to perform saturated adds and subtractions and is branchless.
2643-// The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits.
2644-//
2645-// A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0.
2646-//
2647-// When an item is found in the cache, it's age is incremented.
2648-// If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items.
2649-//
2650-// If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache.
2651-
2652-static void *jk_cachedObjects(JKParseState *parseState) {
2653- unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL;
2654- void *parsedAtom = NULL;
2655-
2656- if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); }
2657-
2658- for(x = 0UL; x < JK_CACHE_PROBES; x++) {
2659- if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; }
2660-
2661- 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))) {
2662- parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U;
2663- parseState->token.value.cacheItem = &parseState->cache.items[bucket];
2664- NSCParameterAssert(parseState->cache.items[bucket].object != NULL);
2665- return((void *)CFRetain(parseState->cache.items[bucket].object));
2666- } else {
2667- if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; }
2668- if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); }
2669- // This is the open addressing function. The values length and type are used as a form of "double hashing" to distribute values with the same effective value hash across different object cache buckets.
2670- // The values type is a prime number that is relatively coprime to the other primes in the set of value types and the number of hash table buckets.
2671- bucket = (parseState->token.value.hash + (parseState->token.value.ptrRange.length * (x + 1UL)) + (parseState->token.value.type * (x + 1UL)) + (3UL * (x + 1UL))) & (parseState->cache.count - 1UL);
2672- }
2673- }
2674-
2675- switch(parseState->token.value.type) {
2676- case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break;
2677- case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break;
2678- case JKValueTypeUnsignedLongLong:
2679- if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); }
2680- else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); }
2681- break;
2682- case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break;
2683- default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2684- }
2685-
2686- if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) {
2687- bucket = useableBucket;
2688- if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; }
2689-
2690- if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) {
2691- memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length);
2692- parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom);
2693- parseState->cache.items[bucket].hash = parseState->token.value.hash;
2694- parseState->cache.items[bucket].cfHash = 0UL;
2695- parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length;
2696- parseState->cache.items[bucket].type = parseState->token.value.type;
2697- parseState->token.value.cacheItem = &parseState->cache.items[bucket];
2698- parseState->cache.age[bucket] = JK_INIT_CACHE_AGE;
2699- } else { // The realloc failed, so clear the appropriate fields.
2700- parseState->cache.items[bucket].hash = 0UL;
2701- parseState->cache.items[bucket].cfHash = 0UL;
2702- parseState->cache.items[bucket].size = 0UL;
2703- parseState->cache.items[bucket].type = 0UL;
2704- }
2705- }
2706-
2707- return(parsedAtom);
2708-}
2709-
2710-
2711-static void *jk_object_for_token(JKParseState *parseState) {
2712- void *parsedAtom = NULL;
2713-
2714- parseState->token.value.cacheItem = NULL;
2715- switch(parseState->token.type) {
2716- case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break;
2717- case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break;
2718- case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break;
2719- case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break;
2720- case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break;
2721- case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break;
2722- case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break;
2723- default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2724- }
2725-
2726- return(parsedAtom);
2727-}
2728-
2729-#pragma mark -
2730-@implementation JSONDecoder
2731-
2732-+ (id)decoder
2733-{
2734- return([self decoderWithParseOptions:JKParseOptionStrict]);
2735-}
2736-
2737-+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags
2738-{
2739- return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]);
2740-}
2741-
2742-- (id)init
2743-{
2744- return([self initWithParseOptions:JKParseOptionStrict]);
2745-}
2746-
2747-- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags
2748-{
2749- if((self = [super init]) == NULL) { return(NULL); }
2750-
2751- if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; }
2752-
2753- if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; }
2754-
2755- parseState->parseOptionFlags = parseOptionFlags;
2756-
2757- parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL;
2758- parseState->objectStack.roundSizeUpToMultipleOf = 2048UL;
2759-
2760- parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass;
2761- parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp;
2762- parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp;
2763-
2764- parseState->cache.prng_lfsr = 1U;
2765- parseState->cache.count = JK_CACHE_SLOTS;
2766- if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; }
2767-
2768- return(self);
2769-
2770- errorExit:
2771- if(self) { [self autorelease]; self = NULL; }
2772- return(NULL);
2773-}
2774-
2775-// This is here primarily to support the NSString and NSData convenience functions so the autoreleased JSONDecoder can release most of its resources before the pool pops.
2776-static void _JSONDecoderCleanup(JSONDecoder *decoder) {
2777- if((decoder != NULL) && (decoder->parseState != NULL)) {
2778- jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer);
2779- jk_objectStack_release(&decoder->parseState->objectStack);
2780-
2781- [decoder clearCache];
2782- if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; }
2783-
2784- free(decoder->parseState); decoder->parseState = NULL;
2785- }
2786-}
2787-
2788-- (void)dealloc
2789-{
2790- _JSONDecoderCleanup(self);
2791- [super dealloc];
2792-}
2793-
2794-- (void)clearCache
2795-{
2796- if(JK_EXPECT_T(parseState != NULL)) {
2797- if(JK_EXPECT_T(parseState->cache.items != NULL)) {
2798- size_t idx = 0UL;
2799- for(idx = 0UL; idx < parseState->cache.count; idx++) {
2800- if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; }
2801- if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; }
2802- memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem));
2803- parseState->cache.age[idx] = 0U;
2804- }
2805- }
2806- }
2807-}
2808-
2809-// This needs to be completely rewritten.
2810-static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) {
2811- NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U));
2812- parseState->stringBuffer.bytes.ptr = string;
2813- parseState->stringBuffer.bytes.length = length;
2814- parseState->atIndex = 0UL;
2815- parseState->lineNumber = 1UL;
2816- parseState->lineStartIndex = 0UL;
2817- parseState->prev_atIndex = 0UL;
2818- parseState->prev_lineNumber = 1UL;
2819- parseState->prev_lineStartIndex = 0UL;
2820- parseState->error = NULL;
2821- parseState->errorIsPrev = 0;
2822- parseState->mutableCollections = (mutableCollections == NO) ? NO : YES;
2823-
2824- unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64);
2825- jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer));
2826-
2827- void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64);
2828- void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64);
2829- CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64);
2830- jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS);
2831-
2832- id parsedJSON = json_parse_it(parseState);
2833-
2834- if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; }
2835-
2836- jk_managedBuffer_release(&parseState->token.tokenBuffer);
2837- jk_objectStack_release(&parseState->objectStack);
2838-
2839- parseState->stringBuffer.bytes.ptr = NULL;
2840- parseState->stringBuffer.bytes.length = 0UL;
2841- parseState->atIndex = 0UL;
2842- parseState->lineNumber = 1UL;
2843- parseState->lineStartIndex = 0UL;
2844- parseState->prev_atIndex = 0UL;
2845- parseState->prev_lineNumber = 1UL;
2846- parseState->prev_lineStartIndex = 0UL;
2847- parseState->error = NULL;
2848- parseState->errorIsPrev = 0;
2849- parseState->mutableCollections = NO;
2850-
2851- return(parsedJSON);
2852-}
2853-
2854-////////////
2855-#pragma mark Deprecated as of v1.4
2856-////////////
2857-
2858-// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
2859-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length
2860-{
2861- return([self objectWithUTF8String:string length:length error:NULL]);
2862-}
2863-
2864-// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
2865-- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error
2866-{
2867- return([self objectWithUTF8String:string length:length error:error]);
2868-}
2869-
2870-// Deprecated in JSONKit v1.4. Use objectWithData: instead.
2871-- (id)parseJSONData:(NSData *)jsonData
2872-{
2873- return([self objectWithData:jsonData error:NULL]);
2874-}
2875-
2876-// Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
2877-- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error
2878-{
2879- return([self objectWithData:jsonData error:error]);
2880-}
2881-
2882-////////////
2883-#pragma mark Methods that return immutable collection objects
2884-////////////
2885-
2886-- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
2887-{
2888- return([self objectWithUTF8String:string length:length error:NULL]);
2889-}
2890-
2891-- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
2892-{
2893- if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
2894- if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
2895-
2896- return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error));
2897-}
2898-
2899-- (id)objectWithData:(NSData *)jsonData
2900-{
2901- return([self objectWithData:jsonData error:NULL]);
2902-}
2903-
2904-- (id)objectWithData:(NSData *)jsonData error:(NSError **)error
2905-{
2906- if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
2907- return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
2908-}
2909-
2910-////////////
2911-#pragma mark Methods that return mutable collection objects
2912-////////////
2913-
2914-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
2915-{
2916- return([self mutableObjectWithUTF8String:string length:length error:NULL]);
2917-}
2918-
2919-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
2920-{
2921- if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
2922- if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
2923-
2924- return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error));
2925-}
2926-
2927-- (id)mutableObjectWithData:(NSData *)jsonData
2928-{
2929- return([self mutableObjectWithData:jsonData error:NULL]);
2930-}
2931-
2932-- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error
2933-{
2934- if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
2935- return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
2936-}
2937-
2938-@end
2939-
2940-/*
2941- The NSString and NSData convenience methods need a little bit of explanation.
2942-
2943- Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like
2944-
2945- const unsigned char *utf8String = (const unsigned char *)[self UTF8String];
2946- if(utf8String == NULL) { return(NULL); }
2947- size_t utf8Length = strlen((const char *)utf8String);
2948- return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]);
2949-
2950- This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is
2951- allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed.
2952-
2953- In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead.
2954-
2955- Now we use an autoreleased CFMutableData that is sized to the UTF8 length of the NSString in question and is used to hold the UTF8
2956- conversion of said string.
2957-
2958- Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free
2959- the buffer.
2960-
2961- Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved
2962- to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls
2963- _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used
2964- again.
2965-
2966- If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the
2967- autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in
2968- autorelease limbo. It's more complicated for us, but a win for the user.
2969-
2970- Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our
2971- requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in
2972- autorelease limbo, but we've done our best to minimize that impact, so it all balances out.
2973- */
2974-
2975-@implementation NSString (JSONKitDeserializing)
2976-
2977-static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) {
2978- id returnObject = NULL;
2979- CFMutableDataRef mutableData = NULL;
2980- JSONDecoder *decoder = NULL;
2981-
2982- CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString);
2983- NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2984-
2985- if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) {
2986- UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData);
2987- CFIndex usedBytes = 0L, convertedCount = 0L;
2988-
2989- convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes);
2990- if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { if(error != NULL) { *error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:[NSDictionary dictionaryWithObject:@"An error occurred converting the contents of a NSString to UTF8." forKey:NSLocalizedDescriptionKey]]; } goto exitNow; }
2991-
2992- if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
2993- else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
2994- }
2995-
2996-exitNow:
2997- if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); }
2998- if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
2999- return(returnObject);
3000-}
3001-
3002-- (id)objectFromJSONString
3003-{
3004- return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
3005-}
3006-
3007-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3008-{
3009- return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
3010-}
3011-
3012-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3013-{
3014- return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO));
3015-}
3016-
3017-
3018-- (id)mutableObjectFromJSONString
3019-{
3020- return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
3021-}
3022-
3023-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3024-{
3025- return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
3026-}
3027-
3028-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3029-{
3030- return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES));
3031-}
3032-
3033-@end
3034-
3035-@implementation NSData (JSONKitDeserializing)
3036-
3037-- (id)objectFromJSONData
3038-{
3039- return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
3040-}
3041-
3042-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3043-{
3044- return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
3045-}
3046-
3047-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3048-{
3049- JSONDecoder *decoder = NULL;
3050- id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error];
3051- if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
3052- return(returnObject);
3053-}
3054-
3055-- (id)mutableObjectFromJSONData
3056-{
3057- return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
3058-}
3059-
3060-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3061-{
3062- return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
3063-}
3064-
3065-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3066-{
3067- JSONDecoder *decoder = NULL;
3068- id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error];
3069- if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
3070- return(returnObject);
3071-}
3072-
3073-
3074-@end
3075-
3076-////////////
3077-#pragma mark -
3078-#pragma mark Encoding / deserializing functions
3079-
3080-static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) {
3081- NSCParameterAssert((encodeState != NULL) && (format != NULL));
3082-
3083- va_list varArgsList;
3084- va_start(varArgsList, format);
3085- NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
3086- va_end(varArgsList);
3087-
3088- if(encodeState->error == NULL) {
3089- encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
3090- [NSDictionary dictionaryWithObjectsAndKeys:
3091- formatString, NSLocalizedDescriptionKey,
3092- NULL]];
3093- }
3094-}
3095-
3096-JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) {
3097- NSCParameterAssert(encodeState != NULL);
3098- if(JK_EXPECT_T(cacheSlot != NULL)) {
3099- NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex));
3100- cacheSlot->object = object;
3101- cacheSlot->offset = startingAtIndex;
3102- cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex);
3103- }
3104-}
3105-
3106-static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) {
3107- va_list varArgsList, varArgsListCopy;
3108- va_start(varArgsList, format);
3109- va_copy(varArgsListCopy, varArgsList);
3110-
3111- NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
3112-
3113- ssize_t formattedStringLength = 0L;
3114- int returnValue = 0;
3115-
3116- 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))) {
3117- NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length));
3118- 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; }
3119- 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; }
3120- }
3121-
3122-exitNow:
3123- va_end(varArgsList);
3124- va_end(varArgsListCopy);
3125- if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); }
3126- return(returnValue);
3127-}
3128-
3129-static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) {
3130- NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
3131- 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); }
3132-
3133- size_t formatIdx = 0UL;
3134- for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; }
3135- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
3136- return(0);
3137-}
3138-
3139-static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) {
3140- NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL));
3141- 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); }
3142- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n';
3143- size_t depthWhiteSpace = 0UL;
3144- for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
3145- return(0);
3146-}
3147-
3148-static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) {
3149- 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));
3150- 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); }
3151- encodeState->depth += depthChange;
3152- if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
3153- else {
3154- if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
3155- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0];
3156- if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
3157- }
3158- NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3159- return(0);
3160-}
3161-
3162-static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) {
3163- NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL));
3164- if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; }
3165- else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); }
3166- return(0);
3167-}
3168-
3169-static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) {
3170- NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex));
3171- 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); } }
3172- memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length);
3173- encodeState->atIndex += length;
3174- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
3175- return(0);
3176-}
3177-
3178-JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) {
3179- return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) );
3180-}
3181-
3182-static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) {
3183- NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL));
3184-
3185- id object = (id)objectPtr, encodeCacheObject = object;
3186- int isClass = JKClassUnknown;
3187- size_t startingAtIndex = encodeState->atIndex;
3188-
3189- JKHash objectHash = jk_encode_object_hash(objectPtr);
3190- JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS];
3191-
3192- if(JK_EXPECT_T(cacheSlot->object == object)) {
3193- NSCParameterAssert((cacheSlot->object != NULL) &&
3194- (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) &&
3195- (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) &&
3196- ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3197- ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3198- ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)));
3199- 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); }
3200- NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) &&
3201- ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3202- ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3203- ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3204- ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3205- ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex)));
3206- memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length);
3207- encodeState->atIndex += cacheSlot->length;
3208- return(0);
3209- }
3210-
3211- // 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,
3212- // 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
3213- // supported classes, we fail the second type (i.e., double fault error).
3214- BOOL rerunningAfterClassFormatter = NO;
3215-rerunAfterClassFormatter:
3216- if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; }
3217- else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; }
3218- else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; }
3219- else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; }
3220- else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; }
3221- else {
3222- if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { encodeState->fastClassLookup.stringClass = object_getClass(object); isClass = JKClassString; }
3223- else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { encodeState->fastClassLookup.numberClass = object_getClass(object); isClass = JKClassNumber; }
3224- else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { encodeState->fastClassLookup.dictionaryClass = object_getClass(object); isClass = JKClassDictionary; }
3225- else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { encodeState->fastClassLookup.arrayClass = object_getClass(object); isClass = JKClassArray; }
3226- else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { encodeState->fastClassLookup.nullClass = object_getClass(object); isClass = JKClassNull; }
3227- else {
3228- if((rerunningAfterClassFormatter == NO) && (
3229-#ifdef __BLOCKS__
3230- ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) ||
3231-#endif
3232- ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; }
3233-
3234- if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); }
3235- 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); }
3236- }
3237- }
3238-
3239- // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray
3240- // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro:
3241- // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f))
3242- int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1;
3243-
3244- switch(isClass) {
3245- case JKClassString:
3246- {
3247- {
3248- const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman);
3249- if(cStringPtr != NULL) {
3250- const unsigned char *utf8String = cStringPtr;
3251- size_t utf8Idx = 0UL;
3252-
3253- CFIndex stringLength = CFStringGetLength((CFStringRef)object);
3254- 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); }
3255-
3256- if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3257- for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) {
3258- NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
3259- NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3260- if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; }
3261- if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
3262- switch(utf8String[utf8Idx]) {
3263- case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
3264- case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
3265- case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
3266- case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
3267- case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
3268- default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
3269- }
3270- } else {
3271- 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++] = '\\'; }
3272- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
3273- }
3274- }
3275- NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
3276- if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3277- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
3278- return(0);
3279- }
3280- }
3281-
3282- slowUTF8Path:
3283- {
3284- CFIndex stringLength = CFStringGetLength((CFStringRef)object);
3285- CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L;
3286-
3287- 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); }
3288-
3289- CFIndex usedBytes = 0L, convertedCount = 0L;
3290- convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes);
3291- if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { jk_encode_error(encodeState, @"An error occurred converting the contents of a NSString to UTF8."); return(1); }
3292-
3293- if(JK_EXPECT_F((encodeState->atIndex + (maxStringUTF8Length * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (maxStringUTF8Length * 2UL) + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); }
3294-
3295- const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr;
3296-
3297- size_t utf8Idx = 0UL;
3298- if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3299- for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) {
3300- NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
3301- NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3302- NSCParameterAssert((CFIndex)utf8Idx < usedBytes);
3303- if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
3304- switch(utf8String[utf8Idx]) {
3305- case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
3306- case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
3307- case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
3308- case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
3309- case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
3310- default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
3311- }
3312- } else {
3313- if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) {
3314- const unsigned char *nextValidCharacter = NULL;
3315- UTF32 u32ch = 0U;
3316- ConversionResult result;
3317-
3318- if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); }
3319- else {
3320- utf8Idx = (nextValidCharacter - utf8String) - 1UL;
3321- if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } }
3322- 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); } }
3323- }
3324- } else {
3325- 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++] = '\\'; }
3326- encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
3327- }
3328- }
3329- }
3330- NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
3331- if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3332- jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
3333- return(0);
3334- }
3335- }
3336- break;
3337-
3338- case JKClassNumber:
3339- {
3340- if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); }
3341- else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); }
3342-
3343- const char *objCType = [object objCType];
3344- char anum[256], *aptr = &anum[255];
3345- int isNegative = 0;
3346- unsigned long long ullv;
3347- long long llv;
3348-
3349- 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) ? "<NULL>" : objCType); return(1); }
3350-
3351- switch(objCType[0]) {
3352- case 'c': case 'i': case 's': case 'l': case 'q':
3353- if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) {
3354- if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; }
3355- goto convertNumber;
3356- } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
3357- break;
3358- case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B':
3359- if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) {
3360- convertNumber:
3361- 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); } }
3362- if(isNegative) { *--aptr = '-'; }
3363- NSCParameterAssert(aptr > anum);
3364- return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr));
3365- } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
3366- break;
3367- case 'f': case 'd':
3368- {
3369- double dv;
3370- if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) {
3371- 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); }
3372- return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv));
3373- } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); }
3374- }
3375- break;
3376- default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break;
3377- }
3378- }
3379- break;
3380-
3381- case JKClassArray:
3382- {
3383- int printComma = 0;
3384- CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L;
3385- if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); }
3386- if(JK_EXPECT_F(arrayCount > 1020L)) {
3387- 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); } }
3388- } else {
3389- void *objects[1024];
3390- CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects);
3391- 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); } }
3392- }
3393- return(jk_encode_write1(encodeState, -1L, "]"));
3394- }
3395- break;
3396-
3397- case JKClassDictionary:
3398- {
3399- int printComma = 0;
3400- CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L;
3401- id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object;
3402-
3403- if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); }
3404- if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) {
3405- for(id keyObject in enumerateObject) {
3406- if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
3407- printComma = 1;
3408- if(JK_EXPECT_F((object_getClass(keyObject) != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); }
3409- if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); }
3410- if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
3411- if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); }
3412- }
3413- } else {
3414- void *keys[1024], *objects[1024];
3415- CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects);
3416- for(idx = 0L; idx < dictionaryCount; idx++) {
3417- if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
3418- printComma = 1;
3419- if(JK_EXPECT_F((object_getClass((id)keys[idx])) != 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); }
3420- if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); }
3421- if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
3422- if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); }
3423- }
3424- }
3425- return(jk_encode_write1(encodeState, -1L, "}"));
3426- }
3427- break;
3428-
3429- case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break;
3430-
3431- default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break;
3432- }
3433-
3434- return(0);
3435-}
3436-
3437-
3438-@implementation JKSerializer
3439-
3440-+ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3441-{
3442- return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]);
3443-}
3444-
3445-- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3446-{
3447-#ifndef __BLOCKS__
3448-#pragma unused(block)
3449-#endif
3450- NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) &&
3451- (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) &&
3452- (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1));
3453-
3454- id returnObject = NULL;
3455-
3456- if(encodeState != NULL) { [self releaseState]; }
3457- if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); }
3458-
3459- if((error != NULL) && (*error != NULL)) { *error = NULL; }
3460-
3461- if(delegate != NULL) {
3462- if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; }
3463- if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; }
3464- encodeState->classFormatterDelegate = delegate;
3465- encodeState->classFormatterSelector = selector;
3466- encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector];
3467- NSCParameterAssert(encodeState->classFormatterIMP != NULL);
3468- }
3469-
3470-#ifdef __BLOCKS__
3471- encodeState->classFormatterBlock = block;
3472-#endif
3473- encodeState->serializeOptionFlags = optionFlags;
3474- encodeState->encodeOption = encodeOption;
3475- encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL);
3476- encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL;
3477-
3478- unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64);
3479- jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer));
3480-
3481- unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64);
3482- jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer));
3483-
3484- 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; }
3485- 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; }
3486-
3487- if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) {
3488- BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO;
3489-
3490- if((encodeState->atIndex < 2UL))
3491- 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; }
3492-
3493- switch((encodeOption & JKEncodeOptionAsTypeMask)) {
3494- case JKEncodeOptionAsData:
3495- 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"); } }
3496- 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"); } }
3497- break;
3498-
3499- case JKEncodeOptionAsString:
3500- 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"); } }
3501- 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"); } }
3502- break;
3503-
3504- default: jk_encode_error(encodeState, @"Unknown encode as type."); break;
3505- }
3506-
3507- if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; }
3508- }
3509-
3510-errorExit:
3511- if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; }
3512- [self releaseState];
3513-
3514- return(returnObject);
3515-}
3516-
3517-- (void)releaseState
3518-{
3519- if(encodeState != NULL) {
3520- jk_managedBuffer_release(&encodeState->stringBuffer);
3521- jk_managedBuffer_release(&encodeState->utf8ConversionBuffer);
3522- free(encodeState); encodeState = NULL;
3523- }
3524-}
3525-
3526-- (void)dealloc
3527-{
3528- [self releaseState];
3529- [super dealloc];
3530-}
3531-
3532-@end
3533-
3534-@implementation NSString (JSONKitSerializing)
3535-
3536-////////////
3537-#pragma mark Methods for serializing a single NSString.
3538-////////////
3539-
3540-// 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.
3541-
3542-// NSData returning methods...
3543-
3544-- (NSData *)JSONData
3545-{
3546- return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
3547-}
3548-
3549-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
3550-{
3551- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]);
3552-}
3553-
3554-// NSString returning methods...
3555-
3556-- (NSString *)JSONString
3557-{
3558- return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
3559-}
3560-
3561-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
3562-{
3563- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]);
3564-}
3565-
3566-@end
3567-
3568-@implementation NSArray (JSONKitSerializing)
3569-
3570-// NSData returning methods...
3571-
3572-- (NSData *)JSONData
3573-{
3574- return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3575-}
3576-
3577-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3578-{
3579- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3580-}
3581-
3582-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3583-{
3584- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3585-}
3586-
3587-// NSString returning methods...
3588-
3589-- (NSString *)JSONString
3590-{
3591- return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3592-}
3593-
3594-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3595-{
3596- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3597-}
3598-
3599-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3600-{
3601- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3602-}
3603-
3604-@end
3605-
3606-@implementation NSDictionary (JSONKitSerializing)
3607-
3608-// NSData returning methods...
3609-
3610-- (NSData *)JSONData
3611-{
3612- return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3613-}
3614-
3615-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3616-{
3617- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3618-}
3619-
3620-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3621-{
3622- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3623-}
3624-
3625-// NSString returning methods...
3626-
3627-- (NSString *)JSONString
3628-{
3629- return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3630-}
3631-
3632-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3633-{
3634- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3635-}
3636-
3637-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3638-{
3639- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3640-}
3641-
3642-@end
3643-
3644-
3645-#ifdef __BLOCKS__
3646-
3647-@implementation NSArray (JSONKitSerializingBlockAdditions)
3648-
3649-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3650-{
3651- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3652-}
3653-
3654-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3655-{
3656- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3657-}
3658-
3659-@end
3660-
3661-@implementation NSDictionary (JSONKitSerializingBlockAdditions)
3662-
3663-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3664-{
3665- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3666-}
3667-
3668-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3669-{
3670- return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3671-}
3672-
3673-@end
3674-
3675-#endif // __BLOCKS__
3676-
3677
3678=== removed file 'Dependencies/JSONKit/README.md'
3679--- Dependencies/JSONKit/README.md 2011-07-10 22:17:52 +0000
3680+++ Dependencies/JSONKit/README.md 1970-01-01 00:00:00 +0000
3681@@ -1,307 +0,0 @@
3682-# JSONKit
3683-
3684-JSONKit is dual licensed under either the terms of the BSD License, or alternatively under the terms of the Apache License, Version 2.0.<br />
3685-Copyright &copy; 2011, John Engelhart.
3686-
3687-### A Very High Performance Objective-C JSON Library
3688-
3689- Parsing | Serializing
3690-:---------:|:-------------:
3691-<img src="http://chart.googleapis.com/chart?chf=a,s,000000%7Cb0,lg,0,6589C760,0,6589C7B4,1%7Cbg,lg,90,EFEFEF,0,F8F8F8,1&chxl=0:%7CTouchJSON%7CXML+.plist%7Cjson-framework%7CYAJL-ObjC%7Cgzip+JSONKit%7CBinary+.plist%7CJSONKit%7C2:%7CTime+to+Deserialize+in+%C2%B5sec&chxp=2,40&chxr=0,0,5%7C1,0,3250&chxs=0,676767,11.5,1,lt,676767&chxt=y,x,x&chbh=a,5,4&chs=350x185&cht=bhs&chco=6589C783&chds=0,3250&chd=t:410.517,510.262,539.614,1351.257,1683.346,1747.953,2955.881&chg=-1,0,1,3&chm=N+*s*+%C2%B5s,676767,0,0:5,10.5%7CN+*s*+%C2%B5s,3d3d3d,0,6,10.5,,r:-5:1&chem=y;s=text_outline;d=666,10.5,l,fff,_,Decompress+%2b+Parse+is+just;ds=0;dp=2;py=0;of=58,7%7Cy;s=text_outline;d=666,10.5,l,fff,_,5.6%25+slower+than+Binary+.plist%21;ds=0;dp=2;py=0;of=53,-5" width="350" height="185" alt="Deserialize from JSON" /> | <img src="http://chart.googleapis.com/chart?chf=a,s,000000%7Cb0,lg,0,699E7260,0,699E72B4,1%7Cbg,lg,90,EFEFEF,0,F8F8F8,1&chxl=0:%7CTouchJSON%7CYAJL-ObjC%7CXML+.plist%7Cjson-framework%7CBinary+.plist%7Cgzip+JSONKit%7CJSONKit%7C2:%7CTime+to+Serialize+in+%C2%B5sec&chxp=2,40&chxr=0,0,5%7C1,0,3250&chxs=0,676767,11.5,1,lt,676767&chxt=y,x,x&chbh=a,5,4&chs=350x175&cht=bhs&chco=699E7284&chds=0,3250&chd=t:96.387,466.947,626.153,1028.432,1945.511,2156.978,3051.976&chg=-1,0,1,3&chm=N+*s*+%C2%B5s,676767,0,0:5,10.5%7CN+*s*+%C2%B5s,4d4d4d,0,6,10.5,,r:-5:1&chem=y;s=text_outline;d=666,10.5,l,fff,_,Serialize+%2b+Compress+is+34%25;ds=0;dp=1;py=0;of=51,7%7Cy;s=text_outline;d=666,10.5,l,fff,_,faster+than+Binary+.plist%21;ds=0;dp=1;py=0;of=62,-5" width="350" height="185" alt="Serialize to JSON" />
3692-*23% Faster than Binary* <code><em>.plist</em></code>*&thinsp;!* | *549% Faster than Binary* <code><em>.plist</em></code>*&thinsp;!*
3693-
3694-* Benchmarking was performed on a MacBook Pro with a 2.66GHz Core 2.
3695-* All JSON libraries were compiled with `gcc-4.2 -DNS_BLOCK_ASSERTIONS -O3 -arch x86_64`.
3696-* Timing results are the average of 1,000 iterations of the user + system time reported by [`getrusage`][getrusage].
3697-* The JSON used was [`twitter_public_timeline.json`](https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json) from [samsoffes / json-benchmarks](https://github.com/samsoffes/json-benchmarks).
3698-* Since the `.plist` format does not support serializing [`NSNull`][NSNull], the `null` values in the original JSON were changed to `"null"`.
3699-* The [experimental](https://github.com/johnezang/JSONKit/tree/experimental) branch contains the `gzip` compression changes.
3700- * JSONKit automagically links to `libz.dylib` on the fly at run time&ndash; no manual linking required.
3701- * Parsing / deserializing will automagically decompress a buffer if it detects a `gzip` signature header.
3702- * You can compress / `gzip` the serialized JSON by passing `JKSerializeOptionCompress` to `-JSONDataWithOptions:error:`.
3703-
3704-[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.
3705-
3706-***
3707-
3708-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][].
3709-
3710-JSON provides the following primitive types:
3711-
3712-* `null`
3713-* Boolean `true` and `false`
3714-* Number
3715-* String
3716-* Array
3717-* Object (a.k.a. Associative Arrays, Key / Value Hash Tables, Maps, Dictionaries, etc.)
3718-
3719-These primitive types are mapped to the following Objective-C Foundation classes:
3720-
3721-JSON | Objective-C
3722--------------------|-------------
3723-`null` | [`NSNull`][NSNull]
3724-`true` and `false` | [`NSNumber`][NSNumber]
3725-Number | [`NSNumber`][NSNumber]
3726-String | [`NSString`][NSString]
3727-Array | [`NSArray`][NSArray]
3728-Object | [`NSDictionary`][NSDictionary]
3729-
3730-JSONKit uses Core Foundation internally, and it is assumed that Core Foundation &equiv; Foundation for every equivalent base type, i.e. [`CFString`][CFString] &equiv; [`NSString`][NSString].
3731-
3732-The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119][].
3733-
3734-### JSON To Objective-C Primitive Mapping Details
3735-
3736-* The [JSON specification][RFC 4627] is somewhat ambiguous about the details and requirements when it comes to Unicode, and it does not specify how Unicode issues and errors should be handled. Most of the ambiguity stems from the interpretation and scope [RFC 4627][] Section 3, Encoding: `JSON text SHALL be encoded in Unicode.` It is the authors opinion and interpretation that the language of [RFC 4627][] requires that a JSON implementation MUST follow the requirements specified in the [Unicode Standard][], and in particular the [Conformance][Unicode Standard - Conformance] chapter of the [Unicode Standard][], which specifies requirements related to handling, interpreting, and manipulating Unicode text.
3737-
3738- The default behavior for JSONKit is strict [RFC 4627][] conformance. It is the authors opinion and interpretation that [RFC 4627][] requires JSON to be encoded in Unicode, and therefore JSON that is not legal Unicode as defined by the [Unicode Standard][] is invalid JSON. Therefore, JSONKit will not accept JSON that contains ill-formed Unicode. The default, strict behavior implies that the `JKParseOptionLooseUnicode` option is not enabled.
3739-
3740- When the `JKParseOptionLooseUnicode` option is enabled, JSONKit follows the specifications and recommendations given in [The Unicode 6.0 standard, Chapter 3 - Conformance][Unicode Standard - Conformance], section 3.9 *Unicode Encoding Forms*. As a general rule of thumb, the Unicode code point `U+FFFD` is substituted for any ill-formed Unicode encountered. JSONKit attempts to follow the recommended *Best Practice for Using U+FFFD*: ***Replace each maximal subpart of an ill-formed subsequence by a single U+FFFD.***
3741-
3742- The following Unicode code points are treated as ill-formed Unicode, and if `JKParseOptionLooseUnicode` is enabled, cause `U+FFFD` to be substituted in their place:
3743-
3744- `U+0000`.<br>
3745- `U+D800` thru `U+DFFF`, inclusive.<br>
3746- `U+FDD0` thru `U+FDEF`, inclusive.<br>
3747- <code>U+<i>n</i>FFFE</code> and <code>U+<i>n</i>FFFF</code>, where *n* is from `0x0` to `0x10`
3748-
3749- The code points `U+FDD0` thru `U+FDEF`, <code>U+<i>n</i>FFFE</code>, and <code>U+<i>n</i>FFFF</code> (where *n* is from `0x0` to `0x10`), are defined as ***Noncharacters*** by the Unicode standard and "should never be interchanged".
3750-
3751- 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].
3752-
3753- [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 &ndash; *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.
3754-
3755- 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].
3756-
3757-* The [JSON specification][RFC 4627] does not specify the details or requirements for JSON String values, other than such strings must consist of Unicode code points, nor does it specify how errors should be handled. While JSONKit makes an effort (subject to the reasonable caveats above regarding Unicode) to preserve the parsed JSON String exactly, it can not guarantee that [`NSString`][NSString] will preserve the exact Unicode semantics of the original JSON String.
3758-
3759- JSONKit does not perform any form of Unicode Normalization on the parsed JSON Strings, but can not make any guarantees that the [`NSString`][NSString] class will not perform Unicode Normalization on the parsed JSON String used to instantiate the [`NSString`][NSString] object. The [`NSString`][NSString] class may place additional restrictions or otherwise transform the JSON String in such a way so that the JSON String is not bijective with the instantiated [`NSString`][NSString] object. In other words, JSONKit can not guarantee that when you round trip a JSON String to a [`NSString`][NSString] and then back to a JSON String that the two JSON Strings will be exactly the same, even though in practice they are. For clarity, "exactly" in this case means bit for bit identical. JSONKit can not even guarantee that the two JSON Strings will be [Unicode equivalent][Unicode_equivalence], even though in practice they will be and would be the most likely cause for the two round tripped JSON Strings to no longer be bit for bit identical.
3760-
3761-* JSONKit maps `true` and `false` to the [`CFBoolean`][CFBoolean] values [`kCFBooleanTrue`][kCFBooleanTrue] and [`kCFBooleanFalse`][kCFBooleanFalse], respectively. Conceptually, [`CFBoolean`][CFBoolean] values can be thought of, and treated as, [`NSNumber`][NSNumber] class objects. The benefit to using [`CFBoolean`][CFBoolean] is that `true` and `false` JSON values can be round trip deserialized and serialized without conversion or promotion to a [`NSNumber`][NSNumber] with a value of `0` or `1`.
3762-
3763-* The [JSON specification][RFC 4627] does not specify the details or requirements for JSON Number values, nor does it specify how errors due to conversion should be handled. In general, JSONKit will not accept JSON that contains JSON Number values that it can not convert with out error or loss of precision.
3764-
3765- 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 <code>2<sup>64</sup>-1</code> and up to <code>-2<sup>63</sup></code> 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.
3766-
3767- 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.
3768-
3769-* 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.
3770-
3771- 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`.
3772-
3773- **See also:**<br />
3774- &nbsp;&nbsp;&nbsp;&nbsp;[W3C - Requirements for String Identity Matching and String Indexing](http://www.w3.org/TR/charreq/#sec2)
3775-
3776-### Objective-C To JSON Primitive Mapping Details
3777-
3778-* 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&ndash; 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.
3779-
3780-* The objects to be serialized MUST be acyclic. If the objects to be serialized contain circular references the behavior is `undefined`. For example,
3781-
3782- ```objective-c
3783- [arrayOne addObject:arrayTwo];
3784- [arrayTwo addObject:arrayOne];
3785- id json = [arrayOne JSONString];
3786- ```
3787-
3788- &hellip; will result in `undefined` behavior.
3789-
3790-* 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 <code>\u<i>XXXX</i></code>, and will encode Unicode code points that require `UTF16` surrogate pairs as <code>\u<i>high</i>\u<i>low</i></code>. 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.
3791-
3792-* 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:].
3793-
3794-* 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.
3795-
3796-* JSON does not allow for Numbers that are <code>&plusmn;Infinity</code> or <code>&plusmn;NaN</code>. Therefore JSONKit will fail with an error if it encounters a [`NSNumber`][NSNumber] that contains such a value during serialization.
3797-
3798-* 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`.
3799-
3800-* [`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.
3801-
3802- 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.
3803-
3804- 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`&ndash; 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.
3805-
3806-
3807-### Reporting Bugs
3808-
3809-Please use the [github.com JSONKit Issue Tracker](https://github.com/johnezang/JSONKit/issues) to report bugs.
3810-
3811-The author requests that you do not file a bug report with JSONKit regarding problems reported by the `clang` static analyzer unless you first manually verify that it is an actual, bona-fide problem with JSONKit and, if appropriate, is not "legal" C code as defined by the C99 language specification. If the `clang` static analyzer is reporting a problem with JSONKit that is not an actual, bona-fide problem and is perfectly legal code as defined by the C99 language specification, then the appropriate place to file a bug report or complaint is with the developers of the `clang` static analyzer.
3812-
3813-### Important Details
3814-
3815-* 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.
3816-
3817-* 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.
3818-
3819-* 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].
3820-
3821-* 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`.
3822-
3823-* 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.
3824-
3825-### Tips for speed
3826-
3827-* 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 <span style="white-space: nowrap;">7-12%</span> increase in performance.
3828-
3829-* 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.
3830-
3831-* 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.
3832-
3833-* 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:
3834- 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.
3835- 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.
3836-
3837-* On average, the <code>JSONData&hellip;</code> methods are nearly four times faster than the <code>JSONString&hellip;</code> 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].
3838-
3839-* 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&ndash; 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.
3840-
3841-### Parsing Interface
3842-
3843-#### JSONDecoder Interface
3844-
3845-The <code>objectWith&hellip;</code> methods return immutable collection objects and their respective <code>mutableObjectWith&hellip;</code> methods return mutable collection objects.
3846-
3847-**Note:** The bytes contained in a [`NSData`][NSData] object ***MUST*** be `UTF8` encoded.
3848-
3849-**Important:** Methods will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `parseOptionFlags` is not valid.
3850-**Important:** `objectWithUTF8String:` and `mutableObjectWithUTF8String:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `string` is `NULL`.
3851-**Important:** `objectWithData:` and `mutableObjectWithData:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `jsonData` is `NULL`.
3852-
3853-```objective-c
3854-+ (id)decoder;
3855-+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3856-- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3857-
3858-- (void)clearCache;
3859-
3860-- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length;
3861-- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error;
3862-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length;
3863-- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error;
3864-
3865-- (id)objectWithData:(NSData *)jsonData;
3866-- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
3867-- (id)mutableObjectWithData:(NSData *)jsonData;
3868-- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
3869-```
3870-
3871-#### NSString Interface
3872-
3873-```objective-c
3874-- (id)objectFromJSONString;
3875-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3876-- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3877-- (id)mutableObjectFromJSONString;
3878-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3879-- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3880-```
3881-
3882-#### NSData Interface
3883-
3884-```objective-c
3885-- (id)objectFromJSONData;
3886-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3887-- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3888-- (id)mutableObjectFromJSONData;
3889-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3890-- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3891-```
3892-
3893-#### JKParseOptionFlags
3894-
3895-<table>
3896- <tr><th>Parsing Option</th><th>Description</th></tr>
3897- <tr><td valign="top"><code>JKParseOptionNone</code></td><td>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 <code>JKParseOptionStrict</code>.</td></tr>
3898- <tr><td valign="top"><code>JKParseOptionStrict</code></td><td>The JSON will be parsed in strict accordance with the <a href="http://tools.ietf.org/html/rfc4627">RFC 4627</a> specification.</td></tr>
3899- <tr><td valign="top"><code>JKParseOptionComments</code></td><td>Allow C style <code>//</code> and <code>/* &hellip; */</code> comments in JSON. This is a fairly common extension to JSON, but JSON that contains C style comments is not strictly conforming JSON.</td></tr>
3900- <tr><td valign="top"><code>JKParseOptionUnicodeNewlines</code></td><td>Allow Unicode recommended <code>(?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}])</code> newlines in JSON. The <a href="http://tools.ietf.org/html/rfc4627">JSON specification</a> only allows the newline characters <code>\r</code> and <code>\n</code>, but this option allows JSON that contains the <a href="http://en.wikipedia.org/wiki/Newline#Unicode">Unicode recommended newline characters</a> to be parsed. JSON that contains these additional newline characters is not strictly conforming JSON.</td></tr>
3901- <tr><td valign="top"><code>JKParseOptionLooseUnicode</code></td><td>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 <code>\uFFFD</code>, or <code>REPLACEMENT CHARACTER</code>, as specified in <a href="http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf">The Unicode 6.0 standard, Chapter 3</a>, section 3.9 <em>Unicode Encoding Forms</em>.</td></tr>
3902- <tr><td valign="top"><code>JKParseOptionPermitTextAfterValidJSON</code></td><td>Normally, <code>non-white-space</code> that follows the JSON is interpreted as a parsing failure. This option allows for any trailing <code>non-white-space</code> to be ignored and not cause a parsing error.</td></tr>
3903-</table>
3904-
3905-### Serializing Interface
3906-
3907-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 `[`&hellip;`]` 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:
3908-
3909-Example | Result | Argument
3910---------------|-------------------|--------------------
3911-`a "test"...` | `"a \"test\"..."` | `includeQuotes:YES`
3912-`a "test"...` | `a \"test\"...` | `includeQuotes:NO`
3913-
3914-**Note:** The [`NSString`][NSString] methods that do not include a `includeQuotes:` argument behave as if invoked with `includeQuotes:YES`.
3915-**Note:** The bytes contained in the returned [`NSData`][NSData] object are `UTF8` encoded.
3916-
3917-#### NSArray and NSDictionary Interface
3918-
3919-```objective-c
3920-- (NSData *)JSONData;
3921-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
3922-- (NSString *)JSONString;
3923-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
3924-```
3925-
3926-
3927-#### NSString Interface
3928-
3929-```objective-c
3930-- (NSData *)JSONData;
3931-- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
3932-- (NSString *)JSONString;
3933-- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
3934-```
3935-
3936-#### JKSerializeOptionFlags
3937-
3938-<table>
3939- <tr><th>Serializing Option</th><th>Description</th></tr>
3940- <tr><td valign="top"><code>JKSerializeOptionNone</code></td><td>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.</td></tr>
3941- <tr><td valign="top"><code>JKSerializeOptionPretty</code></td><td>Normally the serialized JSON does not include any unnecessary <code>white-space</code>. While this form is the most compact, the lack of any <code>white-space</code> means that it's something only another JSON parser could love. Enabling this option causes JSONKit to add additional <code>white-space</code> that makes it easier for people to read. Other than the extra <code>white-space</code>, the serialized JSON is identical to the JSON that would have been produced had this option not been enabled.</td></tr>
3942- <tr><td valign="top"><code>JKSerializeOptionEscapeUnicode</code></td><td>When JSONKit encounters Unicode characters in <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html"><code>NSString</code></a> objects, the default behavior is to encode those Unicode characters as <code>UTF8</code>. This option causes JSONKit to encode those characters as <code>\u<i>XXXX</i></code>. For example,<br/><code>["w&isin;L&#10234;y(&#8739;y&#8739;&le;&#8739;w&#8739;)"]</code><br/>becomes:<br/><code>["w\u2208L\u27fa\u2203y(\u2223y\u2223\u2264\u2223w\u2223)"]</code></td></tr>
3943- <tr><td valign="top"><code>JKSerializeOptionEscapeForwardSlashes</code></td><td>According to the <a href="http://tools.ietf.org/html/rfc4627">JSON specification</a>, the <code>/</code> (<code>U+002F</code>) character may be backslash escaped (i.e., <code>\/</code>), but it is not required. The default behavior of JSONKit is to <b><i>not</i></b> backslash escape the <code>/</code> character. Unfortunately, it was found some real world implementations of the <a href="http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx">ASP.NET Date Format</a> require the date to be <i>strictly</i> encoded as <code>\/Date(...)\/</code>, and the only way to achieve this is through the use of <code>JKSerializeOptionEscapeForwardSlashes</code>. See <a href="https://github.com/johnezang/JSONKit/issues/21">github issue #21</a> for more information.</td></tr>
3944-</table>
3945-
3946-[JSON]: http://www.json.org/
3947-[RFC 4627]: http://tools.ietf.org/html/rfc4627
3948-[RFC 2119]: http://tools.ietf.org/html/rfc2119
3949-[Single Precision]: http://en.wikipedia.org/wiki/Single_precision_floating-point_format
3950-[Double Precision]: http://en.wikipedia.org/wiki/Double_precision_floating-point_format
3951-[wiki_invariant]: http://en.wikipedia.org/wiki/Invariant_(computer_science)
3952-[ARC]: http://clang.llvm.org/docs/AutomaticReferenceCounting.html
3953-[CFBoolean]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/index.html
3954-[kCFBooleanTrue]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanTrue
3955-[kCFBooleanFalse]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanFalse
3956-[kCFNumberDoubleType]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFNumberDoubleType
3957-[CFNumberGetValue]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/c/func/CFNumberGetValue
3958-[Unicode Standard]: http://www.unicode.org/versions/Unicode6.0.0/
3959-[Unicode Standard - Conformance]: http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf
3960-[Unicode_equivalence]: http://en.wikipedia.org/wiki/Unicode_equivalence
3961-[UnicodeNewline]: http://en.wikipedia.org/wiki/Newline#Unicode
3962-[Unicode_UTR36]: http://www.unicode.org/reports/tr36/
3963-[Unicode_UTR36_NonVisualSecurity]: http://www.unicode.org/reports/tr36/#Canonical_Represenation
3964-[Unicode_UTR36_Deleting]: http://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters
3965-[Unicode_Security_FAQ]: http://www.unicode.org/faq/security.html
3966-[NSNull]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/index.html
3967-[NSNumber]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/index.html
3968-[NSNumber_numberWithBool]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/clm/NSNumber/numberWithBool:
3969-[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html
3970-[NSString_initWithBytes]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithBytes:length:encoding:
3971-[NSString_initWithData]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithData:encoding:
3972-[NSString_UTF8String]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/UTF8String
3973-[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html
3974-[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html
3975-[NSError]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/index.html
3976-[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html
3977-[NSMutableData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/index.html
3978-[NSInvalidArgumentException]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException
3979-[CFString]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
3980-[NSCParameterAssert]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/macro/NSCParameterAssert
3981-[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy
3982-[-isKindOfClass:]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html%23//apple_ref/occ/intfm/NSObject/isKindOfClass:
3983-[-objCType]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNumber/objCType
3984-[strtoll]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoll.3.html
3985-[strtod]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtod.3.html
3986-[strtoull]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoull.3.html
3987-[getrusage]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/getrusage.2.html
3988-[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html
3989
3990=== modified file 'U1Music.xcodeproj/project.pbxproj'
3991--- U1Music.xcodeproj/project.pbxproj 2012-08-16 16:25:27 +0000
3992+++ U1Music.xcodeproj/project.pbxproj 2012-08-27 23:04:20 +0000
3993@@ -190,7 +190,6 @@
3994 96377AF314E0730B00517845 /* U1StreamReader.m in Sources */ = {isa = PBXBuildFile; fileRef = 96377AF014E0730B00517845 /* U1StreamReader.m */; };
3995 96377AF414E0730B00517845 /* U1StreamWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 96377AF214E0730B00517845 /* U1StreamWriter.m */; };
3996 963C884E14E1AB0C00EB13A2 /* U1LocalMusicServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 963C884D14E1AB0C00EB13A2 /* U1LocalMusicServer.m */; };
3997- 964FA3C213CA5C4F0018A65B /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = 964FA39513CA5C040018A65B /* JSONKit.m */; };
3998 964FA3C313CA5C4F0018A65B /* NSMutableURLRequest+Parameters.m in Sources */ = {isa = PBXBuildFile; fileRef = 964FA39A13CA5C040018A65B /* NSMutableURLRequest+Parameters.m */; };
3999 964FA3C413CA5C4F0018A65B /* NSString+URLEncoding.m in Sources */ = {isa = PBXBuildFile; fileRef = 964FA39C13CA5C040018A65B /* NSString+URLEncoding.m */; };
4000 964FA3C513CA5C4F0018A65B /* NSURL+Base.m in Sources */ = {isa = PBXBuildFile; fileRef = 964FA39E13CA5C040018A65B /* NSURL+Base.m */; };
4001@@ -505,10 +504,6 @@
4002 96377AF214E0730B00517845 /* U1StreamWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = U1StreamWriter.m; sourceTree = "<group>"; };
4003 963C884C14E1AB0C00EB13A2 /* U1LocalMusicServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = U1LocalMusicServer.h; sourceTree = "<group>"; };
4004 963C884D14E1AB0C00EB13A2 /* U1LocalMusicServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = U1LocalMusicServer.m; sourceTree = "<group>"; };
4005- 964FA39313CA5C040018A65B /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = text; path = CHANGELOG.md; sourceTree = "<group>"; };
4006- 964FA39413CA5C040018A65B /* JSONKit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = "<group>"; };
4007- 964FA39513CA5C040018A65B /* JSONKit.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = "<group>"; };
4008- 964FA39613CA5C040018A65B /* README.md */ = {isa = PBXFileReference; lastKnownFileType = text; path = README.md; sourceTree = "<group>"; };
4009 964FA39913CA5C040018A65B /* NSMutableURLRequest+Parameters.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSMutableURLRequest+Parameters.h"; sourceTree = "<group>"; };
4010 964FA39A13CA5C040018A65B /* NSMutableURLRequest+Parameters.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSMutableURLRequest+Parameters.m"; sourceTree = "<group>"; };
4011 964FA39B13CA5C040018A65B /* NSString+URLEncoding.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSString+URLEncoding.h"; sourceTree = "<group>"; };
4012@@ -1082,24 +1077,11 @@
4013 isa = PBXGroup;
4014 children = (
4015 91328278144E07EA00395F40 /* TestFlight SDK */,
4016- 964FA39213CA5C040018A65B /* JSONKit */,
4017 964FA39713CA5C040018A65B /* oauthconsumer */,
4018 );
4019 name = Dependencies;
4020 sourceTree = "<group>";
4021 };
4022- 964FA39213CA5C040018A65B /* JSONKit */ = {
4023- isa = PBXGroup;
4024- children = (
4025- 964FA39313CA5C040018A65B /* CHANGELOG.md */,
4026- 964FA39413CA5C040018A65B /* JSONKit.h */,
4027- 964FA39513CA5C040018A65B /* JSONKit.m */,
4028- 964FA39613CA5C040018A65B /* README.md */,
4029- );
4030- name = JSONKit;
4031- path = Dependencies/JSONKit;
4032- sourceTree = "<group>";
4033- };
4034 964FA39713CA5C040018A65B /* oauthconsumer */ = {
4035 isa = PBXGroup;
4036 children = (
4037@@ -1351,7 +1333,6 @@
4038 isa = PBXSourcesBuildPhase;
4039 buildActionMask = 2147483647;
4040 files = (
4041- 964FA3C213CA5C4F0018A65B /* JSONKit.m in Sources */,
4042 964FA3C313CA5C4F0018A65B /* NSMutableURLRequest+Parameters.m in Sources */,
4043 964FA3C413CA5C4F0018A65B /* NSString+URLEncoding.m in Sources */,
4044 964FA3C513CA5C4F0018A65B /* NSURL+Base.m in Sources */,
4045@@ -1500,6 +1481,7 @@
4046 GCC_THUMB_SUPPORT = NO;
4047 GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
4048 INFOPLIST_FILE = "U1Music-Info.plist";
4049+ IPHONEOS_DEPLOYMENT_TARGET = 5.0;
4050 LIBRARY_SEARCH_PATHS = (
4051 "$(inherited)",
4052 "\"$(SRCROOT)/TestFlight SDK\"",
4053@@ -1531,7 +1513,7 @@
4054 GCC_THUMB_SUPPORT = NO;
4055 GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
4056 INFOPLIST_FILE = "U1Music-Info.plist";
4057- IPHONEOS_DEPLOYMENT_TARGET = 4.0;
4058+ IPHONEOS_DEPLOYMENT_TARGET = 5.0;
4059 LIBRARY_SEARCH_PATHS = (
4060 "$(inherited)",
4061 "\"$(SRCROOT)/TestFlight SDK\"",
4062@@ -1555,7 +1537,7 @@
4063 GCC_C_LANGUAGE_STANDARD = c99;
4064 GCC_WARN_ABOUT_RETURN_TYPE = YES;
4065 GCC_WARN_UNUSED_VARIABLE = YES;
4066- IPHONEOS_DEPLOYMENT_TARGET = 4.0;
4067+ IPHONEOS_DEPLOYMENT_TARGET = 5.0;
4068 OTHER_CFLAGS = "";
4069 PROVISIONING_PROFILE = "";
4070 "PROVISIONING_PROFILE[sdk=iphoneos*]" = "";
4071@@ -1574,7 +1556,7 @@
4072 GCC_C_LANGUAGE_STANDARD = c99;
4073 GCC_WARN_ABOUT_RETURN_TYPE = YES;
4074 GCC_WARN_UNUSED_VARIABLE = YES;
4075- IPHONEOS_DEPLOYMENT_TARGET = 4.0;
4076+ IPHONEOS_DEPLOYMENT_TARGET = 5.0;
4077 PROVISIONING_PROFILE = "";
4078 "PROVISIONING_PROFILE[sdk=iphoneos*]" = "";
4079 SDKROOT = iphoneos;
4080
4081=== modified file 'utilities/operations/UOJSONFetchOperation.m'
4082--- utilities/operations/UOJSONFetchOperation.m 2011-07-12 21:35:15 +0000
4083+++ utilities/operations/UOJSONFetchOperation.m 2012-08-27 23:04:20 +0000
4084@@ -15,9 +15,6 @@
4085
4086 #import "UOJSONFetchOperation.h"
4087
4088-#import "JSONKit.h"
4089-
4090-
4091 @interface UOJSONFetchOperation ()
4092 @property (copy) void (^action)(NSObject *, NSError *);
4093 @property (retain) NSMutableData *jsonData;
4094@@ -71,7 +68,7 @@
4095 NSObject *jsonObject = nil;
4096 if (self.statusCode == 200)
4097 {
4098- jsonObject = [self.jsonData objectFromJSONDataWithParseOptions:JKParseOptionNone error:&error];
4099+ jsonObject = [NSJSONSerialization JSONObjectWithData:self.jsonData options:0 error:&error];
4100 }
4101 else
4102 {
4103
4104=== modified file 'view_controllers/UOMusicLoginController.m'
4105--- view_controllers/UOMusicLoginController.m 2011-08-03 18:25:38 +0000
4106+++ view_controllers/UOMusicLoginController.m 2012-08-27 23:04:20 +0000
4107@@ -15,7 +15,6 @@
4108
4109 #import "UOMusicLoginController.h"
4110
4111-#import "JSONKit.h"
4112 #import "OAuthConsumer.h"
4113 #import "NSString+Extras.h"
4114
4115@@ -187,8 +186,9 @@
4116 {
4117 NSMutableArray *encodedArguments = [NSMutableArray array];
4118 [arguments enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
4119- if (![key isEqualToString:@"ws.op"])
4120- value = [value JSONString];
4121+ if (![key isEqualToString:@"ws.op"]) {
4122+ value = [NSString stringWithFormat:@"\"%@\"", value];
4123+ }
4124 value = [value urlParameterEncodedString];
4125 NSString *argumentPair = [key stringByAppendingFormat:@"=%@", value];
4126 [encodedArguments addObject:argumentPair];

Subscribers

People subscribed via source and target branches