Merge lp:~threeve/ubuntuone-ios-client/in-app-sso into lp:ubuntuone-ios-client

Proposed by Jason Foreman
Status: Merged
Approved by: Zachery Bir
Approved revision: 222
Merged at revision: 199
Proposed branch: lp:~threeve/ubuntuone-ios-client/in-app-sso
Merge into: lp:ubuntuone-ios-client
Diff against target: 9732 lines (+8994/-67)
66 files modified
musicstreaming/Dependencies/JSONKit/CHANGELOG.md (+389/-0)
musicstreaming/Dependencies/JSONKit/JSONKit.h (+251/-0)
musicstreaming/Dependencies/JSONKit/JSONKit.m (+3022/-0)
musicstreaming/Dependencies/JSONKit/README.md (+307/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.h (+37/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.m (+113/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.h (+35/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.m (+73/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.h (+34/-0)
musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.m (+37/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.c (+230/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.h (+36/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.c (+86/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.h (+31/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.c (+169/-0)
musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.h (+13/-0)
musicstreaming/Dependencies/oauthconsumer/OAAttachment.h (+26/-0)
musicstreaming/Dependencies/oauthconsumer/OAAttachment.m (+33/-0)
musicstreaming/Dependencies/oauthconsumer/OACall.h (+63/-0)
musicstreaming/Dependencies/oauthconsumer/OACall.m (+170/-0)
musicstreaming/Dependencies/oauthconsumer/OAConsumer.h (+42/-0)
musicstreaming/Dependencies/oauthconsumer/OAConsumer.m (+60/-0)
musicstreaming/Dependencies/oauthconsumer/OADataFetcher.h (+44/-0)
musicstreaming/Dependencies/oauthconsumer/OADataFetcher.m (+90/-0)
musicstreaming/Dependencies/oauthconsumer/OAHMAC_SHA1SignatureProvider.h (+32/-0)
musicstreaming/Dependencies/oauthconsumer/OAHMAC_SHA1SignatureProvider.m (+58/-0)
musicstreaming/Dependencies/oauthconsumer/OAMutableURLRequest.h (+65/-0)
musicstreaming/Dependencies/oauthconsumer/OAMutableURLRequest.m (+222/-0)
musicstreaming/Dependencies/oauthconsumer/OAPlaintextSignatureProvider.h (+31/-0)
musicstreaming/Dependencies/oauthconsumer/OAPlaintextSignatureProvider.m (+40/-0)
musicstreaming/Dependencies/oauthconsumer/OAProblem.h (+53/-0)
musicstreaming/Dependencies/oauthconsumer/OAProblem.m (+172/-0)
musicstreaming/Dependencies/oauthconsumer/OARequestParameter.h (+48/-0)
musicstreaming/Dependencies/oauthconsumer/OARequestParameter.m (+80/-0)
musicstreaming/Dependencies/oauthconsumer/OAServiceTicket.h (+46/-0)
musicstreaming/Dependencies/oauthconsumer/OAServiceTicket.m (+59/-0)
musicstreaming/Dependencies/oauthconsumer/OASignatureProviding.h (+34/-0)
musicstreaming/Dependencies/oauthconsumer/OATestServer.rb (+37/-0)
musicstreaming/Dependencies/oauthconsumer/OAToken.h (+73/-0)
musicstreaming/Dependencies/oauthconsumer/OAToken.m (+356/-0)
musicstreaming/Dependencies/oauthconsumer/OATokenManager.h (+68/-0)
musicstreaming/Dependencies/oauthconsumer/OATokenManager.m (+401/-0)
musicstreaming/Dependencies/oauthconsumer/OAuthConsumer.h (+40/-0)
musicstreaming/Dependencies/oauthconsumer/README (+15/-0)
musicstreaming/Other Sources/iSubAppDelegate.m (+35/-28)
musicstreaming/about/about.html (+71/-0)
musicstreaming/categories/NSString+Extras.h (+1/-0)
musicstreaming/categories/NSString+Extras.m (+7/-0)
musicstreaming/iSub-Info.plist (+2/-2)
musicstreaming/iSub.xcodeproj/project.pbxproj (+219/-1)
musicstreaming/utilities/UOSSOMusicCredsFetchOperation.h (+24/-0)
musicstreaming/utilities/UOSSOMusicCredsFetchOperation.m (+57/-0)
musicstreaming/utilities/operations/AbstractNetworkOperation.h (+5/-0)
musicstreaming/utilities/operations/AbstractNetworkOperation.m (+29/-12)
musicstreaming/utilities/operations/UOHTTPFetchOperation.h (+23/-0)
musicstreaming/utilities/operations/UOHTTPFetchOperation.m (+85/-0)
musicstreaming/utilities/operations/UOJSONFetchOperation.h (+25/-0)
musicstreaming/utilities/operations/UOJSONFetchOperation.m (+83/-0)
musicstreaming/view_controllers/SettingsViewController.m (+1/-0)
musicstreaming/view_controllers/SubsonicTableViewController.m (+9/-13)
musicstreaming/view_controllers/UOMusicLoginController.h (+31/-0)
musicstreaming/view_controllers/UOMusicLoginController.m (+198/-0)
musicstreaming/view_controllers/UOSSOCredentialsViewController.h (+38/-0)
musicstreaming/view_controllers/UOSSOCredentialsViewController.m (+80/-0)
musicstreaming/view_controllers/UOSSOCredentialsViewController.xib (+641/-0)
musicstreaming/xibs/SongViewController.xib (+9/-11)
To merge this branch: bzr merge lp:~threeve/ubuntuone-ios-client/in-app-sso
Reviewer Review Type Date Requested Status
Zachery Bir (community) Approve
Review via email: mp+67631@code.launchpad.net

Description of the change

Remove the external openid auth and implement in-app SSO, still ultimately using the mobile phone creds instead of oauth.

To post a comment you must log in.
213. By Jason Foreman

Removing unused code and TODOs that will never be TODOne.

214. By Jason Foreman

Got the header stripes showing property.

215. By Jason Foreman

Handle the case when a U1 user does not have mobile subscription.

216. By Jason Foreman

Bump version.

217. By Jason Foreman

Tweak UI for SSO log in screen.

218. By Jason Foreman

Turn off autocorrect on username field.

219. By Jason Foreman

Tweak messaging.

220. By Jason Foreman

Enlarge the shuffle and repeat buttons for easier tappability.

221. By Jason Foreman

Bump version, set pre-glossed icon flag.

222. By Jason Foreman

Adding attributions for OAuthConsumer and JSONKit.

Revision history for this message
Zachery Bir (urbanape) wrote :

Looks good, woot!

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added directory 'musicstreaming/Dependencies'
2=== added directory 'musicstreaming/Dependencies/JSONKit'
3=== added file 'musicstreaming/Dependencies/JSONKit/CHANGELOG.md'
4--- musicstreaming/Dependencies/JSONKit/CHANGELOG.md 1970-01-01 00:00:00 +0000
5+++ musicstreaming/Dependencies/JSONKit/CHANGELOG.md 2011-07-18 14:06:59 +0000
6@@ -0,0 +1,389 @@
7+# JSONKit Changelog
8+
9+## Version 1.X ????/??/??
10+
11+**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.
12+
13+### New Features
14+
15+* When `JKSerializeOptionPretty` is enabled, JSONKit now sorts the keys.
16+
17+* 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.
18+
19+ 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.
20+
21+ 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.
22+
23+ This greatly simplifies things when you have a complex, nested objects with objects that do not belong to the classes that JSONKit can serialize.
24+
25+ 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).
26+
27+ To serialize NSArray or NSDictionary objects using a delegate–
28+
29+ **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:`).
30+ **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail.
31+
32+ <pre>
33+ &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
34+ &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
35+ </pre>
36+
37+ To serialize NSArray or NSDictionary objects using a `^` block&ndash;
38+
39+ **NOTE:** The block is passed a single argument, the object with the unsupported class.
40+ **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail.
41+
42+ <pre>
43+ &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(&#x005E;)(id object))block error:(NSError \*\*)error;
44+ &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(&#x005E;)(id object))block error:(NSError \*\*)error;
45+ </pre>
46+
47+ Example using the delegate way:
48+
49+ <pre>
50+ @interface MYFormatter : NSObject {
51+ NSDateFormatter \*outputFormatter;
52+ }
53+ @end
54+ &#x200b;
55+ @implementation MYFormatter
56+ -(id)init
57+ {
58+ if((self = [super init]) == NULL) { return(NULL); }
59+ if((outputFormatter = [[NSDateFormatter alloc] init]) == NULL) { [self autorelease]; return(NULL); }
60+ [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
61+ return(self);
62+ }
63+ &#x200b;
64+ -(void)dealloc
65+ {
66+ if(outputFormatter != NULL) { [outputFormatter release]; outputFormatter = NULL; }
67+ [super dealloc];
68+ }
69+ &#x200b;
70+ -(id)formatObject:(id)object
71+ {
72+ if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
73+ return(NULL);
74+ }
75+ @end
76+ &#x200b;
77+ {
78+ MYFormatter \*myFormatter = [[[MYFormatter alloc] init] autorelease];
79+ NSArray \*array = [NSArray arrayWithObject:[NSDate dateWithTimeIntervalSinceNow:0.0]];
80+
81+ NSString \*jsonString = NULL;
82+ jsonString = [array JSONStringWithOptions:JKSerializeOptionNone
83+ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;serializeUnsupportedClassesUsingDelegate:myFormatter
84+ &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:)
85+ &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];
86+ NSLog(@"jsonString: '%@'", jsonString);
87+ // 2011-03-25 11:42:16.175 formatter_example[59120:903] jsonString: '["2011-03-25T11:42:16.175-0400"]'
88+ }
89+ </pre>
90+
91+ Example using the `^` block way:
92+
93+ <pre>
94+ {
95+ NSDateFormatter \*outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
96+ [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
97+ &#x200b;
98+ jsonString = [array JSONStringWithOptions:encodeOptions
99+ &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) {
100+ &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]); }
101+ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return(NULL);
102+ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
103+ &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];
104+ NSLog(@"jsonString: '%@'", jsonString);
105+ // 2011-03-25 11:49:56.434 json_parse[59167:903] jsonString: '["2011-03-25T11:49:56.434-0400"]'
106+ }
107+ </pre>
108+
109+### Major Changes
110+
111+* 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.
112+
113+## Version 1.4 2011/23/03
114+
115+### Highlights
116+
117+* 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.
118+
119+### New Features
120+
121+* JSONKit can now return mutable collection classes.
122+* The `JKSerializeOptionFlags` option `JKSerializeOptionPretty` was implemented.
123+* It is now possible to serialize a single [`NSString`][NSString]. This functionality was requested in issue #4 and issue #11.
124+
125+### Deprecated Methods
126+
127+* The following `JSONDecoder` methods are deprecated beginning with JSONKit v1.4 and will be removed in a later release&ndash;
128+
129+ <pre>
130+ &#x200b;- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length;
131+ &#x200b;- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length error:(NSError \*\*)error;
132+ &#x200b;- (id)parseJSONData:(NSData \*)jsonData;
133+ &#x200b;- (id)parseJSONData:(NSData \*)jsonData error:(NSError \*\*)error;
134+ </pre>
135+
136+ The JSONKit v1.4 <code>objectWith&hellip;</code> methods should be used instead.
137+
138+### NEW API's
139+
140+* The following methods were added to `JSONDecoder`&ndash;
141+
142+ These methods replace their deprecated <code>parse&hellip;</code> counterparts and return immutable collection objects.
143+
144+ <pre>
145+ &#x200b;- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
146+ &#x200b;- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
147+ &#x200b;- (id)objectWithData:(NSData \*)jsonData;
148+ &#x200b;- (id)objectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
149+ </pre>
150+
151+ These methods are the same as their <code>objectWith&hellip;</code> counterparts except they return mutable collection objects.
152+
153+ <pre>
154+ &#x200b;- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
155+ &#x200b;- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
156+ &#x200b;- (id)mutableObjectWithData:(NSData \*)jsonData;
157+ &#x200b;- (id)mutableObjectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
158+ </pre>
159+
160+* The following methods were added to `NSString (JSONKitDeserializing)`&ndash;
161+
162+ These methods are the same as their <code>objectFrom&hellip;</code> counterparts except they return mutable collection objects.
163+
164+ <pre>
165+ &#x200b;- (id)mutableObjectFromJSONString;
166+ &#x200b;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
167+ &#x200b;- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
168+ </pre>
169+
170+* The following methods were added to `NSData (JSONKitDeserializing)`&ndash;
171+
172+ These methods are the same as their <code>objectFrom&hellip;</code> counterparts except they return mutable collection objects.
173+
174+ <pre>
175+ &#x200b;- (id)mutableObjectFromJSONData;
176+ &#x200b;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
177+ &#x200b;- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
178+ </pre>
179+
180+* The following methods were added to `NSString (JSONKitSerializing)`&ndash;
181+
182+ These methods are for those uses that need to serialize a single [`NSString`][NSString]&ndash;
183+
184+ <pre>
185+ &#x200b;- (NSData \*)JSONData;
186+ &#x200b;- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
187+ &#x200b;- (NSString \*)JSONString;
188+ &#x200b;- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
189+ </pre>
190+
191+### Bug Fixes
192+
193+* 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.
194+* 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.
195+* `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.
196+
197+### Important Notes
198+
199+* 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.
200+
201+ In theory, these custom classes should behave exactly the same as the respective Foundation / Cocoa counterparts.
202+
203+ 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.
204+
205+ 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].
206+
207+ 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.
208+
209+ #### Exceptions Thrown
210+
211+ 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].
212+
213+ #### Multithreading Safety
214+
215+ 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.
216+
217+ 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.
218+
219+ #### Mutable Collection Notes
220+
221+ 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.
222+
223+ #### `JKMutableArray` Usage Notes
224+
225+ * 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.
226+
227+ * 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.
228+
229+ * 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.
230+
231+ * 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.
232+
233+ * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSArray`][NSArray] or [`NSMutableArray`][NSMutableArray] class object, respectively, with the contents of the receiver.
234+
235+ #### `JKMutableDictionary` Usage Notes
236+
237+ * 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.
238+
239+ * 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.
240+
241+ * 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.
242+
243+ * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSDictionary`][NSDictionary] or [`NSMutableDictionary`][NSMutableDictionary] class object, respectively, with the contents of the receiver.
244+
245+### Major Changes
246+
247+* The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag that was added to JSONKit v1.3 has been removed.
248+
249+ `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.
250+
251+ 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].
252+
253+ 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.
254+
255+ 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.
256+
257+ 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.
258+
259+ 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;
260+
261+ <pre>
262+ v1.3 read : min: 456.000 us, avg: 460.056 us, char/s: 53341332.36 / 50.870 MB/s
263+ v1.3 write: min: 150.000 us, avg: 151.816 us, char/s: 161643041.58 / 154.155 MB/s</pre>
264+
265+ <pre>
266+ v1.4 read : min: 285.000 us, avg: 288.603 us, char/s: 85030301.14 / 81.091 MB/s
267+ v1.4 write: min: 127.000 us, avg: 129.617 us, char/s: 189327017.29 / 180.556 MB/s</pre>
268+
269+ JSONKit v1.4 is nearly 60% faster at reading and 17% faster at writing than v1.3.
270+
271+ 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".
272+
273+ <pre>
274+ v1.3 read : min: 5222.000 us, avg: 5262.344 us, char/s: 15585260.10 / 14.863 MB/s
275+ v1.3 write: min: 1253.000 us, avg: 1259.914 us, char/s: 65095712.88 / 62.080 MB/s</pre>
276+
277+ <pre>
278+ v1.4 read : min: 4096.000 us, avg: 4122.240 us, char/s: 19895736.30 / 18.974 MB/s
279+ v1.4 write: min: 1319.000 us, avg: 1335.538 us, char/s: 61409709.05 / 58.565 MB/s</pre>
280+
281+ JSONKit v1.4 is 28% faster at reading and 6% faster at writing that v1.3 in this worst-case torture test.
282+
283+ 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.
284+
285+ 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;
286+
287+ <pre>
288+ &#x200b; read : min: 1670.000 us, avg: 1682.461 us, char/s: 14585776.43 / 13.910 MB/s
289+ &#x200b; write: min: 1021.000 us, avg: 1028.970 us, char/s: 23849091.81 / 22.744 MB/s</pre>
290+
291+ 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.
292+
293+ JSONKit v1.4 is 483% faster at reading and 694% faster at writing than [json-framework][].
294+
295+### Other Changes
296+
297+* 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.
298+* 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.
299+* 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.
300+* Removed a lot of internal and private data structures from `JSONKit.h` and put them in `JSONKit.m`.
301+* 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.
302+* The usual sundry of inconsequential tidies and what not, such as updating the `README.md`, etc.
303+* The catagory additions to the Cocoa classes were changed from `JSONKit` to `JSONKitDeserializing` and `JSONKitSerializing`, as appropriate.
304+
305+## Version 1.3 2011/05/02
306+
307+### New Features
308+
309+* Added the `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag.
310+
311+ 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.
312+
313+ 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.
314+
315+ 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.
316+
317+ 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.
318+
319+ **NOTE**: `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to `(CF|NS)` `Dictionary` and `Array` class objects.
320+
321+ 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.
322+
323+ 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`.
324+
325+ `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.
326+
327+### Bug Fixes
328+
329+* 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`.
330+
331+### Other Changes
332+
333+* Added `JK_EXPECTED` optimization hints around several conditionals.
334+* 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.
335+* 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.
336+* Various other minor or trivial modifications, such as updating `README.md`.
337+
338+### Other Issues
339+
340+* 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`.
341+
342+ 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."
343+
344+## Version 1.2 2011/01/08
345+
346+### Bug Fixes
347+
348+* 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.
349+* Under some conditions, JSONKit could potentially leak memory.
350+* 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.
351+
352+### Other Changes
353+
354+* 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.
355+* Various other minor changes such as tightening up numeric literals with `UL` or `L` qualification, assertion check tweaks and additions, etc.
356+* The README.md file was updated with additional information.
357+
358+### Version 1.1
359+
360+No change log information was kept for versions prior to 1.2.
361+
362+[bugtracker]: https://github.com/johnezang/JSONKit/issues
363+[RFC 4627]: http://tools.ietf.org/html/rfc4627
364+[twitter_public_timeline.json]: https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json
365+[json-framework]: https://github.com/stig/json-framework
366+[Single Precision]: http://en.wikipedia.org/wiki/Single_precision
367+[kCFTypeArrayCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html#//apple_ref/c/data/kCFTypeArrayCallBacks
368+[kCFTypeDictionaryKeyCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryKeyCallBacks
369+[kCFTypeDictionaryValueCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryValueCallBacks
370+[CFRetain]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRetain
371+[CFRelease]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRelease
372+[CFDataCreateWithBytesNoCopy]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDataRef/Reference/reference.html#//apple_ref/c/func/CFDataCreateWithBytesNoCopy
373+[CFArray]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html
374+[CFDictionary]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html
375+[CFDictionaryCreate]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/func/CFDictionaryCreate
376+[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy
377+[-copy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/copy
378+[-retain]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retain
379+[-release]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/release
380+[-isEqual:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:
381+[-hash]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/hash
382+[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html
383+[NSMutableArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html
384+[-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:
385+[-removeObjectAtIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/removeObjectAtIndex:
386+[-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:
387+[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html
388+[NSMutableDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/index.html
389+[-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:
390+[-removeObjectForKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/removeObjectForKey:
391+[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html
392+[NSFastEnumeration]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/Reference/NSFastEnumeration.html
393+[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html
394+[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html
395+[memmove]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/memmove.3.html
396
397=== added file 'musicstreaming/Dependencies/JSONKit/JSONKit.h'
398--- musicstreaming/Dependencies/JSONKit/JSONKit.h 1970-01-01 00:00:00 +0000
399+++ musicstreaming/Dependencies/JSONKit/JSONKit.h 2011-07-18 14:06:59 +0000
400@@ -0,0 +1,251 @@
401+//
402+// JSONKit.h
403+// http://github.com/johnezang/JSONKit
404+// Dual licensed under either the terms of the BSD License, or alternatively
405+// under the terms of the Apache License, Version 2.0, as specified below.
406+//
407+
408+/*
409+ Copyright (c) 2011, John Engelhart
410+
411+ All rights reserved.
412+
413+ Redistribution and use in source and binary forms, with or without
414+ modification, are permitted provided that the following conditions are met:
415+
416+ * Redistributions of source code must retain the above copyright
417+ notice, this list of conditions and the following disclaimer.
418+
419+ * Redistributions in binary form must reproduce the above copyright
420+ notice, this list of conditions and the following disclaimer in the
421+ documentation and/or other materials provided with the distribution.
422+
423+ * Neither the name of the Zang Industries nor the names of its
424+ contributors may be used to endorse or promote products derived from
425+ this software without specific prior written permission.
426+
427+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
428+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
429+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
430+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
431+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
432+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
433+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
434+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
435+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
436+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
437+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
438+*/
439+
440+/*
441+ Copyright 2011 John Engelhart
442+
443+ Licensed under the Apache License, Version 2.0 (the "License");
444+ you may not use this file except in compliance with the License.
445+ You may obtain a copy of the License at
446+
447+ http://www.apache.org/licenses/LICENSE-2.0
448+
449+ Unless required by applicable law or agreed to in writing, software
450+ distributed under the License is distributed on an "AS IS" BASIS,
451+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
452+ See the License for the specific language governing permissions and
453+ limitations under the License.
454+*/
455+
456+#include <stddef.h>
457+#include <stdint.h>
458+#include <limits.h>
459+#include <TargetConditionals.h>
460+#include <AvailabilityMacros.h>
461+
462+#ifdef __OBJC__
463+#import <Foundation/NSArray.h>
464+#import <Foundation/NSData.h>
465+#import <Foundation/NSDictionary.h>
466+#import <Foundation/NSError.h>
467+#import <Foundation/NSObjCRuntime.h>
468+#import <Foundation/NSString.h>
469+#endif // __OBJC__
470+
471+#ifdef __cplusplus
472+extern "C" {
473+#endif
474+
475+
476+// For Mac OS X < 10.5.
477+#ifndef NSINTEGER_DEFINED
478+#define NSINTEGER_DEFINED
479+#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
480+typedef long NSInteger;
481+typedef unsigned long NSUInteger;
482+#define NSIntegerMin LONG_MIN
483+#define NSIntegerMax LONG_MAX
484+#define NSUIntegerMax ULONG_MAX
485+#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
486+typedef int NSInteger;
487+typedef unsigned int NSUInteger;
488+#define NSIntegerMin INT_MIN
489+#define NSIntegerMax INT_MAX
490+#define NSUIntegerMax UINT_MAX
491+#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
492+#endif // NSINTEGER_DEFINED
493+
494+
495+#ifndef _JSONKIT_H_
496+#define _JSONKIT_H_
497+
498+#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465)
499+#define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated))
500+#else
501+#define JK_DEPRECATED_ATTRIBUTE
502+#endif
503+
504+#define JSONKIT_VERSION_MAJOR 1
505+#define JSONKIT_VERSION_MINOR 4
506+
507+typedef NSUInteger JKFlags;
508+
509+/*
510+ JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON.
511+ JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines.
512+ JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode.
513+ This option allows JSON with malformed Unicode to be parsed without reporting an error.
514+ Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER".
515+ */
516+
517+enum {
518+ JKParseOptionNone = 0,
519+ JKParseOptionStrict = 0,
520+ JKParseOptionComments = (1 << 0),
521+ JKParseOptionUnicodeNewlines = (1 << 1),
522+ JKParseOptionLooseUnicode = (1 << 2),
523+ JKParseOptionPermitTextAfterValidJSON = (1 << 3),
524+ JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON),
525+};
526+typedef JKFlags JKParseOptionFlags;
527+
528+enum {
529+ JKSerializeOptionNone = 0,
530+ JKSerializeOptionPretty = (1 << 0),
531+ JKSerializeOptionEscapeUnicode = (1 << 1),
532+ JKSerializeOptionEscapeForwardSlashes = (1 << 4),
533+ JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes),
534+};
535+typedef JKFlags JKSerializeOptionFlags;
536+
537+#ifdef __OBJC__
538+
539+typedef struct JKParseState JKParseState; // Opaque internal, private type.
540+
541+// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict
542+
543+@interface JSONDecoder : NSObject {
544+ JKParseState *parseState;
545+}
546++ (id)decoder;
547++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
548+- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
549+- (void)clearCache;
550+
551+// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods.
552+- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
553+- (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.
554+// The NSData MUST be UTF8 encoded JSON.
555+- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead.
556+- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
557+
558+// Methods that return immutable collection objects.
559+- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
560+- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
561+// The NSData MUST be UTF8 encoded JSON.
562+- (id)objectWithData:(NSData *)jsonData;
563+- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
564+
565+// Methods that return mutable collection objects.
566+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
567+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
568+// The NSData MUST be UTF8 encoded JSON.
569+- (id)mutableObjectWithData:(NSData *)jsonData;
570+- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
571+
572+@end
573+
574+////////////
575+#pragma mark Deserializing methods
576+////////////
577+
578+@interface NSString (JSONKitDeserializing)
579+- (id)objectFromJSONString;
580+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
581+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
582+- (id)mutableObjectFromJSONString;
583+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
584+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
585+@end
586+
587+@interface NSData (JSONKitDeserializing)
588+// The NSData MUST be UTF8 encoded JSON.
589+- (id)objectFromJSONData;
590+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
591+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
592+- (id)mutableObjectFromJSONData;
593+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
594+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
595+@end
596+
597+////////////
598+#pragma mark Serializing methods
599+////////////
600+
601+@interface NSString (JSONKitSerializing)
602+// 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).
603+// 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:
604+// includeQuotes:YES `a "test"...` -> `"a \"test\"..."`
605+// includeQuotes:NO `a "test"...` -> `a \"test\"...`
606+- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES
607+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
608+- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES
609+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
610+@end
611+
612+@interface NSArray (JSONKitSerializing)
613+- (NSData *)JSONData;
614+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
615+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
616+- (NSString *)JSONString;
617+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
618+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
619+@end
620+
621+@interface NSDictionary (JSONKitSerializing)
622+- (NSData *)JSONData;
623+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
624+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
625+- (NSString *)JSONString;
626+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
627+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
628+@end
629+
630+#ifdef __BLOCKS__
631+
632+@interface NSArray (JSONKitSerializingBlockAdditions)
633+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
634+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
635+@end
636+
637+@interface NSDictionary (JSONKitSerializingBlockAdditions)
638+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
639+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
640+@end
641+
642+#endif
643+
644+
645+#endif // __OBJC__
646+
647+#endif // _JSONKIT_H_
648+
649+#ifdef __cplusplus
650+} // extern "C"
651+#endif
652
653=== added file 'musicstreaming/Dependencies/JSONKit/JSONKit.m'
654--- musicstreaming/Dependencies/JSONKit/JSONKit.m 1970-01-01 00:00:00 +0000
655+++ musicstreaming/Dependencies/JSONKit/JSONKit.m 2011-07-18 14:06:59 +0000
656@@ -0,0 +1,3022 @@
657+//
658+// JSONKit.m
659+// http://github.com/johnezang/JSONKit
660+// Dual licensed under either the terms of the BSD License, or alternatively
661+// under the terms of the Apache License, Version 2.0, as specified below.
662+//
663+
664+/*
665+ Copyright (c) 2011, John Engelhart
666+
667+ All rights reserved.
668+
669+ Redistribution and use in source and binary forms, with or without
670+ modification, are permitted provided that the following conditions are met:
671+
672+ * Redistributions of source code must retain the above copyright
673+ notice, this list of conditions and the following disclaimer.
674+
675+ * Redistributions in binary form must reproduce the above copyright
676+ notice, this list of conditions and the following disclaimer in the
677+ documentation and/or other materials provided with the distribution.
678+
679+ * Neither the name of the Zang Industries nor the names of its
680+ contributors may be used to endorse or promote products derived from
681+ this software without specific prior written permission.
682+
683+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
684+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
685+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
686+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
687+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
688+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
689+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
690+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
691+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
692+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
693+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
694+*/
695+
696+/*
697+ Copyright 2011 John Engelhart
698+
699+ Licensed under the Apache License, Version 2.0 (the "License");
700+ you may not use this file except in compliance with the License.
701+ You may obtain a copy of the License at
702+
703+ http://www.apache.org/licenses/LICENSE-2.0
704+
705+ Unless required by applicable law or agreed to in writing, software
706+ distributed under the License is distributed on an "AS IS" BASIS,
707+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
708+ See the License for the specific language governing permissions and
709+ limitations under the License.
710+*/
711+
712+
713+/*
714+ Acknowledgments:
715+
716+ The bulk of the UTF8 / UTF32 conversion and verification comes
717+ from ConvertUTF.[hc]. It has been modified from the original sources.
718+
719+ The original sources were obtained from http://www.unicode.org/.
720+ However, the web site no longer seems to host the files. Instead,
721+ the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4
722+ points to International Components for Unicode (ICU)
723+ http://site.icu-project.org/ as an example of how to write a UTF
724+ converter.
725+
726+ The decision to use the ConvertUTF.[ch] code was made to leverage
727+ "proven" code. Hopefully the local modifications are bug free.
728+
729+ The code in isValidCodePoint() is derived from the ICU code in
730+ utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR.
731+
732+ From the original ConvertUTF.[ch]:
733+
734+ * Copyright 2001-2004 Unicode, Inc.
735+ *
736+ * Disclaimer
737+ *
738+ * This source code is provided as is by Unicode, Inc. No claims are
739+ * made as to fitness for any particular purpose. No warranties of any
740+ * kind are expressed or implied. The recipient agrees to determine
741+ * applicability of information provided. If this file has been
742+ * purchased on magnetic or optical media from Unicode, Inc., the
743+ * sole remedy for any claim will be exchange of defective media
744+ * within 90 days of receipt.
745+ *
746+ * Limitations on Rights to Redistribute This Code
747+ *
748+ * Unicode, Inc. hereby grants the right to freely use the information
749+ * supplied in this file in the creation of products supporting the
750+ * Unicode Standard, and to make copies of this file in any form
751+ * for internal or external distribution as long as this notice
752+ * remains attached.
753+
754+*/
755+
756+#include <stdio.h>
757+#include <stdlib.h>
758+#include <stdint.h>
759+#include <string.h>
760+#include <assert.h>
761+#include <sys/errno.h>
762+#include <math.h>
763+#include <limits.h>
764+#include <objc/runtime.h>
765+
766+#import "JSONKit.h"
767+
768+//#include <CoreFoundation/CoreFoundation.h>
769+#include <CoreFoundation/CFString.h>
770+#include <CoreFoundation/CFArray.h>
771+#include <CoreFoundation/CFDictionary.h>
772+#include <CoreFoundation/CFNumber.h>
773+
774+//#import <Foundation/Foundation.h>
775+#import <Foundation/NSArray.h>
776+#import <Foundation/NSAutoreleasePool.h>
777+#import <Foundation/NSData.h>
778+#import <Foundation/NSDictionary.h>
779+#import <Foundation/NSException.h>
780+#import <Foundation/NSNull.h>
781+#import <Foundation/NSObjCRuntime.h>
782+
783+#ifndef __has_feature
784+#define __has_feature(x) 0
785+#endif
786+
787+#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS
788+#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option.
789+#endif
790+
791+#ifdef __OBJC_GC__
792+#error JSONKit does not support Objective-C Garbage Collection
793+#endif
794+
795+#if __has_feature(objc_arc)
796+#error JSONKit does not support Objective-C Automatic Reference Counting (ARC)
797+#endif
798+
799+// The following checks are really nothing more than sanity checks.
800+// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety.
801+// 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.
802+// 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.
803+
804+#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL))
805+#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively.
806+#endif
807+
808+#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT))
809+#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures.
810+#endif
811+
812+// 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
813+
814+#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN)
815+#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type.
816+#endif
817+
818+#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX)
819+#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type.
820+#endif
821+
822+
823+// For DJB hash.
824+#define JK_HASH_INIT (1402737925UL)
825+
826+// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup.
827+#define JK_FAST_TRAILING_BYTES
828+
829+// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots.
830+#define JK_CACHE_SLOTS_BITS (10)
831+#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS)
832+// JK_CACHE_PROBES is the number of probe attempts.
833+#define JK_CACHE_PROBES (4UL)
834+// JK_INIT_CACHE_AGE must be (1 << AGE) - 1
835+#define JK_INIT_CACHE_AGE (0)
836+
837+// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes)
838+#define JK_TOKENBUFFER_SIZE (1024UL * 2UL)
839+
840+// 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.
841+#define JK_STACK_OBJS (1024UL * 1UL)
842+
843+#define JK_JSONBUFFER_SIZE (1024UL * 4UL)
844+#define JK_UTF8BUFFER_SIZE (1024UL * 16UL)
845+
846+#define JK_ENCODE_CACHE_SLOTS (1024UL)
847+
848+
849+#if defined (__GNUC__) && (__GNUC__ >= 4)
850+#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__))
851+#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect))
852+#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U)
853+#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U)
854+#define JK_PREFETCH(ptr) __builtin_prefetch(ptr)
855+#else // defined (__GNUC__) && (__GNUC__ >= 4)
856+#define JK_ATTRIBUTES(attr, ...)
857+#define JK_EXPECTED(cond, expect) (cond)
858+#define JK_EXPECT_T(cond) (cond)
859+#define JK_EXPECT_F(cond) (cond)
860+#define JK_PREFETCH(ptr)
861+#endif // defined (__GNUC__) && (__GNUC__ >= 4)
862+
863+#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline)
864+#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg))
865+#define JK_UNUSED_ARG JK_ATTRIBUTES(unused)
866+#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result)
867+#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const)
868+#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure)
869+#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel)
870+#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__))
871+#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__))
872+#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__))
873+#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__))
874+
875+#if 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__), alloc_size(as))
877+#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
878+#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__))
879+#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
880+
881+
882+@class JKArray, JKDictionaryEnumerator, JKDictionary;
883+
884+enum {
885+ JSONNumberStateStart = 0,
886+ JSONNumberStateFinished = 1,
887+ JSONNumberStateError = 2,
888+ JSONNumberStateWholeNumberStart = 3,
889+ JSONNumberStateWholeNumberMinus = 4,
890+ JSONNumberStateWholeNumberZero = 5,
891+ JSONNumberStateWholeNumber = 6,
892+ JSONNumberStatePeriod = 7,
893+ JSONNumberStateFractionalNumberStart = 8,
894+ JSONNumberStateFractionalNumber = 9,
895+ JSONNumberStateExponentStart = 10,
896+ JSONNumberStateExponentPlusMinus = 11,
897+ JSONNumberStateExponent = 12,
898+};
899+
900+enum {
901+ JSONStringStateStart = 0,
902+ JSONStringStateParsing = 1,
903+ JSONStringStateFinished = 2,
904+ JSONStringStateError = 3,
905+ JSONStringStateEscape = 4,
906+ JSONStringStateEscapedUnicode1 = 5,
907+ JSONStringStateEscapedUnicode2 = 6,
908+ JSONStringStateEscapedUnicode3 = 7,
909+ JSONStringStateEscapedUnicode4 = 8,
910+ JSONStringStateEscapedUnicodeSurrogate1 = 9,
911+ JSONStringStateEscapedUnicodeSurrogate2 = 10,
912+ JSONStringStateEscapedUnicodeSurrogate3 = 11,
913+ JSONStringStateEscapedUnicodeSurrogate4 = 12,
914+ JSONStringStateEscapedNeedEscapeForSurrogate = 13,
915+ JSONStringStateEscapedNeedEscapedUForSurrogate = 14,
916+};
917+
918+enum {
919+ JKParseAcceptValue = (1 << 0),
920+ JKParseAcceptComma = (1 << 1),
921+ JKParseAcceptEnd = (1 << 2),
922+ JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd),
923+ JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd),
924+};
925+
926+enum {
927+ JKClassUnknown = 0,
928+ JKClassString = 1,
929+ JKClassNumber = 2,
930+ JKClassArray = 3,
931+ JKClassDictionary = 4,
932+ JKClassNull = 5,
933+};
934+
935+enum {
936+ JKManagedBufferOnStack = 1,
937+ JKManagedBufferOnHeap = 2,
938+ JKManagedBufferLocationMask = (0x3),
939+ JKManagedBufferLocationShift = (0),
940+
941+ JKManagedBufferMustFree = (1 << 2),
942+};
943+typedef JKFlags JKManagedBufferFlags;
944+
945+enum {
946+ JKObjectStackOnStack = 1,
947+ JKObjectStackOnHeap = 2,
948+ JKObjectStackLocationMask = (0x3),
949+ JKObjectStackLocationShift = (0),
950+
951+ JKObjectStackMustFree = (1 << 2),
952+};
953+typedef JKFlags JKObjectStackFlags;
954+
955+enum {
956+ JKTokenTypeInvalid = 0,
957+ JKTokenTypeNumber = 1,
958+ JKTokenTypeString = 2,
959+ JKTokenTypeObjectBegin = 3,
960+ JKTokenTypeObjectEnd = 4,
961+ JKTokenTypeArrayBegin = 5,
962+ JKTokenTypeArrayEnd = 6,
963+ JKTokenTypeSeparator = 7,
964+ JKTokenTypeComma = 8,
965+ JKTokenTypeTrue = 9,
966+ JKTokenTypeFalse = 10,
967+ JKTokenTypeNull = 11,
968+ JKTokenTypeWhiteSpace = 12,
969+};
970+typedef NSUInteger JKTokenType;
971+
972+// These are prime numbers to assist with hash slot probing.
973+enum {
974+ JKValueTypeNone = 0,
975+ JKValueTypeString = 5,
976+ JKValueTypeLongLong = 7,
977+ JKValueTypeUnsignedLongLong = 11,
978+ JKValueTypeDouble = 13,
979+};
980+typedef NSUInteger JKValueType;
981+
982+enum {
983+ JKEncodeOptionAsData = 1,
984+ JKEncodeOptionAsString = 2,
985+ JKEncodeOptionAsTypeMask = 0x7,
986+ JKEncodeOptionCollectionObj = (1 << 3),
987+ JKEncodeOptionStringObj = (1 << 4),
988+ JKEncodeOptionStringObjTrimQuotes = (1 << 5),
989+
990+};
991+typedef NSUInteger JKEncodeOptionType;
992+
993+typedef NSUInteger JKHash;
994+
995+typedef struct JKTokenCacheItem JKTokenCacheItem;
996+typedef struct JKTokenCache JKTokenCache;
997+typedef struct JKTokenValue JKTokenValue;
998+typedef struct JKParseToken JKParseToken;
999+typedef struct JKPtrRange JKPtrRange;
1000+typedef struct JKObjectStack JKObjectStack;
1001+typedef struct JKBuffer JKBuffer;
1002+typedef struct JKConstBuffer JKConstBuffer;
1003+typedef struct JKConstPtrRange JKConstPtrRange;
1004+typedef struct JKRange JKRange;
1005+typedef struct JKManagedBuffer JKManagedBuffer;
1006+typedef struct JKFastClassLookup JKFastClassLookup;
1007+typedef struct JKEncodeCache JKEncodeCache;
1008+typedef struct JKEncodeState JKEncodeState;
1009+typedef struct JKObjCImpCache JKObjCImpCache;
1010+typedef struct JKHashTableEntry JKHashTableEntry;
1011+
1012+typedef id (*NSNumberAllocImp)(id receiver, SEL selector);
1013+typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value);
1014+typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object);
1015+#ifdef __BLOCKS__
1016+typedef id (^JKClassFormatterBlock)(id formatObject);
1017+#endif
1018+
1019+
1020+struct JKPtrRange {
1021+ unsigned char *ptr;
1022+ size_t length;
1023+};
1024+
1025+struct JKConstPtrRange {
1026+ const unsigned char *ptr;
1027+ size_t length;
1028+};
1029+
1030+struct JKRange {
1031+ size_t location, length;
1032+};
1033+
1034+struct JKManagedBuffer {
1035+ JKPtrRange bytes;
1036+ JKManagedBufferFlags flags;
1037+ size_t roundSizeUpToMultipleOf;
1038+};
1039+
1040+struct JKObjectStack {
1041+ void **objects, **keys;
1042+ CFHashCode *cfHashes;
1043+ size_t count, index, roundSizeUpToMultipleOf;
1044+ JKObjectStackFlags flags;
1045+};
1046+
1047+struct JKBuffer {
1048+ JKPtrRange bytes;
1049+};
1050+
1051+struct JKConstBuffer {
1052+ JKConstPtrRange bytes;
1053+};
1054+
1055+struct JKTokenValue {
1056+ JKConstPtrRange ptrRange;
1057+ JKValueType type;
1058+ JKHash hash;
1059+ union {
1060+ long long longLongValue;
1061+ unsigned long long unsignedLongLongValue;
1062+ double doubleValue;
1063+ } number;
1064+ JKTokenCacheItem *cacheItem;
1065+};
1066+
1067+struct JKParseToken {
1068+ JKConstPtrRange tokenPtrRange;
1069+ JKTokenType type;
1070+ JKTokenValue value;
1071+ JKManagedBuffer tokenBuffer;
1072+};
1073+
1074+struct JKTokenCacheItem {
1075+ void *object;
1076+ JKHash hash;
1077+ CFHashCode cfHash;
1078+ size_t size;
1079+ unsigned char *bytes;
1080+ JKValueType type;
1081+};
1082+
1083+struct JKTokenCache {
1084+ JKTokenCacheItem *items;
1085+ size_t count;
1086+ unsigned int prng_lfsr;
1087+ unsigned char age[JK_CACHE_SLOTS];
1088+};
1089+
1090+struct JKObjCImpCache {
1091+ Class NSNumberClass;
1092+ NSNumberAllocImp NSNumberAlloc;
1093+ NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong;
1094+};
1095+
1096+struct JKParseState {
1097+ JKParseOptionFlags parseOptionFlags;
1098+ JKConstBuffer stringBuffer;
1099+ size_t atIndex, lineNumber, lineStartIndex;
1100+ size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex;
1101+ JKParseToken token;
1102+ JKObjectStack objectStack;
1103+ JKTokenCache cache;
1104+ JKObjCImpCache objCImpCache;
1105+ NSError *error;
1106+ int errorIsPrev;
1107+ BOOL mutableCollections;
1108+};
1109+
1110+struct JKFastClassLookup {
1111+ void *stringClass;
1112+ void *numberClass;
1113+ void *arrayClass;
1114+ void *dictionaryClass;
1115+ void *nullClass;
1116+};
1117+
1118+struct JKEncodeCache {
1119+ id object;
1120+ size_t offset;
1121+ size_t length;
1122+};
1123+
1124+struct JKEncodeState {
1125+ JKManagedBuffer utf8ConversionBuffer;
1126+ JKManagedBuffer stringBuffer;
1127+ size_t atIndex;
1128+ JKFastClassLookup fastClassLookup;
1129+ JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS];
1130+ JKSerializeOptionFlags serializeOptionFlags;
1131+ JKEncodeOptionType encodeOption;
1132+ size_t depth;
1133+ NSError *error;
1134+ id classFormatterDelegate;
1135+ SEL classFormatterSelector;
1136+ JKClassFormatterIMP classFormatterIMP;
1137+#ifdef __BLOCKS__
1138+ JKClassFormatterBlock classFormatterBlock;
1139+#endif
1140+};
1141+
1142+// This is a JSONKit private class.
1143+@interface JKSerializer : NSObject {
1144+ JKEncodeState *encodeState;
1145+}
1146+
1147+#ifdef __BLOCKS__
1148+#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object)
1149+#else
1150+#define JKSERIALIZER_BLOCKS_PROTO id
1151+#endif
1152+
1153++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
1154+- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
1155+- (void)releaseState;
1156+
1157+@end
1158+
1159+struct JKHashTableEntry {
1160+ NSUInteger keyHash;
1161+ id key, object;
1162+};
1163+
1164+
1165+typedef uint32_t UTF32; /* at least 32 bits */
1166+typedef uint16_t UTF16; /* at least 16 bits */
1167+typedef uint8_t UTF8; /* typically 8 bits */
1168+
1169+typedef enum {
1170+ conversionOK, /* conversion successful */
1171+ sourceExhausted, /* partial character in source, but hit end */
1172+ targetExhausted, /* insuff. room in target for conversion */
1173+ sourceIllegal /* source sequence is illegal/malformed */
1174+} ConversionResult;
1175+
1176+#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
1177+#define UNI_MAX_BMP (UTF32)0x0000FFFF
1178+#define UNI_MAX_UTF16 (UTF32)0x0010FFFF
1179+#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
1180+#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
1181+#define UNI_SUR_HIGH_START (UTF32)0xD800
1182+#define UNI_SUR_HIGH_END (UTF32)0xDBFF
1183+#define UNI_SUR_LOW_START (UTF32)0xDC00
1184+#define UNI_SUR_LOW_END (UTF32)0xDFFF
1185+
1186+
1187+#if !defined(JK_FAST_TRAILING_BYTES)
1188+static const char trailingBytesForUTF8[256] = {
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+ 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,
1194+ 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,
1195+ 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,
1196+ 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
1197+};
1198+#endif
1199+
1200+static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
1201+static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
1202+
1203+#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex]))
1204+#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length]))
1205+
1206+
1207+static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection);
1208+static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex);
1209+static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject);
1210+static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex);
1211+
1212+
1213+static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count);
1214+static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection);
1215+static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary);
1216+static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary);
1217+static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary);
1218+static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry);
1219+static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object);
1220+static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey);
1221+
1222+
1223+static void _JSONDecoderCleanup(JSONDecoder *decoder);
1224+
1225+static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection);
1226+
1227+
1228+static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer);
1229+static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length);
1230+static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize);
1231+static void jk_objectStack_release(JKObjectStack *objectStack);
1232+static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count);
1233+static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount);
1234+
1235+static void jk_error(JKParseState *parseState, NSString *format, ...);
1236+static int jk_parse_string(JKParseState *parseState);
1237+static int jk_parse_number(JKParseState *parseState);
1238+static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr);
1239+JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState);
1240+JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState);
1241+static int jk_parse_next_token(JKParseState *parseState);
1242+static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String);
1243+static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex);
1244+static void *jk_parse_dictionary(JKParseState *parseState);
1245+static void *jk_parse_array(JKParseState *parseState);
1246+static void *jk_object_for_token(JKParseState *parseState);
1247+static void *jk_cachedObjects(JKParseState *parseState);
1248+JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState);
1249+JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy);
1250+
1251+
1252+static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...);
1253+static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...);
1254+static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format);
1255+static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState);
1256+static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format);
1257+static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format);
1258+static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length);
1259+JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr);
1260+JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object);
1261+static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr);
1262+
1263+#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))
1264+
1265+
1266+JK_STATIC_INLINE size_t jk_min(size_t a, size_t b);
1267+JK_STATIC_INLINE size_t jk_max(size_t a, size_t b);
1268+JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c);
1269+
1270+// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type.
1271+// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the
1272+// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection
1273+// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable.
1274+// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4.
1275+
1276+
1277+// This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23
1278+// Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly.
1279+// 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.
1280+
1281+static Class _JKArrayClass = NULL;
1282+static size_t _JKArrayInstanceSize = 0UL;
1283+static Class _JKDictionaryClass = NULL;
1284+static size_t _JKDictionaryInstanceSize = 0UL;
1285+
1286+// For JSONDecoder...
1287+static Class _jk_NSNumberClass = NULL;
1288+static NSNumberAllocImp _jk_NSNumberAllocImp = NULL;
1289+static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL;
1290+
1291+extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor));
1292+
1293+void jk_collectionClassLoadTimeInitialization(void) {
1294+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal.
1295+
1296+ _JKArrayClass = objc_getClass("JKArray");
1297+ _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass));
1298+
1299+ _JKDictionaryClass = objc_getClass("JKDictionary");
1300+ _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass));
1301+
1302+ // For JSONDecoder...
1303+ _jk_NSNumberClass = [NSNumber class];
1304+ _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)];
1305+
1306+ // Hacktacular. Need to do it this way due to the nature of class clusters.
1307+ id temp_NSNumber = [NSNumber alloc];
1308+ _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)];
1309+ [[temp_NSNumber init] release];
1310+ temp_NSNumber = NULL;
1311+
1312+ [pool release]; pool = NULL;
1313+}
1314+
1315+
1316+#pragma mark -
1317+@interface JKArray : NSMutableArray <NSCopying, NSMutableCopying, NSFastEnumeration> {
1318+ id *objects;
1319+ NSUInteger count, capacity, mutations;
1320+}
1321+@end
1322+
1323+@implementation JKArray
1324+
1325++ (id)allocWithZone:(NSZone *)zone
1326+{
1327+#pragma unused(zone)
1328+ [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])];
1329+ return(NULL);
1330+}
1331+
1332+static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) {
1333+ NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL));
1334+ JKArray *array = NULL;
1335+ if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc.
1336+ array->isa = _JKArrayClass;
1337+ if((array = [array init]) == NULL) { return(NULL); }
1338+ array->capacity = count;
1339+ array->count = count;
1340+ if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); }
1341+ memcpy(array->objects, objects, array->capacity * sizeof(id));
1342+ array->mutations = (mutableCollection == NO) ? 0UL : 1UL;
1343+ }
1344+ return(array);
1345+}
1346+
1347+// Note: The caller is responsible for -retaining the object that is to be added.
1348+static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) {
1349+ NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL));
1350+ if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; }
1351+ array->count++;
1352+ if(array->count >= array->capacity) {
1353+ array->capacity += 16UL;
1354+ id *newObjects = NULL;
1355+ if((newObjects = (id *)realloc(array->objects, sizeof(id) * array->capacity)) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; }
1356+ array->objects = newObjects;
1357+ memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count));
1358+ }
1359+ if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; }
1360+ array->objects[objectIndex] = newObject;
1361+}
1362+
1363+// Note: The caller is responsible for -retaining the object that is to be added.
1364+static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) {
1365+ NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL));
1366+ if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; }
1367+ CFRelease(array->objects[objectIndex]);
1368+ array->objects[objectIndex] = NULL;
1369+ array->objects[objectIndex] = newObject;
1370+}
1371+
1372+static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) {
1373+ NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL));
1374+ if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; }
1375+ CFRelease(array->objects[objectIndex]);
1376+ array->objects[objectIndex] = NULL;
1377+ if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count] = NULL; }
1378+ array->count--;
1379+}
1380+
1381+- (void)dealloc
1382+{
1383+ if(JK_EXPECT_T(objects != NULL)) {
1384+ NSUInteger atObject = 0UL;
1385+ for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } }
1386+ free(objects); objects = NULL;
1387+ }
1388+
1389+ [super dealloc];
1390+}
1391+
1392+- (NSUInteger)count
1393+{
1394+ NSParameterAssert((objects != NULL) && (count <= capacity));
1395+ return(count);
1396+}
1397+
1398+- (void)getObjects:(id *)objectsPtr range:(NSRange)range
1399+{
1400+ NSParameterAssert((objects != NULL) && (count <= capacity));
1401+ if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range)]; }
1402+ if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; }
1403+ memcpy(objectsPtr, objects + range.location, range.length * sizeof(id));
1404+}
1405+
1406+- (id)objectAtIndex:(NSUInteger)objectIndex
1407+{
1408+ if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1409+ NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL));
1410+ return(objects[objectIndex]);
1411+}
1412+
1413+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
1414+{
1415+ NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity));
1416+ if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
1417+ if(JK_EXPECT_F(state->state >= count)) { return(0UL); }
1418+
1419+ NSUInteger enumeratedCount = 0UL;
1420+ while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; }
1421+
1422+ return(enumeratedCount);
1423+}
1424+
1425+- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex
1426+{
1427+ if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1428+ if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1429+ if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count + 1UL]; }
1430+#ifdef __clang_analyzer__
1431+ [anObject retain]; // Stupid clang analyzer... Issue #19.
1432+#else
1433+ anObject = [anObject retain];
1434+#endif
1435+ _JKArrayInsertObjectAtIndex(self, anObject, objectIndex);
1436+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1437+}
1438+
1439+- (void)removeObjectAtIndex:(NSUInteger)objectIndex
1440+{
1441+ if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1442+ if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1443+ _JKArrayRemoveObjectAtIndex(self, objectIndex);
1444+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1445+}
1446+
1447+- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject
1448+{
1449+ if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1450+ if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1451+ if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
1452+#ifdef __clang_analyzer__
1453+ [anObject retain]; // Stupid clang analyzer... Issue #19.
1454+#else
1455+ anObject = [anObject retain];
1456+#endif
1457+ _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject);
1458+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1459+}
1460+
1461+- (id)copyWithZone:(NSZone *)zone
1462+{
1463+ NSParameterAssert((objects != NULL) && (count <= capacity));
1464+ return((mutations == 0UL) ? [self retain] : [[NSArray allocWithZone:zone] initWithObjects:objects count:count]);
1465+}
1466+
1467+- (id)mutableCopyWithZone:(NSZone *)zone
1468+{
1469+ NSParameterAssert((objects != NULL) && (count <= capacity));
1470+ return([[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
1471+}
1472+
1473+@end
1474+
1475+
1476+#pragma mark -
1477+@interface JKDictionaryEnumerator : NSEnumerator {
1478+ id collection;
1479+ NSUInteger nextObject;
1480+}
1481+
1482+- (id)initWithJKDictionary:(JKDictionary *)initDictionary;
1483+- (NSArray *)allObjects;
1484+- (id)nextObject;
1485+
1486+@end
1487+
1488+@implementation JKDictionaryEnumerator
1489+
1490+- (id)initWithJKDictionary:(JKDictionary *)initDictionary
1491+{
1492+ NSParameterAssert(initDictionary != NULL);
1493+ if((self = [super init]) == NULL) { return(NULL); }
1494+ if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); }
1495+ return(self);
1496+}
1497+
1498+- (void)dealloc
1499+{
1500+ if(collection != NULL) { CFRelease(collection); collection = NULL; }
1501+ [super dealloc];
1502+}
1503+
1504+- (NSArray *)allObjects
1505+{
1506+ NSParameterAssert(collection != NULL);
1507+ NSUInteger count = [collection count], atObject = 0UL;
1508+ id objects[count];
1509+
1510+ while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; }
1511+
1512+ return([NSArray arrayWithObjects:objects count:atObject]);
1513+}
1514+
1515+- (id)nextObject
1516+{
1517+ NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL));
1518+ JKHashTableEntry *entry = _JKDictionaryHashEntry(collection);
1519+ NSUInteger capacity = _JKDictionaryCapacity(collection);
1520+ id returnObject = NULL;
1521+
1522+ if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } }
1523+
1524+ return(returnObject);
1525+}
1526+
1527+@end
1528+
1529+#pragma mark -
1530+@interface JKDictionary : NSMutableDictionary <NSCopying, NSMutableCopying, NSFastEnumeration> {
1531+ NSUInteger count, capacity, mutations;
1532+ JKHashTableEntry *entry;
1533+}
1534+@end
1535+
1536+@implementation JKDictionary
1537+
1538++ (id)allocWithZone:(NSZone *)zone
1539+{
1540+#pragma unused(zone)
1541+ [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])];
1542+ return(NULL);
1543+}
1544+
1545+// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too.
1546+static const NSUInteger jk_dictionaryCapacities[] = {
1547+ 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL,
1548+ 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL,
1549+ 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL,
1550+ 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL,
1551+ 111638519UL, 180634607UL, 292272623UL, 472907251UL
1552+};
1553+
1554+static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) {
1555+ NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33));
1556+ while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } }
1557+ return(jk_dictionaryCapacities[bottom]);
1558+}
1559+
1560+static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
1561+ NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
1562+
1563+ NSUInteger capacityForCount = 0UL;
1564+ if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize
1565+ NSUInteger oldCapacity = dictionary->capacity;
1566+#ifndef NS_BLOCK_ASSERTIONS
1567+ NSUInteger oldCount = dictionary->count;
1568+#endif
1569+ JKHashTableEntry *oldEntry = dictionary->entry;
1570+ if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; }
1571+ dictionary->capacity = capacityForCount;
1572+ dictionary->count = 0UL;
1573+
1574+ NSUInteger idx = 0UL;
1575+ 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; } }
1576+ NSCParameterAssert((oldCount == dictionary->count));
1577+ free(oldEntry); oldEntry = NULL;
1578+ }
1579+}
1580+
1581+static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) {
1582+ NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL));
1583+ JKDictionary *dictionary = NULL;
1584+ if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc.
1585+ dictionary->isa = _JKDictionaryClass;
1586+ if((dictionary = [dictionary init]) == NULL) { return(NULL); }
1587+ dictionary->capacity = _JKDictionaryCapacityForCount(count);
1588+ dictionary->count = 0UL;
1589+
1590+ if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); }
1591+
1592+ NSUInteger idx = 0UL;
1593+ for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); }
1594+
1595+ dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL;
1596+ }
1597+ return(dictionary);
1598+}
1599+
1600+- (void)dealloc
1601+{
1602+ if(JK_EXPECT_T(entry != NULL)) {
1603+ NSUInteger atEntry = 0UL;
1604+ for(atEntry = 0UL; atEntry < capacity; atEntry++) {
1605+ if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; }
1606+ if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; }
1607+ }
1608+
1609+ free(entry); entry = NULL;
1610+ }
1611+
1612+ [super dealloc];
1613+}
1614+
1615+static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) {
1616+ NSCParameterAssert(dictionary != NULL);
1617+ return(dictionary->entry);
1618+}
1619+
1620+static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) {
1621+ NSCParameterAssert(dictionary != NULL);
1622+ return(dictionary->capacity);
1623+}
1624+
1625+static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) {
1626+ NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity));
1627+ CFRelease(entry->key); entry->key = NULL;
1628+ CFRelease(entry->object); entry->object = NULL;
1629+ entry->keyHash = 0UL;
1630+ dictionary->count--;
1631+ // 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.
1632+ NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL;
1633+ NSCParameterAssert((removeIdx < dictionary->capacity));
1634+ for(idx = 0UL; idx < dictionary->capacity; idx++) {
1635+ NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity;
1636+ JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
1637+ if(atEntry->key == NULL) { break; }
1638+ NSUInteger keyHash = atEntry->keyHash;
1639+ id key = atEntry->key, object = atEntry->object;
1640+ NSCParameterAssert(object != NULL);
1641+ atEntry->keyHash = 0UL;
1642+ atEntry->key = NULL;
1643+ atEntry->object = NULL;
1644+ NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL;
1645+ for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) {
1646+ JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)];
1647+ if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; }
1648+ }
1649+ }
1650+}
1651+
1652+static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) {
1653+ NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL));
1654+ NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL;
1655+ for(idx = 0UL; idx < dictionary->capacity; idx++) {
1656+ NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity;
1657+ JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
1658+ 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); }
1659+ 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; }
1660+ }
1661+
1662+ // We should never get here. If we do, we -release the key / object because it's our responsibility.
1663+ CFRelease(key);
1664+ CFRelease(object);
1665+}
1666+
1667+- (NSUInteger)count
1668+{
1669+ return(count);
1670+}
1671+
1672+static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) {
1673+ NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
1674+ if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); }
1675+ NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL;
1676+ JKHashTableEntry *atEntry = NULL;
1677+ for(idx = 0UL; idx < dictionary->capacity; idx++) {
1678+ atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity];
1679+ 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; }
1680+ 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.
1681+ }
1682+ return(NULL);
1683+}
1684+
1685+- (id)objectForKey:(id)aKey
1686+{
1687+ NSParameterAssert((entry != NULL) && (count <= capacity));
1688+ JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey);
1689+ return((entryForKey != NULL) ? entryForKey->object : NULL);
1690+}
1691+
1692+- (void)getObjects:(id *)objects andKeys:(id *)keys
1693+{
1694+ NSParameterAssert((entry != NULL) && (count <= capacity));
1695+ NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL;
1696+ for(atEntry = 0UL; atEntry < capacity; atEntry++) {
1697+ if(JK_EXPECT_T(entry[atEntry].key != NULL)) {
1698+ NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count));
1699+ if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; }
1700+ if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; }
1701+ arrayIdx++;
1702+ }
1703+ }
1704+}
1705+
1706+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
1707+{
1708+ NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity));
1709+ if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
1710+ if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); }
1711+
1712+ NSUInteger enumeratedCount = 0UL;
1713+ 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++; }
1714+
1715+ return(enumeratedCount);
1716+}
1717+
1718+- (NSEnumerator *)keyEnumerator
1719+{
1720+ return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]);
1721+}
1722+
1723+- (void)setObject:(id)anObject forKey:(id)aKey
1724+{
1725+ if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1726+ if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1727+ if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; }
1728+
1729+ _JKDictionaryResizeIfNeccessary(self);
1730+#ifndef __clang_analyzer__
1731+ aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak",
1732+ anObject = [anObject retain]; // but this -retain doesn't!?
1733+#endif // __clang_analyzer__
1734+ _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject);
1735+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1736+}
1737+
1738+- (void)removeObjectForKey:(id)aKey
1739+{
1740+ if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1741+ if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
1742+ JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey);
1743+ if(entryForKey != NULL) {
1744+ _JKDictionaryRemoveObjectWithEntry(self, entryForKey);
1745+ mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
1746+ }
1747+}
1748+
1749+- (id)copyWithZone:(NSZone *)zone
1750+{
1751+ NSParameterAssert((entry != NULL) && (count <= capacity));
1752+ return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]);
1753+}
1754+
1755+- (id)mutableCopyWithZone:(NSZone *)zone
1756+{
1757+ NSParameterAssert((entry != NULL) && (count <= capacity));
1758+ return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]);
1759+}
1760+
1761+@end
1762+
1763+
1764+
1765+#pragma mark -
1766+
1767+JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); }
1768+JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); }
1769+
1770+JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); }
1771+
1772+static void jk_error(JKParseState *parseState, NSString *format, ...) {
1773+ NSCParameterAssert((parseState != NULL) && (format != NULL));
1774+
1775+ va_list varArgsList;
1776+ va_start(varArgsList, format);
1777+ NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
1778+ va_end(varArgsList);
1779+
1780+#if 0
1781+ const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex;
1782+ const unsigned char *lineEnd = lineStart;
1783+ const unsigned char *atCharacterPtr = NULL;
1784+
1785+ for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } }
1786+
1787+ NSString *lineString = @"", *carretString = @"";
1788+ if(lineStart < JK_END_STRING_PTR(parseState)) {
1789+ lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease];
1790+ carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "];
1791+ }
1792+#endif
1793+
1794+ if(parseState->error == NULL) {
1795+ parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
1796+ [NSDictionary dictionaryWithObjectsAndKeys:
1797+ formatString, NSLocalizedDescriptionKey,
1798+ [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey",
1799+ [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey",
1800+ //lineString, @"JKErrorLine0Key",
1801+ //carretString, @"JKErrorLine1Key",
1802+ NULL]];
1803+ }
1804+}
1805+
1806+#pragma mark -
1807+#pragma mark Buffer and Object Stack management functions
1808+
1809+static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) {
1810+ if((managedBuffer->flags & JKManagedBufferMustFree)) {
1811+ if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; }
1812+ managedBuffer->flags &= ~JKManagedBufferMustFree;
1813+ }
1814+
1815+ managedBuffer->bytes.ptr = NULL;
1816+ managedBuffer->bytes.length = 0UL;
1817+ managedBuffer->flags &= ~JKManagedBufferLocationMask;
1818+}
1819+
1820+static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) {
1821+ jk_managedBuffer_release(managedBuffer);
1822+ managedBuffer->bytes.ptr = ptr;
1823+ managedBuffer->bytes.length = length;
1824+ managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack;
1825+}
1826+
1827+static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) {
1828+ size_t roundedUpNewSize = newSize;
1829+
1830+ if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); }
1831+
1832+ if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) {
1833+ if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) {
1834+ NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0);
1835+ unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr;
1836+
1837+ if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); }
1838+ memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize));
1839+ managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree);
1840+ managedBuffer->bytes.ptr = newBuffer;
1841+ managedBuffer->bytes.length = roundedUpNewSize;
1842+ } else {
1843+ NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap));
1844+ if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); }
1845+ managedBuffer->bytes.length = roundedUpNewSize;
1846+ }
1847+ }
1848+
1849+ return(managedBuffer->bytes.ptr);
1850+}
1851+
1852+
1853+
1854+static void jk_objectStack_release(JKObjectStack *objectStack) {
1855+ NSCParameterAssert(objectStack != NULL);
1856+
1857+ NSCParameterAssert(objectStack->index <= objectStack->count);
1858+ size_t atIndex = 0UL;
1859+ for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) {
1860+ if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; }
1861+ if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; }
1862+ }
1863+ objectStack->index = 0UL;
1864+
1865+ if(objectStack->flags & JKObjectStackMustFree) {
1866+ NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap);
1867+ if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; }
1868+ if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; }
1869+ if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; }
1870+ objectStack->flags &= ~JKObjectStackMustFree;
1871+ }
1872+
1873+ objectStack->objects = NULL;
1874+ objectStack->keys = NULL;
1875+ objectStack->cfHashes = NULL;
1876+
1877+ objectStack->count = 0UL;
1878+ objectStack->flags &= ~JKObjectStackLocationMask;
1879+}
1880+
1881+static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) {
1882+ NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL));
1883+ jk_objectStack_release(objectStack);
1884+ objectStack->objects = objects;
1885+ objectStack->keys = keys;
1886+ objectStack->cfHashes = cfHashes;
1887+ objectStack->count = count;
1888+ objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack;
1889+#ifndef NS_BLOCK_ASSERTIONS
1890+ size_t idx;
1891+ for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
1892+#endif
1893+}
1894+
1895+static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) {
1896+ size_t roundedUpNewCount = newCount;
1897+ int returnCode = 0;
1898+
1899+ void **newObjects = NULL, **newKeys = NULL;
1900+ CFHashCode *newCFHashes = NULL;
1901+
1902+ if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); }
1903+
1904+ if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) {
1905+ if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) {
1906+ NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0);
1907+
1908+ if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
1909+ memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
1910+ if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
1911+ memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
1912+
1913+ if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; }
1914+ memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode));
1915+
1916+ objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree);
1917+ objectStack->objects = newObjects; newObjects = NULL;
1918+ objectStack->keys = newKeys; newKeys = NULL;
1919+ objectStack->cfHashes = newCFHashes; newCFHashes = NULL;
1920+ objectStack->count = roundedUpNewCount;
1921+ } else {
1922+ NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap));
1923+ if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; }
1924+ if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; }
1925+ if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; }
1926+
1927+#ifndef NS_BLOCK_ASSERTIONS
1928+ size_t idx;
1929+ for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
1930+#endif
1931+ objectStack->count = roundedUpNewCount;
1932+ }
1933+ }
1934+
1935+ errorExit:
1936+ if(newObjects != NULL) { free(newObjects); newObjects = NULL; }
1937+ if(newKeys != NULL) { free(newKeys); newKeys = NULL; }
1938+ if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; }
1939+
1940+ return(returnCode);
1941+}
1942+
1943+////////////
1944+#pragma mark -
1945+#pragma mark Unicode related functions
1946+
1947+JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) {
1948+ ConversionResult result = conversionOK;
1949+ UTF32 ch = *u32CodePoint;
1950+
1951+ 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; }
1952+ 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; }
1953+ if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; }
1954+
1955+ finished:
1956+ *u32CodePoint = ch;
1957+ return(result);
1958+}
1959+
1960+
1961+static int isLegalUTF8(const UTF8 *source, size_t length) {
1962+ const UTF8 *srcptr = source + length;
1963+ UTF8 a;
1964+
1965+ switch(length) {
1966+ default: return(0); // Everything else falls through when "true"...
1967+ case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
1968+ case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
1969+ case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); }
1970+
1971+ switch(*source) { // no fall-through in this inner switch
1972+ case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break;
1973+ case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break;
1974+ case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break;
1975+ case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break;
1976+ default: if(JK_EXPECT_F(a < 0x80)) { return(0); }
1977+ }
1978+
1979+ case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); }
1980+ }
1981+
1982+ if(JK_EXPECT_F(*source > 0xF4)) { return(0); }
1983+
1984+ return(1);
1985+}
1986+
1987+static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) {
1988+ ConversionResult result = conversionOK;
1989+ const UTF8 *source = sourceStart;
1990+ UTF32 ch = 0UL;
1991+
1992+#if !defined(JK_FAST_TRAILING_BYTES)
1993+ unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
1994+#else
1995+ unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25);
1996+#endif
1997+
1998+ if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) {
1999+ source++;
2000+ while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; }
2001+ NSCParameterAssert(source <= sourceEnd);
2002+ result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal;
2003+ ch = UNI_REPLACEMENT_CHAR;
2004+ goto finished;
2005+ }
2006+
2007+ switch(extraBytesToRead) { // The cases all fall through.
2008+ case 5: ch += *source++; ch <<= 6;
2009+ case 4: ch += *source++; ch <<= 6;
2010+ case 3: ch += *source++; ch <<= 6;
2011+ case 2: ch += *source++; ch <<= 6;
2012+ case 1: ch += *source++; ch <<= 6;
2013+ case 0: ch += *source++;
2014+ }
2015+ ch -= offsetsFromUTF8[extraBytesToRead];
2016+
2017+ result = isValidCodePoint(&ch);
2018+
2019+ finished:
2020+ *nextUTF8 = source;
2021+ *convertedUTF32 = ch;
2022+
2023+ return(result);
2024+}
2025+
2026+
2027+static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) {
2028+ const UTF32 byteMask = 0xBF, byteMark = 0x80;
2029+ ConversionResult result = conversionOK;
2030+ UTF8 *target = *targetStart;
2031+ UTF32 ch = u32CodePoint;
2032+ unsigned short bytesToWrite = 0;
2033+
2034+ result = isValidCodePoint(&ch);
2035+
2036+ // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars.
2037+ if(ch < (UTF32)0x80) { bytesToWrite = 1; }
2038+ else if(ch < (UTF32)0x800) { bytesToWrite = 2; }
2039+ else if(ch < (UTF32)0x10000) { bytesToWrite = 3; }
2040+ else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; }
2041+ else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; }
2042+
2043+ target += bytesToWrite;
2044+ if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; }
2045+
2046+ switch (bytesToWrite) { // note: everything falls through.
2047+ case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2048+ case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2049+ case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
2050+ case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
2051+ }
2052+
2053+ target += bytesToWrite;
2054+
2055+ finished:
2056+ *targetStart = target;
2057+ return(result);
2058+}
2059+
2060+JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) {
2061+ UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx];
2062+ ConversionResult result;
2063+
2064+ if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } }
2065+ size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len;
2066+
2067+ while(*tokenBufferIdx < nextIdx) { *stringHash = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); }
2068+
2069+ return(0);
2070+}
2071+
2072+////////////
2073+#pragma mark -
2074+#pragma mark Decoding / parsing / deserializing functions
2075+
2076+static int jk_parse_string(JKParseState *parseState) {
2077+ NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2078+ const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1;
2079+ const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
2080+ const unsigned char *atStringCharacter = stringStart;
2081+ unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr;
2082+ size_t tokenStartIndex = parseState->atIndex;
2083+ size_t tokenBufferIdx = 0UL;
2084+
2085+ int onlySimpleString = 1, stringState = JSONStringStateStart;
2086+ uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U;
2087+ uint32_t escapedUnicodeCodePoint = 0U;
2088+ JKHash stringHash = JK_HASH_INIT;
2089+
2090+ while(1) {
2091+ unsigned long currentChar;
2092+
2093+ if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; }
2094+
2095+ if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) {
2096+ const unsigned char *nextValidCharacter = NULL;
2097+ UTF32 u32ch = 0U;
2098+ ConversionResult result;
2099+
2100+ if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; }
2101+ stringHash = calculateHash(stringHash, currentChar);
2102+ while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = calculateHash(stringHash, *atStringCharacter++); }
2103+ continue;
2104+ } else {
2105+ if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; }
2106+
2107+ if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) {
2108+ switchToSlowPath:
2109+ onlySimpleString = 0;
2110+ stringState = JSONStringStateParsing;
2111+ tokenBufferIdx = (atStringCharacter - stringStart) - 1L;
2112+ 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; } }
2113+ memcpy(tokenBuffer, stringStart, tokenBufferIdx);
2114+ goto slowMatch;
2115+ }
2116+
2117+ if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; }
2118+
2119+ stringHash = calculateHash(stringHash, currentChar);
2120+ }
2121+ }
2122+
2123+ slowMatch:
2124+
2125+ for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) {
2126+ 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; } }
2127+
2128+ NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length);
2129+
2130+ unsigned long currentChar = (*atStringCharacter), escapedChar;
2131+
2132+ if(JK_EXPECT_T(stringState == JSONStringStateParsing)) {
2133+ if(JK_EXPECT_T(currentChar >= 0x20UL)) {
2134+ if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence
2135+ if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; }
2136+ if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; }
2137+ stringHash = calculateHash(stringHash, currentChar);
2138+ tokenBuffer[tokenBufferIdx++] = currentChar;
2139+ continue;
2140+ } else { // UTF8 sequence
2141+ const unsigned char *nextValidCharacter = NULL;
2142+ UTF32 u32ch = 0U;
2143+ ConversionResult result;
2144+
2145+ if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) {
2146+ if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
2147+ if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
2148+ 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; }
2149+ atStringCharacter = nextValidCharacter - 1;
2150+ continue;
2151+ } else {
2152+ while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); }
2153+ atStringCharacter--;
2154+ continue;
2155+ }
2156+ }
2157+ } else { // currentChar < 0x20
2158+ jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing;
2159+ }
2160+
2161+ } else { // stringState != JSONStringStateParsing
2162+ int isSurrogate = 1;
2163+
2164+ switch(stringState) {
2165+ case JSONStringStateEscape:
2166+ switch(currentChar) {
2167+ case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break;
2168+
2169+ case 'b': escapedChar = '\b'; goto parsedEscapedChar;
2170+ case 'f': escapedChar = '\f'; goto parsedEscapedChar;
2171+ case 'n': escapedChar = '\n'; goto parsedEscapedChar;
2172+ case 'r': escapedChar = '\r'; goto parsedEscapedChar;
2173+ case 't': escapedChar = '\t'; goto parsedEscapedChar;
2174+ case '\\': escapedChar = '\\'; goto parsedEscapedChar;
2175+ case '/': escapedChar = '/'; goto parsedEscapedChar;
2176+ case '"': escapedChar = '"'; goto parsedEscapedChar;
2177+
2178+ parsedEscapedChar:
2179+ stringState = JSONStringStateParsing;
2180+ stringHash = calculateHash(stringHash, escapedChar);
2181+ tokenBuffer[tokenBufferIdx++] = escapedChar;
2182+ break;
2183+
2184+ default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break;
2185+ }
2186+ break;
2187+
2188+ case JSONStringStateEscapedUnicode1:
2189+ case JSONStringStateEscapedUnicode2:
2190+ case JSONStringStateEscapedUnicode3:
2191+ case JSONStringStateEscapedUnicode4: isSurrogate = 0;
2192+ case JSONStringStateEscapedUnicodeSurrogate1:
2193+ case JSONStringStateEscapedUnicodeSurrogate2:
2194+ case JSONStringStateEscapedUnicodeSurrogate3:
2195+ case JSONStringStateEscapedUnicodeSurrogate4:
2196+ {
2197+ uint16_t hexValue = 0U;
2198+
2199+ switch(currentChar) {
2200+ case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex;
2201+ case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex;
2202+ case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex;
2203+
2204+ parsedHex:
2205+ if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; }
2206+
2207+ if(stringState == JSONStringStateEscapedUnicode4) {
2208+ if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) {
2209+ if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; }
2210+ else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) {
2211+ if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
2212+ else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2213+ }
2214+ }
2215+ else { escapedUnicodeCodePoint = escapedUnicode1; }
2216+ }
2217+
2218+ if(stringState == JSONStringStateEscapedUnicodeSurrogate4) {
2219+ if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) {
2220+ if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
2221+ else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2222+ }
2223+ else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; }
2224+ }
2225+
2226+ if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) {
2227+ if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
2228+ stringState = JSONStringStateParsing;
2229+ 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; }
2230+ }
2231+ else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; }
2232+ break;
2233+
2234+ 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;
2235+ }
2236+ }
2237+ break;
2238+
2239+ case JSONStringStateEscapedNeedEscapeForSurrogate:
2240+ if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; }
2241+ else {
2242+ 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; }
2243+ 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; } }
2244+ }
2245+ break;
2246+
2247+ case JSONStringStateEscapedNeedEscapedUForSurrogate:
2248+ if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; }
2249+ else {
2250+ 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; }
2251+ 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; } }
2252+ }
2253+ break;
2254+
2255+ default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break;
2256+ }
2257+ }
2258+ }
2259+
2260+finishedParsing:
2261+
2262+ if(JK_EXPECT_T(stringState == JSONStringStateFinished)) {
2263+ NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter);
2264+
2265+ parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex;
2266+ parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr);
2267+
2268+ if(JK_EXPECT_T(onlySimpleString)) {
2269+ NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer));
2270+ parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1;
2271+ parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL;
2272+ } else {
2273+ parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr;
2274+ parseState->token.value.ptrRange.length = tokenBufferIdx;
2275+ }
2276+
2277+ parseState->token.value.hash = stringHash;
2278+ parseState->token.value.type = JKValueTypeString;
2279+ parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr);
2280+ }
2281+
2282+ if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); }
2283+ return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1);
2284+}
2285+
2286+static int jk_parse_number(JKParseState *parseState) {
2287+ NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2288+ const unsigned char *numberStart = JK_AT_STRING_PTR(parseState);
2289+ const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
2290+ const unsigned char *atNumberCharacter = NULL;
2291+ int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0;
2292+ size_t startingIndex = parseState->atIndex;
2293+
2294+ for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) {
2295+ unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL;
2296+
2297+ switch(numberState) {
2298+ case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; }
2299+ case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; }
2300+ else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; }
2301+ else { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
2302+ case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; }
2303+ case JSONNumberStateFractionalNumberStart:
2304+ case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
2305+ else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; }
2306+ else { numberState = JSONNumberStateExponent; } break; }
2307+ case JSONNumberStateWholeNumberZero:
2308+ case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; }
2309+ case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; }
2310+ case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; }
2311+ break;
2312+ default: /* XXX Add error message */ numberState = JSONNumberStateError; break;
2313+ }
2314+ }
2315+
2316+ parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex;
2317+ parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup;
2318+ parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr;
2319+
2320+ if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) {
2321+ unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL];
2322+ unsigned char *endOfNumber = NULL;
2323+
2324+ memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length);
2325+ numberTempBuf[parseState->token.tokenPtrRange.length] = 0;
2326+
2327+ errno = 0;
2328+
2329+ // Treat "-0" as a floating point number, which is capable of representing negative zeros.
2330+ if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; }
2331+
2332+ if(isFloatingPoint) {
2333+ 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).
2334+ parseState->token.value.type = JKValueTypeDouble;
2335+ parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue;
2336+ parseState->token.value.ptrRange.length = sizeof(double);
2337+ parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type);
2338+ } else {
2339+ if(isNegative) {
2340+ parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10);
2341+ parseState->token.value.type = JKValueTypeLongLong;
2342+ parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue;
2343+ parseState->token.value.ptrRange.length = sizeof(long long);
2344+ parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue;
2345+ } else {
2346+ parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10);
2347+ parseState->token.value.type = JKValueTypeUnsignedLongLong;
2348+ parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue;
2349+ parseState->token.value.ptrRange.length = sizeof(unsigned long long);
2350+ parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue;
2351+ }
2352+ }
2353+
2354+ if(JK_EXPECT_F(errno != 0)) {
2355+ numberState = JSONNumberStateError;
2356+ if(errno == ERANGE) {
2357+ switch(parseState->token.value.type) {
2358+ 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.
2359+ case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break;
2360+ case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break;
2361+ default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2362+ }
2363+ }
2364+ }
2365+ 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."); }
2366+
2367+ size_t hashIndex = 0UL;
2368+ 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]); }
2369+ }
2370+
2371+ if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); }
2372+ return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1);
2373+}
2374+
2375+JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) {
2376+ parseState->token.tokenPtrRange.ptr = ptr;
2377+ parseState->token.tokenPtrRange.length = length;
2378+ parseState->token.type = type;
2379+ parseState->atIndex += advanceBy;
2380+}
2381+
2382+static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) {
2383+ NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState)));
2384+ const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2385+
2386+ if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); }
2387+
2388+ if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); }
2389+ if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); }
2390+ if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) {
2391+ if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); }
2392+ if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); }
2393+ }
2394+
2395+ return(0UL);
2396+}
2397+
2398+JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) {
2399+ size_t newlineAdvanceAtIndex = 0UL;
2400+ 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); }
2401+ return(0);
2402+}
2403+
2404+JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) {
2405+#ifndef __clang_analyzer__
2406+ NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2407+ const unsigned char *atCharacterPtr = NULL;
2408+ const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2409+
2410+ for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
2411+ if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; }
2412+ if(jk_parse_skip_newline(parseState)) { continue; }
2413+ if(parseState->parseOptionFlags & JKParseOptionComments) {
2414+ if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) {
2415+ if((*(atCharacterPtr + 1)) == '/') {
2416+ parseState->atIndex++;
2417+ 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; } }
2418+ continue;
2419+ }
2420+ if((*(atCharacterPtr + 1)) == '*') {
2421+ parseState->atIndex++;
2422+ for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
2423+ if(jk_parse_skip_newline(parseState)) { continue; }
2424+ if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; }
2425+ }
2426+ continue;
2427+ }
2428+ }
2429+ }
2430+ break;
2431+ }
2432+#endif
2433+}
2434+
2435+static int jk_parse_next_token(JKParseState *parseState) {
2436+ NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2437+ const unsigned char *atCharacterPtr = NULL;
2438+ const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
2439+ unsigned char currentCharacter = 0U;
2440+ int stopParsing = 0;
2441+
2442+ parseState->prev_atIndex = parseState->atIndex;
2443+ parseState->prev_lineNumber = parseState->lineNumber;
2444+ parseState->prev_lineStartIndex = parseState->lineStartIndex;
2445+
2446+ jk_parse_skip_whitespace(parseState);
2447+
2448+ if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; }
2449+
2450+ if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) {
2451+ currentCharacter = *atCharacterPtr;
2452+
2453+ 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); } }
2454+ else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); }
2455+ else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); }
2456+ 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); } }
2457+ else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); }
2458+ else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); }
2459+ else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); }
2460+ else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); }
2461+
2462+ 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); } }
2463+ 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); } }
2464+ 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); } }
2465+ else { stopParsing = 1; /* XXX Add error message */ }
2466+ }
2467+
2468+ if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); }
2469+ return(stopParsing);
2470+}
2471+
2472+static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) {
2473+ NSString *acceptStrings[16];
2474+ int acceptIdx = 0;
2475+ if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; }
2476+ if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; }
2477+ if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; }
2478+ 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); }
2479+ 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); }
2480+ 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); }
2481+}
2482+
2483+static void *jk_parse_array(JKParseState *parseState) {
2484+ size_t startingObjectIndex = parseState->objectStack.index;
2485+ int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0;
2486+ void *parsedArray = NULL;
2487+
2488+ while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
2489+ 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; } }
2490+
2491+ if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) {
2492+ void *object = NULL;
2493+#ifndef NS_BLOCK_ASSERTIONS
2494+ parseState->objectStack.objects[parseState->objectStack.index] = NULL;
2495+ parseState->objectStack.keys [parseState->objectStack.index] = NULL;
2496+#endif
2497+ switch(parseState->token.type) {
2498+ case JKTokenTypeNumber:
2499+ case JKTokenTypeString:
2500+ case JKTokenTypeTrue:
2501+ case JKTokenTypeFalse:
2502+ case JKTokenTypeNull:
2503+ case JKTokenTypeArrayBegin:
2504+ case JKTokenTypeObjectBegin:
2505+ if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
2506+ 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; }
2507+ break;
2508+ 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;
2509+ case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break;
2510+ default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break;
2511+ }
2512+ }
2513+ }
2514+
2515+ 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; } } }
2516+#if !defined(NS_BLOCK_ASSERTIONS)
2517+ else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
2518+#endif
2519+
2520+ parseState->objectStack.index = startingObjectIndex;
2521+ return(parsedArray);
2522+}
2523+
2524+static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) {
2525+ void *parsedDictionary = NULL;
2526+
2527+ parseState->objectStack.index--;
2528+
2529+ parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections);
2530+
2531+ return(parsedDictionary);
2532+}
2533+
2534+static void *jk_parse_dictionary(JKParseState *parseState) {
2535+ size_t startingObjectIndex = parseState->objectStack.index;
2536+ int dictState = JKParseAcceptValueOrEnd, stopParsing = 0;
2537+ void *parsedDictionary = NULL;
2538+
2539+ while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
2540+ 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; } }
2541+
2542+ size_t objectStackIndex = parseState->objectStack.index++;
2543+ parseState->objectStack.keys[objectStackIndex] = NULL;
2544+ parseState->objectStack.objects[objectStackIndex] = NULL;
2545+ void *key = NULL, *object = NULL;
2546+
2547+ if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) {
2548+ switch(parseState->token.type) {
2549+ case JKTokenTypeString:
2550+ if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; }
2551+ if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; }
2552+ else {
2553+ parseState->objectStack.keys[objectStackIndex] = key;
2554+ 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; }
2555+ else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); }
2556+ }
2557+ break;
2558+
2559+ 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;
2560+ 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;
2561+
2562+ default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break;
2563+ }
2564+ }
2565+
2566+ if(JK_EXPECT_T(stopParsing == 0)) {
2567+ 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; } }
2568+ }
2569+
2570+ if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
2571+ switch(parseState->token.type) {
2572+ case JKTokenTypeNumber:
2573+ case JKTokenTypeString:
2574+ case JKTokenTypeTrue:
2575+ case JKTokenTypeFalse:
2576+ case JKTokenTypeNull:
2577+ case JKTokenTypeArrayBegin:
2578+ case JKTokenTypeObjectBegin:
2579+ if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
2580+ 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; }
2581+ break;
2582+ default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break;
2583+ }
2584+ }
2585+ }
2586+
2587+ 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; } } }
2588+#if !defined(NS_BLOCK_ASSERTIONS)
2589+ else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
2590+#endif
2591+
2592+ parseState->objectStack.index = startingObjectIndex;
2593+ return(parsedDictionary);
2594+}
2595+
2596+static id json_parse_it(JKParseState *parseState) {
2597+ id parsedObject = NULL;
2598+ int stopParsing = 0;
2599+
2600+ while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) {
2601+ if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
2602+ switch(parseState->token.type) {
2603+ case JKTokenTypeArrayBegin:
2604+ case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break;
2605+ default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break;
2606+ }
2607+ }
2608+ }
2609+
2610+ NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
2611+
2612+ if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); }
2613+ if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); }
2614+
2615+ if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
2616+ jk_parse_skip_whitespace(parseState);
2617+ if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
2618+ jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining.");
2619+ parsedObject = NULL;
2620+ }
2621+ }
2622+
2623+ return(parsedObject);
2624+}
2625+
2626+////////////
2627+#pragma mark -
2628+#pragma mark Object cache
2629+
2630+// 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.
2631+// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value.
2632+JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
2633+ NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U));
2634+ parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U);
2635+ parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1;
2636+}
2637+
2638+// The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts.
2639+//
2640+// 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].
2641+//
2642+// 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.
2643+// 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).
2644+// The reason for this is it allows us to perform saturated adds and subtractions and is branchless.
2645+// The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits.
2646+//
2647+// A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0.
2648+//
2649+// When an item is found in the cache, it's age is incremented.
2650+// If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items.
2651+//
2652+// If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache.
2653+
2654+static void *jk_cachedObjects(JKParseState *parseState) {
2655+ unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL;
2656+ void *parsedAtom = NULL;
2657+
2658+ if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); }
2659+
2660+ for(x = 0UL; x < JK_CACHE_PROBES; x++) {
2661+ if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; }
2662+
2663+ 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))) {
2664+ parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U;
2665+ parseState->token.value.cacheItem = &parseState->cache.items[bucket];
2666+ NSCParameterAssert(parseState->cache.items[bucket].object != NULL);
2667+ return((void *)CFRetain(parseState->cache.items[bucket].object));
2668+ } else {
2669+ if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; }
2670+ if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); }
2671+ // 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.
2672+ // 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.
2673+ 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);
2674+ }
2675+ }
2676+
2677+ switch(parseState->token.value.type) {
2678+ case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break;
2679+ case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break;
2680+ case JKValueTypeUnsignedLongLong:
2681+ if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); }
2682+ else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); }
2683+ break;
2684+ case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break;
2685+ default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2686+ }
2687+
2688+ if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) {
2689+ bucket = useableBucket;
2690+ if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; }
2691+
2692+ if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) {
2693+ memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length);
2694+ parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom);
2695+ parseState->cache.items[bucket].hash = parseState->token.value.hash;
2696+ parseState->cache.items[bucket].cfHash = 0UL;
2697+ parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length;
2698+ parseState->cache.items[bucket].type = parseState->token.value.type;
2699+ parseState->token.value.cacheItem = &parseState->cache.items[bucket];
2700+ parseState->cache.age[bucket] = JK_INIT_CACHE_AGE;
2701+ } else { // The realloc failed, so clear the appropriate fields.
2702+ parseState->cache.items[bucket].hash = 0UL;
2703+ parseState->cache.items[bucket].cfHash = 0UL;
2704+ parseState->cache.items[bucket].size = 0UL;
2705+ parseState->cache.items[bucket].type = 0UL;
2706+ }
2707+ }
2708+
2709+ return(parsedAtom);
2710+}
2711+
2712+
2713+static void *jk_object_for_token(JKParseState *parseState) {
2714+ void *parsedAtom = NULL;
2715+
2716+ parseState->token.value.cacheItem = NULL;
2717+ switch(parseState->token.type) {
2718+ case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break;
2719+ case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break;
2720+ case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break;
2721+ case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break;
2722+ case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break;
2723+ case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break;
2724+ case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break;
2725+ default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
2726+ }
2727+
2728+ return(parsedAtom);
2729+}
2730+
2731+#pragma mark -
2732+@implementation JSONDecoder
2733+
2734++ (id)decoder
2735+{
2736+ return([self decoderWithParseOptions:JKParseOptionStrict]);
2737+}
2738+
2739++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags
2740+{
2741+ return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]);
2742+}
2743+
2744+- (id)init
2745+{
2746+ return([self initWithParseOptions:JKParseOptionStrict]);
2747+}
2748+
2749+- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags
2750+{
2751+ if((self = [super init]) == NULL) { return(NULL); }
2752+
2753+ if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; }
2754+
2755+ if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; }
2756+
2757+ parseState->parseOptionFlags = parseOptionFlags;
2758+
2759+ parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL;
2760+ parseState->objectStack.roundSizeUpToMultipleOf = 2048UL;
2761+
2762+ parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass;
2763+ parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp;
2764+ parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp;
2765+
2766+ parseState->cache.prng_lfsr = 1U;
2767+ parseState->cache.count = JK_CACHE_SLOTS;
2768+ if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; }
2769+
2770+ return(self);
2771+
2772+ errorExit:
2773+ if(self) { [self autorelease]; self = NULL; }
2774+ return(NULL);
2775+}
2776+
2777+// 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.
2778+static void _JSONDecoderCleanup(JSONDecoder *decoder) {
2779+ if((decoder != NULL) && (decoder->parseState != NULL)) {
2780+ jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer);
2781+ jk_objectStack_release(&decoder->parseState->objectStack);
2782+
2783+ [decoder clearCache];
2784+ if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; }
2785+
2786+ free(decoder->parseState); decoder->parseState = NULL;
2787+ }
2788+}
2789+
2790+- (void)dealloc
2791+{
2792+ _JSONDecoderCleanup(self);
2793+ [super dealloc];
2794+}
2795+
2796+- (void)clearCache
2797+{
2798+ if(JK_EXPECT_T(parseState != NULL)) {
2799+ if(JK_EXPECT_T(parseState->cache.items != NULL)) {
2800+ size_t idx = 0UL;
2801+ for(idx = 0UL; idx < parseState->cache.count; idx++) {
2802+ if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; }
2803+ if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; }
2804+ memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem));
2805+ parseState->cache.age[idx] = 0U;
2806+ }
2807+ }
2808+ }
2809+}
2810+
2811+// This needs to be completely rewritten.
2812+static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) {
2813+ NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U));
2814+ parseState->stringBuffer.bytes.ptr = string;
2815+ parseState->stringBuffer.bytes.length = length;
2816+ parseState->atIndex = 0UL;
2817+ parseState->lineNumber = 1UL;
2818+ parseState->lineStartIndex = 0UL;
2819+ parseState->prev_atIndex = 0UL;
2820+ parseState->prev_lineNumber = 1UL;
2821+ parseState->prev_lineStartIndex = 0UL;
2822+ parseState->error = NULL;
2823+ parseState->errorIsPrev = 0;
2824+ parseState->mutableCollections = (mutableCollections == NO) ? NO : YES;
2825+
2826+ unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64);
2827+ jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer));
2828+
2829+ void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64);
2830+ void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64);
2831+ CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64);
2832+ jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS);
2833+
2834+ id parsedJSON = json_parse_it(parseState);
2835+
2836+ if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; }
2837+
2838+ jk_managedBuffer_release(&parseState->token.tokenBuffer);
2839+ jk_objectStack_release(&parseState->objectStack);
2840+
2841+ parseState->stringBuffer.bytes.ptr = NULL;
2842+ parseState->stringBuffer.bytes.length = 0UL;
2843+ parseState->atIndex = 0UL;
2844+ parseState->lineNumber = 1UL;
2845+ parseState->lineStartIndex = 0UL;
2846+ parseState->prev_atIndex = 0UL;
2847+ parseState->prev_lineNumber = 1UL;
2848+ parseState->prev_lineStartIndex = 0UL;
2849+ parseState->error = NULL;
2850+ parseState->errorIsPrev = 0;
2851+ parseState->mutableCollections = NO;
2852+
2853+ return(parsedJSON);
2854+}
2855+
2856+////////////
2857+#pragma mark Deprecated as of v1.4
2858+////////////
2859+
2860+// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
2861+- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length
2862+{
2863+ return([self objectWithUTF8String:string length:length error:NULL]);
2864+}
2865+
2866+// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
2867+- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error
2868+{
2869+ return([self objectWithUTF8String:string length:length error:error]);
2870+}
2871+
2872+// Deprecated in JSONKit v1.4. Use objectWithData: instead.
2873+- (id)parseJSONData:(NSData *)jsonData
2874+{
2875+ return([self objectWithData:jsonData error:NULL]);
2876+}
2877+
2878+// Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
2879+- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error
2880+{
2881+ return([self objectWithData:jsonData error:error]);
2882+}
2883+
2884+////////////
2885+#pragma mark Methods that return immutable collection objects
2886+////////////
2887+
2888+- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
2889+{
2890+ return([self objectWithUTF8String:string length:length error:NULL]);
2891+}
2892+
2893+- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
2894+{
2895+ if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
2896+ if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
2897+
2898+ return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error));
2899+}
2900+
2901+- (id)objectWithData:(NSData *)jsonData
2902+{
2903+ return([self objectWithData:jsonData error:NULL]);
2904+}
2905+
2906+- (id)objectWithData:(NSData *)jsonData error:(NSError **)error
2907+{
2908+ if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
2909+ return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
2910+}
2911+
2912+////////////
2913+#pragma mark Methods that return mutable collection objects
2914+////////////
2915+
2916+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
2917+{
2918+ return([self mutableObjectWithUTF8String:string length:length error:NULL]);
2919+}
2920+
2921+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
2922+{
2923+ if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
2924+ if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
2925+
2926+ return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error));
2927+}
2928+
2929+- (id)mutableObjectWithData:(NSData *)jsonData
2930+{
2931+ return([self mutableObjectWithData:jsonData error:NULL]);
2932+}
2933+
2934+- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error
2935+{
2936+ if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
2937+ return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
2938+}
2939+
2940+@end
2941+
2942+/*
2943+ The NSString and NSData convenience methods need a little bit of explanation.
2944+
2945+ Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like
2946+
2947+ const unsigned char *utf8String = (const unsigned char *)[self UTF8String];
2948+ if(utf8String == NULL) { return(NULL); }
2949+ size_t utf8Length = strlen((const char *)utf8String);
2950+ return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]);
2951+
2952+ This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is
2953+ allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed.
2954+
2955+ In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead.
2956+
2957+ 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
2958+ conversion of said string.
2959+
2960+ Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free
2961+ the buffer.
2962+
2963+ Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved
2964+ to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls
2965+ _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used
2966+ again.
2967+
2968+ If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the
2969+ autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in
2970+ autorelease limbo. It's more complicated for us, but a win for the user.
2971+
2972+ Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our
2973+ requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in
2974+ autorelease limbo, but we've done our best to minimize that impact, so it all balances out.
2975+ */
2976+
2977+@implementation NSString (JSONKitDeserializing)
2978+
2979+static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) {
2980+ id returnObject = NULL;
2981+ CFMutableDataRef mutableData = NULL;
2982+ JSONDecoder *decoder = NULL;
2983+
2984+ CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString);
2985+ NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2986+
2987+ if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) {
2988+ UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData);
2989+ CFIndex usedBytes = 0L, convertedCount = 0L;
2990+
2991+ convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes);
2992+ 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; }
2993+
2994+ if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
2995+ else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
2996+ }
2997+
2998+exitNow:
2999+ if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); }
3000+ if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
3001+ return(returnObject);
3002+}
3003+
3004+- (id)objectFromJSONString
3005+{
3006+ return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
3007+}
3008+
3009+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3010+{
3011+ return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
3012+}
3013+
3014+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3015+{
3016+ return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO));
3017+}
3018+
3019+
3020+- (id)mutableObjectFromJSONString
3021+{
3022+ return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
3023+}
3024+
3025+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3026+{
3027+ return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
3028+}
3029+
3030+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3031+{
3032+ return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES));
3033+}
3034+
3035+@end
3036+
3037+@implementation NSData (JSONKitDeserializing)
3038+
3039+- (id)objectFromJSONData
3040+{
3041+ return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
3042+}
3043+
3044+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3045+{
3046+ return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
3047+}
3048+
3049+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3050+{
3051+ JSONDecoder *decoder = NULL;
3052+ id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error];
3053+ if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
3054+ return(returnObject);
3055+}
3056+
3057+- (id)mutableObjectFromJSONData
3058+{
3059+ return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
3060+}
3061+
3062+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
3063+{
3064+ return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
3065+}
3066+
3067+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
3068+{
3069+ JSONDecoder *decoder = NULL;
3070+ id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error];
3071+ if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
3072+ return(returnObject);
3073+}
3074+
3075+
3076+@end
3077+
3078+////////////
3079+#pragma mark -
3080+#pragma mark Encoding / deserializing functions
3081+
3082+static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) {
3083+ NSCParameterAssert((encodeState != NULL) && (format != NULL));
3084+
3085+ va_list varArgsList;
3086+ va_start(varArgsList, format);
3087+ NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
3088+ va_end(varArgsList);
3089+
3090+ if(encodeState->error == NULL) {
3091+ encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
3092+ [NSDictionary dictionaryWithObjectsAndKeys:
3093+ formatString, NSLocalizedDescriptionKey,
3094+ NULL]];
3095+ }
3096+}
3097+
3098+JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) {
3099+ NSCParameterAssert(encodeState != NULL);
3100+ if(JK_EXPECT_T(cacheSlot != NULL)) {
3101+ NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex));
3102+ cacheSlot->object = object;
3103+ cacheSlot->offset = startingAtIndex;
3104+ cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex);
3105+ }
3106+}
3107+
3108+static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) {
3109+ va_list varArgsList, varArgsListCopy;
3110+ va_start(varArgsList, format);
3111+ va_copy(varArgsListCopy, varArgsList);
3112+
3113+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
3114+
3115+ ssize_t formattedStringLength = 0L;
3116+ int returnValue = 0;
3117+
3118+ 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))) {
3119+ NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length));
3120+ 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; }
3121+ 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; }
3122+ }
3123+
3124+exitNow:
3125+ va_end(varArgsList);
3126+ va_end(varArgsListCopy);
3127+ if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); }
3128+ return(returnValue);
3129+}
3130+
3131+static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) {
3132+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
3133+ 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); }
3134+
3135+ size_t formatIdx = 0UL;
3136+ for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; }
3137+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
3138+ return(0);
3139+}
3140+
3141+static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) {
3142+ NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL));
3143+ 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); }
3144+ encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n';
3145+ size_t depthWhiteSpace = 0UL;
3146+ for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
3147+ return(0);
3148+}
3149+
3150+static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) {
3151+ 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));
3152+ 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); }
3153+ encodeState->depth += depthChange;
3154+ if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
3155+ else {
3156+ if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
3157+ encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0];
3158+ if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
3159+ }
3160+ NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3161+ return(0);
3162+}
3163+
3164+static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) {
3165+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL));
3166+ if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; }
3167+ else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); }
3168+ return(0);
3169+}
3170+
3171+static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) {
3172+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex));
3173+ 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); } }
3174+ memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length);
3175+ encodeState->atIndex += length;
3176+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
3177+ return(0);
3178+}
3179+
3180+JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) {
3181+ return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) );
3182+}
3183+
3184+static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) {
3185+ NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL));
3186+
3187+ id object = (id)objectPtr, encodeCacheObject = object;
3188+ int isClass = JKClassUnknown;
3189+ size_t startingAtIndex = encodeState->atIndex;
3190+
3191+ JKHash objectHash = jk_encode_object_hash(objectPtr);
3192+ JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS];
3193+
3194+ if(JK_EXPECT_T(cacheSlot->object == object)) {
3195+ NSCParameterAssert((cacheSlot->object != NULL) &&
3196+ (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) &&
3197+ (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) &&
3198+ ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3199+ ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3200+ ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)));
3201+ 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); }
3202+ NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) &&
3203+ ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3204+ ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3205+ ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3206+ ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
3207+ ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex)));
3208+ memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length);
3209+ encodeState->atIndex += cacheSlot->length;
3210+ return(0);
3211+ }
3212+
3213+ // 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,
3214+ // 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
3215+ // supported classes, we fail the second type (i.e., double fault error).
3216+ BOOL rerunningAfterClassFormatter = NO;
3217+rerunAfterClassFormatter:
3218+ if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; }
3219+ else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; }
3220+ else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; }
3221+ else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; }
3222+ else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; }
3223+ else {
3224+ if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { encodeState->fastClassLookup.stringClass = object->isa; isClass = JKClassString; }
3225+ else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { encodeState->fastClassLookup.numberClass = object->isa; isClass = JKClassNumber; }
3226+ else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { encodeState->fastClassLookup.dictionaryClass = object->isa; isClass = JKClassDictionary; }
3227+ else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { encodeState->fastClassLookup.arrayClass = object->isa; isClass = JKClassArray; }
3228+ else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { encodeState->fastClassLookup.nullClass = object->isa; isClass = JKClassNull; }
3229+ else {
3230+ if((rerunningAfterClassFormatter == NO) && (
3231+#ifdef __BLOCKS__
3232+ ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) ||
3233+#endif
3234+ ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; }
3235+
3236+ if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); }
3237+ 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); }
3238+ }
3239+ }
3240+
3241+ // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray
3242+ // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro:
3243+ // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f))
3244+ int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1;
3245+
3246+ switch(isClass) {
3247+ case JKClassString:
3248+ {
3249+ {
3250+ const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman);
3251+ if(cStringPtr != NULL) {
3252+ const unsigned char *utf8String = cStringPtr;
3253+ size_t utf8Idx = 0UL;
3254+
3255+ CFIndex stringLength = CFStringGetLength((CFStringRef)object);
3256+ 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); }
3257+
3258+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3259+ for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) {
3260+ NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
3261+ NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3262+ if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; }
3263+ if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
3264+ switch(utf8String[utf8Idx]) {
3265+ case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
3266+ case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
3267+ case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
3268+ case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
3269+ case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
3270+ default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
3271+ }
3272+ } else {
3273+ 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++] = '\\'; }
3274+ encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
3275+ }
3276+ }
3277+ NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
3278+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3279+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
3280+ return(0);
3281+ }
3282+ }
3283+
3284+ slowUTF8Path:
3285+ {
3286+ CFIndex stringLength = CFStringGetLength((CFStringRef)object);
3287+ CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L;
3288+
3289+ 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); }
3290+
3291+ CFIndex usedBytes = 0L, convertedCount = 0L;
3292+ convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes);
3293+ 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); }
3294+
3295+ 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); }
3296+
3297+ const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr;
3298+
3299+ size_t utf8Idx = 0UL;
3300+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3301+ for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) {
3302+ NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
3303+ NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
3304+ NSCParameterAssert((CFIndex)utf8Idx < usedBytes);
3305+ if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
3306+ switch(utf8String[utf8Idx]) {
3307+ case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
3308+ case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
3309+ case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
3310+ case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
3311+ case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
3312+ default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
3313+ }
3314+ } else {
3315+ if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) {
3316+ const unsigned char *nextValidCharacter = NULL;
3317+ UTF32 u32ch = 0U;
3318+ ConversionResult result;
3319+
3320+ if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); }
3321+ else {
3322+ utf8Idx = (nextValidCharacter - utf8String) - 1UL;
3323+ if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } }
3324+ 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); } }
3325+ }
3326+ } else {
3327+ 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++] = '\\'; }
3328+ encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
3329+ }
3330+ }
3331+ }
3332+ NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
3333+ if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
3334+ jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject);
3335+ return(0);
3336+ }
3337+ }
3338+ break;
3339+
3340+ case JKClassNumber:
3341+ {
3342+ if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); }
3343+ else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); }
3344+
3345+ const char *objCType = [object objCType];
3346+ char anum[256], *aptr = &anum[255];
3347+ int isNegative = 0;
3348+ unsigned long long ullv;
3349+ long long llv;
3350+
3351+ 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); }
3352+
3353+ switch(objCType[0]) {
3354+ case 'c': case 'i': case 's': case 'l': case 'q':
3355+ if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) {
3356+ if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; }
3357+ goto convertNumber;
3358+ } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
3359+ break;
3360+ case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B':
3361+ if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) {
3362+ convertNumber:
3363+ 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); } }
3364+ if(isNegative) { *--aptr = '-'; }
3365+ NSCParameterAssert(aptr > anum);
3366+ return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr));
3367+ } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
3368+ break;
3369+ case 'f': case 'd':
3370+ {
3371+ double dv;
3372+ if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) {
3373+ 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); }
3374+ return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv));
3375+ } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); }
3376+ }
3377+ break;
3378+ default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break;
3379+ }
3380+ }
3381+ break;
3382+
3383+ case JKClassArray:
3384+ {
3385+ int printComma = 0;
3386+ CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L;
3387+ if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); }
3388+ if(JK_EXPECT_F(arrayCount > 1020L)) {
3389+ 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); } }
3390+ } else {
3391+ void *objects[1024];
3392+ CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects);
3393+ 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); } }
3394+ }
3395+ return(jk_encode_write1(encodeState, -1L, "]"));
3396+ }
3397+ break;
3398+
3399+ case JKClassDictionary:
3400+ {
3401+ int printComma = 0;
3402+ CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L;
3403+ id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object;
3404+
3405+ if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); }
3406+ if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) {
3407+ for(id keyObject in enumerateObject) {
3408+ if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
3409+ printComma = 1;
3410+ if(JK_EXPECT_F((keyObject->isa != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); }
3411+ if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); }
3412+ if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
3413+ if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); }
3414+ }
3415+ } else {
3416+ void *keys[1024], *objects[1024];
3417+ CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects);
3418+ for(idx = 0L; idx < dictionaryCount; idx++) {
3419+ if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
3420+ printComma = 1;
3421+ if(JK_EXPECT_F(((id)keys[idx])->isa != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); }
3422+ if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); }
3423+ if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
3424+ if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); }
3425+ }
3426+ }
3427+ return(jk_encode_write1(encodeState, -1L, "}"));
3428+ }
3429+ break;
3430+
3431+ case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break;
3432+
3433+ default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break;
3434+ }
3435+
3436+ return(0);
3437+}
3438+
3439+
3440+@implementation JKSerializer
3441+
3442++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3443+{
3444+ return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]);
3445+}
3446+
3447+- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3448+{
3449+#ifndef __BLOCKS__
3450+#pragma unused(block)
3451+#endif
3452+ NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) &&
3453+ (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) &&
3454+ (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1));
3455+
3456+ id returnObject = NULL;
3457+
3458+ if(encodeState != NULL) { [self releaseState]; }
3459+ if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); }
3460+
3461+ if((error != NULL) && (*error != NULL)) { *error = NULL; }
3462+
3463+ if(delegate != NULL) {
3464+ if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; }
3465+ if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; }
3466+ encodeState->classFormatterDelegate = delegate;
3467+ encodeState->classFormatterSelector = selector;
3468+ encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector];
3469+ NSCParameterAssert(encodeState->classFormatterIMP != NULL);
3470+ }
3471+
3472+#ifdef __BLOCKS__
3473+ encodeState->classFormatterBlock = block;
3474+#endif
3475+ encodeState->serializeOptionFlags = optionFlags;
3476+ encodeState->encodeOption = encodeOption;
3477+ encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL);
3478+ encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL;
3479+
3480+ unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64);
3481+ jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer));
3482+
3483+ unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64);
3484+ jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer));
3485+
3486+ 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; }
3487+ 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; }
3488+
3489+ if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) {
3490+ BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO;
3491+
3492+ if((encodeState->atIndex < 2UL))
3493+ 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; }
3494+
3495+ switch((encodeOption & JKEncodeOptionAsTypeMask)) {
3496+ case JKEncodeOptionAsData:
3497+ 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"); } }
3498+ 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"); } }
3499+ break;
3500+
3501+ case JKEncodeOptionAsString:
3502+ 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"); } }
3503+ 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"); } }
3504+ break;
3505+
3506+ default: jk_encode_error(encodeState, @"Unknown encode as type."); break;
3507+ }
3508+
3509+ if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; }
3510+ }
3511+
3512+errorExit:
3513+ if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; }
3514+ [self releaseState];
3515+
3516+ return(returnObject);
3517+}
3518+
3519+- (void)releaseState
3520+{
3521+ if(encodeState != NULL) {
3522+ jk_managedBuffer_release(&encodeState->stringBuffer);
3523+ jk_managedBuffer_release(&encodeState->utf8ConversionBuffer);
3524+ free(encodeState); encodeState = NULL;
3525+ }
3526+}
3527+
3528+- (void)dealloc
3529+{
3530+ [self releaseState];
3531+ [super dealloc];
3532+}
3533+
3534+@end
3535+
3536+@implementation NSString (JSONKitSerializing)
3537+
3538+////////////
3539+#pragma mark Methods for serializing a single NSString.
3540+////////////
3541+
3542+// 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.
3543+
3544+// NSData returning methods...
3545+
3546+- (NSData *)JSONData
3547+{
3548+ return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
3549+}
3550+
3551+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
3552+{
3553+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]);
3554+}
3555+
3556+// NSString returning methods...
3557+
3558+- (NSString *)JSONString
3559+{
3560+ return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
3561+}
3562+
3563+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
3564+{
3565+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]);
3566+}
3567+
3568+@end
3569+
3570+@implementation NSArray (JSONKitSerializing)
3571+
3572+// NSData returning methods...
3573+
3574+- (NSData *)JSONData
3575+{
3576+ return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3577+}
3578+
3579+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3580+{
3581+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3582+}
3583+
3584+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3585+{
3586+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3587+}
3588+
3589+// NSString returning methods...
3590+
3591+- (NSString *)JSONString
3592+{
3593+ return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3594+}
3595+
3596+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3597+{
3598+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3599+}
3600+
3601+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3602+{
3603+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3604+}
3605+
3606+@end
3607+
3608+@implementation NSDictionary (JSONKitSerializing)
3609+
3610+// NSData returning methods...
3611+
3612+- (NSData *)JSONData
3613+{
3614+ return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3615+}
3616+
3617+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3618+{
3619+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3620+}
3621+
3622+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3623+{
3624+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3625+}
3626+
3627+// NSString returning methods...
3628+
3629+- (NSString *)JSONString
3630+{
3631+ return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]);
3632+}
3633+
3634+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
3635+{
3636+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]);
3637+}
3638+
3639+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error
3640+{
3641+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]);
3642+}
3643+
3644+@end
3645+
3646+
3647+#ifdef __BLOCKS__
3648+
3649+@implementation NSArray (JSONKitSerializingBlockAdditions)
3650+
3651+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3652+{
3653+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3654+}
3655+
3656+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3657+{
3658+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3659+}
3660+
3661+@end
3662+
3663+@implementation NSDictionary (JSONKitSerializingBlockAdditions)
3664+
3665+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3666+{
3667+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3668+}
3669+
3670+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error
3671+{
3672+ return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]);
3673+}
3674+
3675+@end
3676+
3677+#endif // __BLOCKS__
3678+
3679
3680=== added file 'musicstreaming/Dependencies/JSONKit/README.md'
3681--- musicstreaming/Dependencies/JSONKit/README.md 1970-01-01 00:00:00 +0000
3682+++ musicstreaming/Dependencies/JSONKit/README.md 2011-07-18 14:06:59 +0000
3683@@ -0,0 +1,307 @@
3684+# JSONKit
3685+
3686+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 />
3687+Copyright &copy; 2011, John Engelhart.
3688+
3689+### A Very High Performance Objective-C JSON Library
3690+
3691+ Parsing | Serializing
3692+:---------:|:-------------:
3693+<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" />
3694+*23% Faster than Binary* <code><em>.plist</em></code>*&thinsp;!* | *549% Faster than Binary* <code><em>.plist</em></code>*&thinsp;!*
3695+
3696+* Benchmarking was performed on a MacBook Pro with a 2.66GHz Core 2.
3697+* All JSON libraries were compiled with `gcc-4.2 -DNS_BLOCK_ASSERTIONS -O3 -arch x86_64`.
3698+* Timing results are the average of 1,000 iterations of the user + system time reported by [`getrusage`][getrusage].
3699+* 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).
3700+* Since the `.plist` format does not support serializing [`NSNull`][NSNull], the `null` values in the original JSON were changed to `"null"`.
3701+* The [experimental](https://github.com/johnezang/JSONKit/tree/experimental) branch contains the `gzip` compression changes.
3702+ * JSONKit automagically links to `libz.dylib` on the fly at run time&ndash; no manual linking required.
3703+ * Parsing / deserializing will automagically decompress a buffer if it detects a `gzip` signature header.
3704+ * You can compress / `gzip` the serialized JSON by passing `JKSerializeOptionCompress` to `-JSONDataWithOptions:error:`.
3705+
3706+[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.
3707+
3708+***
3709+
3710+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][].
3711+
3712+JSON provides the following primitive types:
3713+
3714+* `null`
3715+* Boolean `true` and `false`
3716+* Number
3717+* String
3718+* Array
3719+* Object (a.k.a. Associative Arrays, Key / Value Hash Tables, Maps, Dictionaries, etc.)
3720+
3721+These primitive types are mapped to the following Objective-C Foundation classes:
3722+
3723+JSON | Objective-C
3724+-------------------|-------------
3725+`null` | [`NSNull`][NSNull]
3726+`true` and `false` | [`NSNumber`][NSNumber]
3727+Number | [`NSNumber`][NSNumber]
3728+String | [`NSString`][NSString]
3729+Array | [`NSArray`][NSArray]
3730+Object | [`NSDictionary`][NSDictionary]
3731+
3732+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].
3733+
3734+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][].
3735+
3736+### JSON To Objective-C Primitive Mapping Details
3737+
3738+* 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.
3739+
3740+ 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.
3741+
3742+ 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.***
3743+
3744+ 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:
3745+
3746+ `U+0000`.<br>
3747+ `U+D800` thru `U+DFFF`, inclusive.<br>
3748+ `U+FDD0` thru `U+FDEF`, inclusive.<br>
3749+ <code>U+<i>n</i>FFFE</code> and <code>U+<i>n</i>FFFF</code>, where *n* is from `0x0` to `0x10`
3750+
3751+ 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".
3752+
3753+ 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].
3754+
3755+ [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.
3756+
3757+ 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].
3758+
3759+* 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.
3760+
3761+ 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.
3762+
3763+* 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`.
3764+
3765+* 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.
3766+
3767+ 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.
3768+
3769+ 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.
3770+
3771+* 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.
3772+
3773+ 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`.
3774+
3775+ **See also:**<br />
3776+ &nbsp;&nbsp;&nbsp;&nbsp;[W3C - Requirements for String Identity Matching and String Indexing](http://www.w3.org/TR/charreq/#sec2)
3777+
3778+### Objective-C To JSON Primitive Mapping Details
3779+
3780+* 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.
3781+
3782+* The objects to be serialized MUST be acyclic. If the objects to be serialized contain circular references the behavior is `undefined`. For example,
3783+
3784+ ```objective-c
3785+ [arrayOne addObject:arrayTwo];
3786+ [arrayTwo addObject:arrayOne];
3787+ id json = [arrayOne JSONString];
3788+ ```
3789+
3790+ &hellip; will result in `undefined` behavior.
3791+
3792+* 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.
3793+
3794+* 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:].
3795+
3796+* 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.
3797+
3798+* 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.
3799+
3800+* 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`.
3801+
3802+* [`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.
3803+
3804+ 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.
3805+
3806+ 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.
3807+
3808+
3809+### Reporting Bugs
3810+
3811+Please use the [github.com JSONKit Issue Tracker](https://github.com/johnezang/JSONKit/issues) to report bugs.
3812+
3813+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.
3814+
3815+### Important Details
3816+
3817+* 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.
3818+
3819+* 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.
3820+
3821+* 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].
3822+
3823+* 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`.
3824+
3825+* 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.
3826+
3827+### Tips for speed
3828+
3829+* 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.
3830+
3831+* 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.
3832+
3833+* 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.
3834+
3835+* 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:
3836+ 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.
3837+ 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.
3838+
3839+* 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].
3840+
3841+* 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.
3842+
3843+### Parsing Interface
3844+
3845+#### JSONDecoder Interface
3846+
3847+The <code>objectWith&hellip;</code> methods return immutable collection objects and their respective <code>mutableObjectWith&hellip;</code> methods return mutable collection objects.
3848+
3849+**Note:** The bytes contained in a [`NSData`][NSData] object ***MUST*** be `UTF8` encoded.
3850+
3851+**Important:** Methods will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `parseOptionFlags` is not valid.
3852+**Important:** `objectWithUTF8String:` and `mutableObjectWithUTF8String:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `string` is `NULL`.
3853+**Important:** `objectWithData:` and `mutableObjectWithData:` will raise [`NSInvalidArgumentException`][NSInvalidArgumentException] if `jsonData` is `NULL`.
3854+
3855+```objective-c
3856++ (id)decoder;
3857++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3858+- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3859+
3860+- (void)clearCache;
3861+
3862+- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length;
3863+- (id)objectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error;
3864+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length;
3865+- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error;
3866+
3867+- (id)objectWithData:(NSData *)jsonData;
3868+- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
3869+- (id)mutableObjectWithData:(NSData *)jsonData;
3870+- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
3871+```
3872+
3873+#### NSString Interface
3874+
3875+```objective-c
3876+- (id)objectFromJSONString;
3877+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3878+- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3879+- (id)mutableObjectFromJSONString;
3880+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3881+- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3882+```
3883+
3884+#### NSData Interface
3885+
3886+```objective-c
3887+- (id)objectFromJSONData;
3888+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3889+- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3890+- (id)mutableObjectFromJSONData;
3891+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
3892+- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
3893+```
3894+
3895+#### JKParseOptionFlags
3896+
3897+<table>
3898+ <tr><th>Parsing Option</th><th>Description</th></tr>
3899+ <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>
3900+ <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>
3901+ <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>
3902+ <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>
3903+ <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>
3904+ <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>
3905+</table>
3906+
3907+### Serializing Interface
3908+
3909+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:
3910+
3911+Example | Result | Argument
3912+--------------|-------------------|--------------------
3913+`a "test"...` | `"a \"test\"..."` | `includeQuotes:YES`
3914+`a "test"...` | `a \"test\"...` | `includeQuotes:NO`
3915+
3916+**Note:** The [`NSString`][NSString] methods that do not include a `includeQuotes:` argument behave as if invoked with `includeQuotes:YES`.
3917+**Note:** The bytes contained in the returned [`NSData`][NSData] object are `UTF8` encoded.
3918+
3919+#### NSArray and NSDictionary Interface
3920+
3921+```objective-c
3922+- (NSData *)JSONData;
3923+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
3924+- (NSString *)JSONString;
3925+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
3926+```
3927+
3928+
3929+#### NSString Interface
3930+
3931+```objective-c
3932+- (NSData *)JSONData;
3933+- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
3934+- (NSString *)JSONString;
3935+- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
3936+```
3937+
3938+#### JKSerializeOptionFlags
3939+
3940+<table>
3941+ <tr><th>Serializing Option</th><th>Description</th></tr>
3942+ <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>
3943+ <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>
3944+ <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>
3945+ <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>
3946+</table>
3947+
3948+[JSON]: http://www.json.org/
3949+[RFC 4627]: http://tools.ietf.org/html/rfc4627
3950+[RFC 2119]: http://tools.ietf.org/html/rfc2119
3951+[Single Precision]: http://en.wikipedia.org/wiki/Single_precision_floating-point_format
3952+[Double Precision]: http://en.wikipedia.org/wiki/Double_precision_floating-point_format
3953+[wiki_invariant]: http://en.wikipedia.org/wiki/Invariant_(computer_science)
3954+[ARC]: http://clang.llvm.org/docs/AutomaticReferenceCounting.html
3955+[CFBoolean]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/index.html
3956+[kCFBooleanTrue]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanTrue
3957+[kCFBooleanFalse]: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFBooleanRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFBooleanFalse
3958+[kCFNumberDoubleType]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/doc/c_ref/kCFNumberDoubleType
3959+[CFNumberGetValue]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFNumberRef/Reference/reference.html#//apple_ref/c/func/CFNumberGetValue
3960+[Unicode Standard]: http://www.unicode.org/versions/Unicode6.0.0/
3961+[Unicode Standard - Conformance]: http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf
3962+[Unicode_equivalence]: http://en.wikipedia.org/wiki/Unicode_equivalence
3963+[UnicodeNewline]: http://en.wikipedia.org/wiki/Newline#Unicode
3964+[Unicode_UTR36]: http://www.unicode.org/reports/tr36/
3965+[Unicode_UTR36_NonVisualSecurity]: http://www.unicode.org/reports/tr36/#Canonical_Represenation
3966+[Unicode_UTR36_Deleting]: http://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters
3967+[Unicode_Security_FAQ]: http://www.unicode.org/faq/security.html
3968+[NSNull]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/index.html
3969+[NSNumber]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/index.html
3970+[NSNumber_numberWithBool]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/clm/NSNumber/numberWithBool:
3971+[NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html
3972+[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:
3973+[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:
3974+[NSString_UTF8String]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/UTF8String
3975+[NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html
3976+[NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html
3977+[NSError]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/index.html
3978+[NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html
3979+[NSMutableData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableData_Class/index.html
3980+[NSInvalidArgumentException]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException
3981+[CFString]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
3982+[NSCParameterAssert]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/macro/NSCParameterAssert
3983+[-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy
3984+[-isKindOfClass:]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html%23//apple_ref/occ/intfm/NSObject/isKindOfClass:
3985+[-objCType]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNumber/objCType
3986+[strtoll]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoll.3.html
3987+[strtod]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtod.3.html
3988+[strtoull]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strtoull.3.html
3989+[getrusage]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/getrusage.2.html
3990+[printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html
3991
3992=== added directory 'musicstreaming/Dependencies/oauthconsumer'
3993=== added directory 'musicstreaming/Dependencies/oauthconsumer/Categories'
3994=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.h'
3995--- musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.h 1970-01-01 00:00:00 +0000
3996+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.h 2011-07-18 14:06:59 +0000
3997@@ -0,0 +1,37 @@
3998+//
3999+// NSMutableURLRequest+Parameters.h
4000+//
4001+// Created by Jon Crosby on 10/19/07.
4002+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4003+//
4004+// Permission is hereby granted, free of charge, to any person obtaining a copy
4005+// of this software and associated documentation files (the "Software"), to deal
4006+// in the Software without restriction, including without limitation the rights
4007+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4008+// copies of the Software, and to permit persons to whom the Software is
4009+// furnished to do so, subject to the following conditions:
4010+//
4011+// The above copyright notice and this permission notice shall be included in
4012+// all copies or substantial portions of the Software.
4013+//
4014+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4015+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4016+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4017+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4018+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4019+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4020+// THE SOFTWARE.
4021+
4022+#import <Foundation/Foundation.h>
4023+#import "OARequestParameter.h"
4024+#import "NSURL+Base.h"
4025+
4026+
4027+@interface NSMutableURLRequest (OAParameterAdditions)
4028+
4029+@property(nonatomic, retain) NSArray *parameters;
4030+
4031+- (void)setHTTPBodyWithString:(NSString *)body;
4032+- (void)attachFileWithName:(NSString *)name filename:(NSString*)filename contentType:(NSString *)contentType data:(NSData*)data;
4033+
4034+@end
4035
4036=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.m'
4037--- musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.m 1970-01-01 00:00:00 +0000
4038+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSMutableURLRequest+Parameters.m 2011-07-18 14:06:59 +0000
4039@@ -0,0 +1,113 @@
4040+//
4041+// NSMutableURLRequest+Parameters.m
4042+//
4043+// Created by Jon Crosby on 10/19/07.
4044+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4045+//
4046+// Permission is hereby granted, free of charge, to any person obtaining a copy
4047+// of this software and associated documentation files (the "Software"), to deal
4048+// in the Software without restriction, including without limitation the rights
4049+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4050+// copies of the Software, and to permit persons to whom the Software is
4051+// furnished to do so, subject to the following conditions:
4052+//
4053+// The above copyright notice and this permission notice shall be included in
4054+// all copies or substantial portions of the Software.
4055+//
4056+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4057+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4058+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4059+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4060+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4061+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4062+// THE SOFTWARE.
4063+
4064+
4065+#import "NSMutableURLRequest+Parameters.h"
4066+
4067+static NSString *Boundary = @"-----------------------------------0xCoCoaouTHeBouNDaRy";
4068+
4069+@implementation NSMutableURLRequest (OAParameterAdditions)
4070+
4071+- (BOOL)isMultipart {
4072+ return [[self valueForHTTPHeaderField:@"Content-Type"] hasPrefix:@"multipart/form-data"];
4073+}
4074+
4075+- (NSArray *)parameters {
4076+ NSString *encodedParameters = nil;
4077+
4078+ if (![self isMultipart]) {
4079+ if ([[self HTTPMethod] isEqualToString:@"GET"] || [[self HTTPMethod] isEqualToString:@"DELETE"]) {
4080+ encodedParameters = [[self URL] query];
4081+ } else {
4082+ encodedParameters = [[[NSString alloc] initWithData:[self HTTPBody] encoding:NSASCIIStringEncoding] autorelease];
4083+ }
4084+ }
4085+
4086+ if (encodedParameters == nil || [encodedParameters isEqualToString:@""]) {
4087+ return nil;
4088+ }
4089+// NSLog(@"raw parameters %@", encodedParameters);
4090+ NSArray *encodedParameterPairs = [encodedParameters componentsSeparatedByString:@"&"];
4091+ NSMutableArray *requestParameters = [NSMutableArray arrayWithCapacity:[encodedParameterPairs count]];
4092+
4093+ for (NSString *encodedPair in encodedParameterPairs) {
4094+ NSArray *encodedPairElements = [encodedPair componentsSeparatedByString:@"="];
4095+ OARequestParameter *parameter = [[OARequestParameter alloc] initWithName:[[encodedPairElements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
4096+ value:[[encodedPairElements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
4097+ [requestParameters addObject:parameter];
4098+ [parameter release];
4099+ }
4100+
4101+ return requestParameters;
4102+}
4103+
4104+- (void)setParameters:(NSArray *)parameters
4105+{
4106+ NSMutableArray *pairs = [[[NSMutableArray alloc] initWithCapacity:[parameters count]] autorelease];
4107+ for (OARequestParameter *requestParameter in parameters) {
4108+ [pairs addObject:[requestParameter URLEncodedNameValuePair]];
4109+ }
4110+
4111+ NSString *encodedParameterPairs = [pairs componentsJoinedByString:@"&"];
4112+
4113+ if ([[self HTTPMethod] isEqualToString:@"GET"] || [[self HTTPMethod] isEqualToString:@"DELETE"]) {
4114+ [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [[self URL] URLStringWithoutQuery], encodedParameterPairs]]];
4115+ } else {
4116+ // POST, PUT
4117+ [self setHTTPBodyWithString:encodedParameterPairs];
4118+ [self setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
4119+ }
4120+}
4121+
4122+- (void)setHTTPBodyWithString:(NSString *)body {
4123+ NSData *bodyData = [body dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
4124+ [self setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"];
4125+ [self setHTTPBody:bodyData];
4126+}
4127+
4128+- (void)attachFileWithName:(NSString *)name filename:(NSString*)filename contentType:(NSString *)contentType data:(NSData*)data {
4129+
4130+ NSArray *parameters = [self parameters];
4131+ [self setValue:[@"multipart/form-data; boundary=" stringByAppendingString:Boundary] forHTTPHeaderField:@"Content-type"];
4132+
4133+ NSMutableData *bodyData = [NSMutableData new];
4134+ for (OARequestParameter *parameter in parameters) {
4135+ NSString *param = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",
4136+ Boundary, [parameter URLEncodedName], [parameter value]];
4137+
4138+ [bodyData appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];
4139+ }
4140+
4141+ NSString *filePrefix = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",
4142+ Boundary, name, filename, contentType];
4143+ [bodyData appendData:[filePrefix dataUsingEncoding:NSUTF8StringEncoding]];
4144+ [bodyData appendData:data];
4145+
4146+ [bodyData appendData:[[[@"\r\n--" stringByAppendingString:Boundary] stringByAppendingString:@"--"] dataUsingEncoding:NSUTF8StringEncoding]];
4147+ [self setValue:[NSString stringWithFormat:@"%d", [bodyData length]] forHTTPHeaderField:@"Content-Length"];
4148+ [self setHTTPBody:bodyData];
4149+ [bodyData release];
4150+}
4151+
4152+@end
4153
4154=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.h'
4155--- musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.h 1970-01-01 00:00:00 +0000
4156+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.h 2011-07-18 14:06:59 +0000
4157@@ -0,0 +1,35 @@
4158+//
4159+// NSString+URLEncoding.h
4160+//
4161+// Created by Jon Crosby on 10/19/07.
4162+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4163+//
4164+// Permission is hereby granted, free of charge, to any person obtaining a copy
4165+// of this software and associated documentation files (the "Software"), to deal
4166+// in the Software without restriction, including without limitation the rights
4167+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4168+// copies of the Software, and to permit persons to whom the Software is
4169+// furnished to do so, subject to the following conditions:
4170+//
4171+// The above copyright notice and this permission notice shall be included in
4172+// all copies or substantial portions of the Software.
4173+//
4174+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4175+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4176+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4177+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4178+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4179+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4180+// THE SOFTWARE.
4181+
4182+
4183+#import <Foundation/Foundation.h>
4184+
4185+
4186+@interface NSString (OAURLEncodingAdditions)
4187+
4188+- (NSString *)encodedURLString;
4189+- (NSString *)encodedURLParameterString;
4190+- (NSString *)decodedURLString;
4191+- (NSString *)removeQuotes;
4192+@end
4193
4194=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.m'
4195--- musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.m 1970-01-01 00:00:00 +0000
4196+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSString+URLEncoding.m 2011-07-18 14:06:59 +0000
4197@@ -0,0 +1,73 @@
4198+//
4199+// NSString+URLEncoding.m
4200+//
4201+// Created by Jon Crosby on 10/19/07.
4202+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4203+//
4204+// Permission is hereby granted, free of charge, to any person obtaining a copy
4205+// of this software and associated documentation files (the "Software"), to deal
4206+// in the Software without restriction, including without limitation the rights
4207+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4208+// copies of the Software, and to permit persons to whom the Software is
4209+// furnished to do so, subject to the following conditions:
4210+//
4211+// The above copyright notice and this permission notice shall be included in
4212+// all copies or substantial portions of the Software.
4213+//
4214+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4215+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4216+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4217+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4218+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4219+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4220+// THE SOFTWARE.
4221+
4222+
4223+#import "NSString+URLEncoding.h"
4224+
4225+
4226+@implementation NSString (OAURLEncodingAdditions)
4227+
4228+- (NSString *)encodedURLString {
4229+ NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
4230+ (CFStringRef)self,
4231+ NULL, // characters to leave unescaped (NULL = all escaped sequences are replaced)
4232+ CFSTR("?=&+"), // legal URL characters to be escaped (NULL = all legal characters are replaced)
4233+ kCFStringEncodingUTF8); // encoding
4234+ return [result autorelease];
4235+}
4236+
4237+- (NSString *)encodedURLParameterString {
4238+ NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
4239+ (CFStringRef)self,
4240+ NULL,
4241+ CFSTR(":/=,!$&'()*+;[]@#?"),
4242+ kCFStringEncodingUTF8);
4243+ return [result autorelease];
4244+}
4245+
4246+- (NSString *)decodedURLString {
4247+ NSString *result = (NSString*)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
4248+ (CFStringRef)self,
4249+ CFSTR(""),
4250+ kCFStringEncodingUTF8);
4251+
4252+ return [result autorelease];
4253+
4254+}
4255+
4256+-(NSString *)removeQuotes
4257+{
4258+ NSUInteger length = [self length];
4259+ NSString *ret = self;
4260+ if ([self characterAtIndex:0] == '"') {
4261+ ret = [ret substringFromIndex:1];
4262+ }
4263+ if ([self characterAtIndex:length - 1] == '"') {
4264+ ret = [ret substringToIndex:length - 2];
4265+ }
4266+
4267+ return ret;
4268+}
4269+
4270+@end
4271
4272=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.h'
4273--- musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.h 1970-01-01 00:00:00 +0000
4274+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.h 2011-07-18 14:06:59 +0000
4275@@ -0,0 +1,34 @@
4276+//
4277+// NSURL+Base.h
4278+// OAuthConsumer
4279+//
4280+// Created by Jon Crosby on 10/19/07.
4281+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4282+//
4283+// Permission is hereby granted, free of charge, to any person obtaining a copy
4284+// of this software and associated documentation files (the "Software"), to deal
4285+// in the Software without restriction, including without limitation the rights
4286+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4287+// copies of the Software, and to permit persons to whom the Software is
4288+// furnished to do so, subject to the following conditions:
4289+//
4290+// The above copyright notice and this permission notice shall be included in
4291+// all copies or substantial portions of the Software.
4292+//
4293+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4294+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4295+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4296+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4297+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4298+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4299+// THE SOFTWARE.
4300+
4301+
4302+#import <Foundation/Foundation.h>
4303+
4304+
4305+@interface NSURL (OABaseAdditions)
4306+
4307+- (NSString *)URLStringWithoutQuery;
4308+
4309+@end
4310
4311=== added file 'musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.m'
4312--- musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.m 1970-01-01 00:00:00 +0000
4313+++ musicstreaming/Dependencies/oauthconsumer/Categories/NSURL+Base.m 2011-07-18 14:06:59 +0000
4314@@ -0,0 +1,37 @@
4315+//
4316+// NSURL+Base.m
4317+// OAuthConsumer
4318+//
4319+// Created by Jon Crosby on 10/19/07.
4320+// Copyright 2007 Kaboomerang LLC. All rights reserved.
4321+//
4322+// Permission is hereby granted, free of charge, to any person obtaining a copy
4323+// of this software and associated documentation files (the "Software"), to deal
4324+// in the Software without restriction, including without limitation the rights
4325+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4326+// copies of the Software, and to permit persons to whom the Software is
4327+// furnished to do so, subject to the following conditions:
4328+//
4329+// The above copyright notice and this permission notice shall be included in
4330+// all copies or substantial portions of the Software.
4331+//
4332+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4333+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4334+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4335+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4336+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4337+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4338+// THE SOFTWARE.
4339+
4340+
4341+#import "NSURL+Base.h"
4342+
4343+
4344+@implementation NSURL (OABaseAdditions)
4345+
4346+- (NSString *)URLStringWithoutQuery {
4347+ NSArray *parts = [[self absoluteString] componentsSeparatedByString:@"?"];
4348+ return [parts objectAtIndex:0];
4349+}
4350+
4351+@end
4352
4353=== added directory 'musicstreaming/Dependencies/oauthconsumer/Crypto'
4354=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.c'
4355--- musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.c 1970-01-01 00:00:00 +0000
4356+++ musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.c 2011-07-18 14:06:59 +0000
4357@@ -0,0 +1,230 @@
4358+/*
4359+ * Base64Transcoder.c
4360+ * Base64Test
4361+ *
4362+ * Created by Jonathan Wight on Tue Mar 18 2003.
4363+ * Copyright (c) 2003 Toxic Software. All rights reserved.
4364+ *
4365+ * Permission is hereby granted, free of charge, to any person obtaining a copy
4366+ * of this software and associated documentation files (the "Software"), to deal
4367+ * in the Software without restriction, including without limitation the rights
4368+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4369+ * copies of the Software, and to permit persons to whom the Software is
4370+ * furnished to do so, subject to the following conditions:
4371+ *
4372+ * The above copyright notice and this permission notice shall be included in
4373+ * all copies or substantial portions of the Software.
4374+ *
4375+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4376+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4377+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4378+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4379+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4380+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4381+ * THE SOFTWARE.
4382+ *
4383+ */
4384+
4385+#include "Base64Transcoder.h"
4386+
4387+#include <math.h>
4388+#include <string.h>
4389+
4390+const u_int8_t kBase64EncodeTable[64] = {
4391+ /* 0 */ 'A', /* 1 */ 'B', /* 2 */ 'C', /* 3 */ 'D',
4392+ /* 4 */ 'E', /* 5 */ 'F', /* 6 */ 'G', /* 7 */ 'H',
4393+ /* 8 */ 'I', /* 9 */ 'J', /* 10 */ 'K', /* 11 */ 'L',
4394+ /* 12 */ 'M', /* 13 */ 'N', /* 14 */ 'O', /* 15 */ 'P',
4395+ /* 16 */ 'Q', /* 17 */ 'R', /* 18 */ 'S', /* 19 */ 'T',
4396+ /* 20 */ 'U', /* 21 */ 'V', /* 22 */ 'W', /* 23 */ 'X',
4397+ /* 24 */ 'Y', /* 25 */ 'Z', /* 26 */ 'a', /* 27 */ 'b',
4398+ /* 28 */ 'c', /* 29 */ 'd', /* 30 */ 'e', /* 31 */ 'f',
4399+ /* 32 */ 'g', /* 33 */ 'h', /* 34 */ 'i', /* 35 */ 'j',
4400+ /* 36 */ 'k', /* 37 */ 'l', /* 38 */ 'm', /* 39 */ 'n',
4401+ /* 40 */ 'o', /* 41 */ 'p', /* 42 */ 'q', /* 43 */ 'r',
4402+ /* 44 */ 's', /* 45 */ 't', /* 46 */ 'u', /* 47 */ 'v',
4403+ /* 48 */ 'w', /* 49 */ 'x', /* 50 */ 'y', /* 51 */ 'z',
4404+ /* 52 */ '0', /* 53 */ '1', /* 54 */ '2', /* 55 */ '3',
4405+ /* 56 */ '4', /* 57 */ '5', /* 58 */ '6', /* 59 */ '7',
4406+ /* 60 */ '8', /* 61 */ '9', /* 62 */ '+', /* 63 */ '/'
4407+};
4408+
4409+/*
4410+-1 = Base64 end of data marker.
4411+-2 = White space (tabs, cr, lf, space)
4412+-3 = Noise (all non whitespace, non-base64 characters)
4413+-4 = Dangerous noise
4414+-5 = Illegal noise (null byte)
4415+*/
4416+
4417+const int8_t kBase64DecodeTable[128] = {
4418+ /* 0x00 */ -5, /* 0x01 */ -3, /* 0x02 */ -3, /* 0x03 */ -3,
4419+ /* 0x04 */ -3, /* 0x05 */ -3, /* 0x06 */ -3, /* 0x07 */ -3,
4420+ /* 0x08 */ -3, /* 0x09 */ -2, /* 0x0a */ -2, /* 0x0b */ -2,
4421+ /* 0x0c */ -2, /* 0x0d */ -2, /* 0x0e */ -3, /* 0x0f */ -3,
4422+ /* 0x10 */ -3, /* 0x11 */ -3, /* 0x12 */ -3, /* 0x13 */ -3,
4423+ /* 0x14 */ -3, /* 0x15 */ -3, /* 0x16 */ -3, /* 0x17 */ -3,
4424+ /* 0x18 */ -3, /* 0x19 */ -3, /* 0x1a */ -3, /* 0x1b */ -3,
4425+ /* 0x1c */ -3, /* 0x1d */ -3, /* 0x1e */ -3, /* 0x1f */ -3,
4426+ /* ' ' */ -2, /* '!' */ -3, /* '"' */ -3, /* '#' */ -3,
4427+ /* '$' */ -3, /* '%' */ -3, /* '&' */ -3, /* ''' */ -3,
4428+ /* '(' */ -3, /* ')' */ -3, /* '*' */ -3, /* '+' */ 62,
4429+ /* ',' */ -3, /* '-' */ -3, /* '.' */ -3, /* '/' */ 63,
4430+ /* '0' */ 52, /* '1' */ 53, /* '2' */ 54, /* '3' */ 55,
4431+ /* '4' */ 56, /* '5' */ 57, /* '6' */ 58, /* '7' */ 59,
4432+ /* '8' */ 60, /* '9' */ 61, /* ':' */ -3, /* ';' */ -3,
4433+ /* '<' */ -3, /* '=' */ -1, /* '>' */ -3, /* '?' */ -3,
4434+ /* '@' */ -3, /* 'A' */ 0, /* 'B' */ 1, /* 'C' */ 2,
4435+ /* 'D' */ 3, /* 'E' */ 4, /* 'F' */ 5, /* 'G' */ 6,
4436+ /* 'H' */ 7, /* 'I' */ 8, /* 'J' */ 9, /* 'K' */ 10,
4437+ /* 'L' */ 11, /* 'M' */ 12, /* 'N' */ 13, /* 'O' */ 14,
4438+ /* 'P' */ 15, /* 'Q' */ 16, /* 'R' */ 17, /* 'S' */ 18,
4439+ /* 'T' */ 19, /* 'U' */ 20, /* 'V' */ 21, /* 'W' */ 22,
4440+ /* 'X' */ 23, /* 'Y' */ 24, /* 'Z' */ 25, /* '[' */ -3,
4441+ /* '\' */ -3, /* ']' */ -3, /* '^' */ -3, /* '_' */ -3,
4442+ /* '`' */ -3, /* 'a' */ 26, /* 'b' */ 27, /* 'c' */ 28,
4443+ /* 'd' */ 29, /* 'e' */ 30, /* 'f' */ 31, /* 'g' */ 32,
4444+ /* 'h' */ 33, /* 'i' */ 34, /* 'j' */ 35, /* 'k' */ 36,
4445+ /* 'l' */ 37, /* 'm' */ 38, /* 'n' */ 39, /* 'o' */ 40,
4446+ /* 'p' */ 41, /* 'q' */ 42, /* 'r' */ 43, /* 's' */ 44,
4447+ /* 't' */ 45, /* 'u' */ 46, /* 'v' */ 47, /* 'w' */ 48,
4448+ /* 'x' */ 49, /* 'y' */ 50, /* 'z' */ 51, /* '{' */ -3,
4449+ /* '|' */ -3, /* '}' */ -3, /* '~' */ -3, /* 0x7f */ -3
4450+};
4451+
4452+const u_int8_t kBits_00000011 = 0x03;
4453+const u_int8_t kBits_00001111 = 0x0F;
4454+const u_int8_t kBits_00110000 = 0x30;
4455+const u_int8_t kBits_00111100 = 0x3C;
4456+const u_int8_t kBits_00111111 = 0x3F;
4457+const u_int8_t kBits_11000000 = 0xC0;
4458+const u_int8_t kBits_11110000 = 0xF0;
4459+const u_int8_t kBits_11111100 = 0xFC;
4460+
4461+size_t EstimateBas64EncodedDataSize(size_t inDataSize)
4462+{
4463+size_t theEncodedDataSize = (int)ceil(inDataSize / 3.0) * 4;
4464+theEncodedDataSize = theEncodedDataSize / 72 * 74 + theEncodedDataSize % 72;
4465+return(theEncodedDataSize);
4466+}
4467+
4468+size_t EstimateBas64DecodedDataSize(size_t inDataSize)
4469+{
4470+size_t theDecodedDataSize = (int)ceil(inDataSize / 4.0) * 3;
4471+//theDecodedDataSize = theDecodedDataSize / 72 * 74 + theDecodedDataSize % 72;
4472+return(theDecodedDataSize);
4473+}
4474+
4475+bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize)
4476+{
4477+size_t theEncodedDataSize = EstimateBas64EncodedDataSize(inInputDataSize);
4478+if (*ioOutputDataSize < theEncodedDataSize)
4479+ return(false);
4480+*ioOutputDataSize = theEncodedDataSize;
4481+const u_int8_t *theInPtr = (const u_int8_t *)inInputData;
4482+u_int32_t theInIndex = 0, theOutIndex = 0;
4483+for (; theInIndex < (inInputDataSize / 3) * 3; theInIndex += 3)
4484+ {
4485+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
4486+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4];
4487+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (theInPtr[theInIndex + 2] & kBits_11000000) >> 6];
4488+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 2] & kBits_00111111) >> 0];
4489+ if (theOutIndex % 74 == 72)
4490+ {
4491+ outOutputData[theOutIndex++] = '\r';
4492+ outOutputData[theOutIndex++] = '\n';
4493+ }
4494+ }
4495+const size_t theRemainingBytes = inInputDataSize - theInIndex;
4496+if (theRemainingBytes == 1)
4497+ {
4498+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
4499+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (0 & kBits_11110000) >> 4];
4500+ outOutputData[theOutIndex++] = '=';
4501+ outOutputData[theOutIndex++] = '=';
4502+ if (theOutIndex % 74 == 72)
4503+ {
4504+ outOutputData[theOutIndex++] = '\r';
4505+ outOutputData[theOutIndex++] = '\n';
4506+ }
4507+ }
4508+else if (theRemainingBytes == 2)
4509+ {
4510+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
4511+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4];
4512+ outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (0 & kBits_11000000) >> 6];
4513+ outOutputData[theOutIndex++] = '=';
4514+ if (theOutIndex % 74 == 72)
4515+ {
4516+ outOutputData[theOutIndex++] = '\r';
4517+ outOutputData[theOutIndex++] = '\n';
4518+ }
4519+ }
4520+return(true);
4521+}
4522+
4523+bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize)
4524+{
4525+memset(ioOutputData, '.', *ioOutputDataSize);
4526+
4527+size_t theDecodedDataSize = EstimateBas64DecodedDataSize(inInputDataSize);
4528+if (*ioOutputDataSize < theDecodedDataSize)
4529+ return(false);
4530+*ioOutputDataSize = 0;
4531+const u_int8_t *theInPtr = (const u_int8_t *)inInputData;
4532+u_int8_t *theOutPtr = (u_int8_t *)ioOutputData;
4533+size_t theInIndex = 0, theOutIndex = 0;
4534+u_int8_t theOutputOctet;
4535+size_t theSequence = 0;
4536+for (; theInIndex < inInputDataSize; )
4537+ {
4538+ int8_t theSextet = 0;
4539+
4540+ int8_t theCurrentInputOctet = theInPtr[theInIndex];
4541+ theSextet = kBase64DecodeTable[theCurrentInputOctet];
4542+ if (theSextet == -1)
4543+ break;
4544+ while (theSextet == -2)
4545+ {
4546+ theCurrentInputOctet = theInPtr[++theInIndex];
4547+ theSextet = kBase64DecodeTable[theCurrentInputOctet];
4548+ }
4549+ while (theSextet == -3)
4550+ {
4551+ theCurrentInputOctet = theInPtr[++theInIndex];
4552+ theSextet = kBase64DecodeTable[theCurrentInputOctet];
4553+ }
4554+ if (theSequence == 0)
4555+ {
4556+ theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 2 & kBits_11111100;
4557+ }
4558+ else if (theSequence == 1)
4559+ {
4560+ theOutputOctet |= (theSextet >- 0 ? theSextet : 0) >> 4 & kBits_00000011;
4561+ theOutPtr[theOutIndex++] = theOutputOctet;
4562+ }
4563+ else if (theSequence == 2)
4564+ {
4565+ theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 4 & kBits_11110000;
4566+ }
4567+ else if (theSequence == 3)
4568+ {
4569+ theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 2 & kBits_00001111;
4570+ theOutPtr[theOutIndex++] = theOutputOctet;
4571+ }
4572+ else if (theSequence == 4)
4573+ {
4574+ theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 6 & kBits_11000000;
4575+ }
4576+ else if (theSequence == 5)
4577+ {
4578+ theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 0 & kBits_00111111;
4579+ theOutPtr[theOutIndex++] = theOutputOctet;
4580+ }
4581+ theSequence = (theSequence + 1) % 6;
4582+ if (theSequence != 2 && theSequence != 4)
4583+ theInIndex++;
4584+ }
4585+*ioOutputDataSize = theOutIndex;
4586+return(true);
4587+}
4588
4589=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.h'
4590--- musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.h 1970-01-01 00:00:00 +0000
4591+++ musicstreaming/Dependencies/oauthconsumer/Crypto/Base64Transcoder.h 2011-07-18 14:06:59 +0000
4592@@ -0,0 +1,36 @@
4593+/*
4594+ * Base64Transcoder.h
4595+ * Base64Test
4596+ *
4597+ * Created by Jonathan Wight on Tue Mar 18 2003.
4598+ * Copyright (c) 2003 Toxic Software. All rights reserved.
4599+ *
4600+ * Permission is hereby granted, free of charge, to any person obtaining a copy
4601+ * of this software and associated documentation files (the "Software"), to deal
4602+ * in the Software without restriction, including without limitation the rights
4603+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4604+ * copies of the Software, and to permit persons to whom the Software is
4605+ * furnished to do so, subject to the following conditions:
4606+ *
4607+ * The above copyright notice and this permission notice shall be included in
4608+ * all copies or substantial portions of the Software.
4609+ *
4610+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4611+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4612+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4613+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4614+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4615+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4616+ * THE SOFTWARE.
4617+ *
4618+ */
4619+
4620+#include <stdlib.h>
4621+#include <stdbool.h>
4622+
4623+extern size_t EstimateBas64EncodedDataSize(size_t inDataSize);
4624+extern size_t EstimateBas64DecodedDataSize(size_t inDataSize);
4625+
4626+extern bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize);
4627+extern bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize);
4628+
4629
4630=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.c'
4631--- musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.c 1970-01-01 00:00:00 +0000
4632+++ musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.c 2011-07-18 14:06:59 +0000
4633@@ -0,0 +1,86 @@
4634+//
4635+// hmac.c
4636+// OAuthConsumer
4637+//
4638+// Created by Jonathan Wight on 4/8/8.
4639+// Copyright 2008 Jonathan Wight. All rights reserved.
4640+//
4641+// Permission is hereby granted, free of charge, to any person obtaining a copy
4642+// of this software and associated documentation files (the "Software"), to deal
4643+// in the Software without restriction, including without limitation the rights
4644+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4645+// copies of the Software, and to permit persons to whom the Software is
4646+// furnished to do so, subject to the following conditions:
4647+//
4648+// The above copyright notice and this permission notice shall be included in
4649+// all copies or substantial portions of the Software.
4650+//
4651+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4652+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4653+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4654+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4655+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4656+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4657+// THE SOFTWARE.
4658+
4659+/*
4660+ * Implementation of HMAC-SHA1. Adapted from example at http://tools.ietf.org/html/rfc2104
4661+
4662+ */
4663+
4664+#include "sha1.h"
4665+
4666+#include <stdlib.h>
4667+#include <string.h>
4668+
4669+void hmac_sha1(const u_int8_t *inText, size_t inTextLength, u_int8_t* inKey, size_t inKeyLength, u_int8_t *outDigest)
4670+{
4671+#define B 64
4672+#define L 20
4673+
4674+SHA1_CTX theSHA1Context;
4675+u_int8_t k_ipad[B + 1]; /* inner padding - key XORd with ipad */
4676+u_int8_t k_opad[B + 1]; /* outer padding - key XORd with opad */
4677+
4678+/* if key is longer than 64 bytes reset it to key=SHA1 (key) */
4679+if (inKeyLength > B)
4680+ {
4681+ SHA1Init(&theSHA1Context);
4682+ SHA1Update(&theSHA1Context, inKey, inKeyLength);
4683+ SHA1Final(inKey, &theSHA1Context);
4684+ inKeyLength = L;
4685+ }
4686+
4687+/* start out by storing key in pads */
4688+memset(k_ipad, 0, sizeof k_ipad);
4689+memset(k_opad, 0, sizeof k_opad);
4690+memcpy(k_ipad, inKey, inKeyLength);
4691+memcpy(k_opad, inKey, inKeyLength);
4692+
4693+/* XOR key with ipad and opad values */
4694+int i;
4695+for (i = 0; i < B; i++)
4696+ {
4697+ k_ipad[i] ^= 0x36;
4698+ k_opad[i] ^= 0x5c;
4699+ }
4700+
4701+/*
4702+* perform inner SHA1
4703+*/
4704+SHA1Init(&theSHA1Context); /* init context for 1st pass */
4705+SHA1Update(&theSHA1Context, k_ipad, B); /* start with inner pad */
4706+SHA1Update(&theSHA1Context, (u_int8_t *)inText, inTextLength); /* then text of datagram */
4707+SHA1Final((u_int8_t *)outDigest, &theSHA1Context); /* finish up 1st pass */
4708+
4709+/*
4710+* perform outer SHA1
4711+*/
4712+SHA1Init(&theSHA1Context); /* init context for 2nd
4713+* pass */
4714+SHA1Update(&theSHA1Context, k_opad, B); /* start with outer pad */
4715+SHA1Update(&theSHA1Context, (u_int8_t *)outDigest, L); /* then results of 1st
4716+* hash */
4717+SHA1Final((u_int8_t *)outDigest, &theSHA1Context); /* finish up 2nd pass */
4718+
4719+}
4720\ No newline at end of file
4721
4722=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.h'
4723--- musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.h 1970-01-01 00:00:00 +0000
4724+++ musicstreaming/Dependencies/oauthconsumer/Crypto/hmac.h 2011-07-18 14:06:59 +0000
4725@@ -0,0 +1,31 @@
4726+//
4727+// hmac.h
4728+// OAuthConsumer
4729+//
4730+// Created by Jonathan Wight on 4/8/8.
4731+// Copyright 2008 Jonathan Wight. All rights reserved.
4732+//
4733+// Permission is hereby granted, free of charge, to any person obtaining a copy
4734+// of this software and associated documentation files (the "Software"), to deal
4735+// in the Software without restriction, including without limitation the rights
4736+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4737+// copies of the Software, and to permit persons to whom the Software is
4738+// furnished to do so, subject to the following conditions:
4739+//
4740+// The above copyright notice and this permission notice shall be included in
4741+// all copies or substantial portions of the Software.
4742+//
4743+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4744+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4745+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4746+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4747+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4748+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4749+// THE SOFTWARE.
4750+
4751+#ifndef HMAC_H
4752+#define HMAC_H 1
4753+
4754+extern void hmac_sha1(const u_int8_t *inText, size_t inTextLength, u_int8_t* inKey, const size_t inKeyLength, u_int8_t *outDigest);
4755+
4756+#endif /* HMAC_H */
4757\ No newline at end of file
4758
4759=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.c'
4760--- musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.c 1970-01-01 00:00:00 +0000
4761+++ musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.c 2011-07-18 14:06:59 +0000
4762@@ -0,0 +1,169 @@
4763+/*
4764+SHA-1 in C
4765+By Steve Reid <steve@edmweb.com>
4766+100% Public Domain
4767+
4768+Test Vectors (from FIPS PUB 180-1)
4769+"abc"
4770+ A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
4771+"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
4772+ 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
4773+A million repetitions of "a"
4774+ 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
4775+*/
4776+
4777+/* #define LITTLE_ENDIAN * This should be #define'd if true. */
4778+#if __LITTLE_ENDIAN__
4779+#define LITTLE_ENDIAN
4780+#endif
4781+/* #define SHA1HANDSOFF * Copies data before messing with it. */
4782+
4783+#include <stdio.h>
4784+#include <string.h>
4785+
4786+#include "sha1.h"
4787+
4788+void SHA1Transform(u_int32_t state[5], u_int8_t buffer[64]);
4789+
4790+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
4791+
4792+/* blk0() and blk() perform the initial expand. */
4793+/* I got the idea of expanding during the round function from SSLeay */
4794+#ifdef LITTLE_ENDIAN
4795+#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
4796+ |(rol(block->l[i],8)&0x00FF00FF))
4797+#else
4798+#define blk0(i) block->l[i]
4799+#endif
4800+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
4801+ ^block->l[(i+2)&15]^block->l[i&15],1))
4802+
4803+/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
4804+#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
4805+#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
4806+#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
4807+#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
4808+#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
4809+
4810+
4811+/* Hash a single 512-bit block. This is the core of the algorithm. */
4812+
4813+void SHA1Transform(u_int32_t state[5], u_int8_t buffer[64])
4814+{
4815+u_int32_t a, b, c, d, e;
4816+typedef union {
4817+ u_int8_t c[64];
4818+ u_int32_t l[16];
4819+} CHAR64LONG16;
4820+CHAR64LONG16* block;
4821+#ifdef SHA1HANDSOFF
4822+static u_int8_t workspace[64];
4823+ block = (CHAR64LONG16*)workspace;
4824+ memcpy(block, buffer, 64);
4825+#else
4826+ block = (CHAR64LONG16*)buffer;
4827+#endif
4828+ /* Copy context->state[] to working vars */
4829+ a = state[0];
4830+ b = state[1];
4831+ c = state[2];
4832+ d = state[3];
4833+ e = state[4];
4834+ /* 4 rounds of 20 operations each. Loop unrolled. */
4835+ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
4836+ R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
4837+ R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
4838+ R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
4839+ R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
4840+ R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
4841+ R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
4842+ R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
4843+ R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
4844+ R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
4845+ R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
4846+ R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
4847+ R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
4848+ R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
4849+ R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
4850+ R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
4851+ R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
4852+ R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
4853+ R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
4854+ R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
4855+ /* Add the working vars back into context.state[] */
4856+ state[0] += a;
4857+ state[1] += b;
4858+ state[2] += c;
4859+ state[3] += d;
4860+ state[4] += e;
4861+ /* Wipe variables */
4862+ a = b = c = d = e = 0;
4863+}
4864+
4865+
4866+/* SHA1Init - Initialize new context */
4867+
4868+void SHA1Init(SHA1_CTX* context)
4869+{
4870+ /* SHA1 initialization constants */
4871+ context->state[0] = 0x67452301;
4872+ context->state[1] = 0xEFCDAB89;
4873+ context->state[2] = 0x98BADCFE;
4874+ context->state[3] = 0x10325476;
4875+ context->state[4] = 0xC3D2E1F0;
4876+ context->count[0] = context->count[1] = 0;
4877+}
4878+
4879+
4880+/* Run your data through this. */
4881+
4882+void SHA1Update(SHA1_CTX* context, u_int8_t* data, unsigned int len)
4883+{
4884+unsigned int i, j;
4885+
4886+ j = (context->count[0] >> 3) & 63;
4887+ if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++;
4888+ context->count[1] += (len >> 29);
4889+ if ((j + len) > 63) {
4890+ memcpy(&context->buffer[j], data, (i = 64-j));
4891+ SHA1Transform(context->state, context->buffer);
4892+ for ( ; i + 63 < len; i += 64) {
4893+ SHA1Transform(context->state, &data[i]);
4894+ }
4895+ j = 0;
4896+ }
4897+ else i = 0;
4898+ memcpy(&context->buffer[j], &data[i], len - i);
4899+}
4900+
4901+
4902+/* Add padding and return the message digest. */
4903+
4904+void SHA1Final(u_int8_t digest[20], SHA1_CTX* context)
4905+{
4906+u_int32_t i, j;
4907+u_int8_t finalcount[8];
4908+
4909+ for (i = 0; i < 8; i++) {
4910+ finalcount[i] = (u_int8_t)((context->count[(i >= 4 ? 0 : 1)]
4911+ >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
4912+ }
4913+ SHA1Update(context, (u_int8_t *)"\200", 1);
4914+ while ((context->count[0] & 504) != 448) {
4915+ SHA1Update(context, (u_int8_t *)"\0", 1);
4916+ }
4917+ SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
4918+ for (i = 0; i < 20; i++) {
4919+ digest[i] = (u_int8_t)
4920+ ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
4921+ }
4922+ /* Wipe variables */
4923+ i = j = 0;
4924+ memset(context->buffer, 0, 64);
4925+ memset(context->state, 0, 20);
4926+ memset(context->count, 0, 8);
4927+ memset(&finalcount, 0, 8);
4928+#ifdef SHA1HANDSOFF /* make SHA1Transform overwrite it's own static vars */
4929+ SHA1Transform(context->state, context->buffer);
4930+#endif
4931+}
4932
4933=== added file 'musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.h'
4934--- musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.h 1970-01-01 00:00:00 +0000
4935+++ musicstreaming/Dependencies/oauthconsumer/Crypto/sha1.h 2011-07-18 14:06:59 +0000
4936@@ -0,0 +1,13 @@
4937+#include <sys/types.h>
4938+
4939+// From http://www.mirrors.wiretapped.net/security/cryptography/hashes/sha1/sha1.c
4940+
4941+typedef struct {
4942+ u_int32_t state[5];
4943+ u_int32_t count[2];
4944+ u_int8_t buffer[64];
4945+} SHA1_CTX;
4946+
4947+extern void SHA1Init(SHA1_CTX* context);
4948+extern void SHA1Update(SHA1_CTX* context, u_int8_t* data, u_int32_t len);
4949+extern void SHA1Final(u_int8_t digest[20], SHA1_CTX* context);
4950
4951=== added file 'musicstreaming/Dependencies/oauthconsumer/OAAttachment.h'
4952--- musicstreaming/Dependencies/oauthconsumer/OAAttachment.h 1970-01-01 00:00:00 +0000
4953+++ musicstreaming/Dependencies/oauthconsumer/OAAttachment.h 2011-07-18 14:06:59 +0000
4954@@ -0,0 +1,26 @@
4955+//
4956+// OAAttachment.h
4957+// Zeus
4958+//
4959+// Created by Jamie Pinkham on 2/3/11.
4960+// Copyright 2011 Tumblr. All rights reserved.
4961+//
4962+
4963+#import <Foundation/Foundation.h>
4964+
4965+
4966+@interface OAAttachment : NSObject {
4967+ NSString *name;
4968+ NSString *fileName;
4969+ NSString *contentType;
4970+ NSData *data;
4971+}
4972+
4973+@property (nonatomic, copy) NSString *name;
4974+@property (nonatomic, copy) NSString *fileName;
4975+@property (nonatomic, copy) NSString *contentType;
4976+@property (nonatomic, copy) NSData *data;
4977+
4978+- (id)initWithName:(NSString *)aName filename:(NSString *)aFilename contentType:(NSString *)aContentType data:(NSData *)aData;
4979+
4980+@end
4981
4982=== added file 'musicstreaming/Dependencies/oauthconsumer/OAAttachment.m'
4983--- musicstreaming/Dependencies/oauthconsumer/OAAttachment.m 1970-01-01 00:00:00 +0000
4984+++ musicstreaming/Dependencies/oauthconsumer/OAAttachment.m 2011-07-18 14:06:59 +0000
4985@@ -0,0 +1,33 @@
4986+//
4987+// OAAttachment.h
4988+// Zeus
4989+//
4990+// Created by Jamie Pinkham on 2/3/11.
4991+// Copyright 2011 Tumblr. All rights reserved.
4992+//
4993+
4994+#import "OAAttachment.h"
4995+
4996+@implementation OAAttachment
4997+
4998+@synthesize name, fileName, contentType, data;
4999+
5000+- (id)initWithName:(NSString *)aName filename:(NSString *)aFilename contentType:(NSString *)aContentType data:(NSData *)aData{
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches

to all changes: